import React, { useEffect, useState } from 'react';
import { Button, Card, Form, Input, message, Modal, Space, Table } from 'antd';
import {
  PlusCircleOutlined,
  CloudDownloadOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { ColumnsType } from 'antd/es/table';
import Edit from './edit';
import {
  queryExport,
  queryReportHome,
  queryReportHomeDetail,
  reportHomeAbandon,
  reportHomeSuccess,
} from '@/services/reportHome';
import Check from './check';

interface DataType {
  name: string;
  address: string;
  created_name: string;
  record_id: string;
  status: number;
}

const CommunityManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState([]);
  const [searchData, setSearchData] = useState<object | null>({});
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [editData, setEditData] = useState(null);
  const [visible, setVisible] = useState(false);
  const [checkVisible, setCheckVisible] = useState(false);
  const [checkData, setCheckData] = useState<object | null>({});

  const getList = () => {
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryReportHome(params).then((res) => {
      if (res && res.code === 0) {
        setDataList(res.data.list || []);
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    setLoading(true);
    getList();
  }, []);

  const onFinish = () => {
    form.validateFields().then((data) => {
      setLoading(true);
      setSearchData(data);
    });
  };

  const onReset = () => {
    form.resetFields();
    setLoading(true);
    setSearchData(null);
  };

  useEffect(() => {
    getList();
  }, [searchData]);

  // 分页切换
  const tableChange = () => {
    setLoading(true);
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryReportHome(params).then((res) => {
      if (res?.code === 0) {
        setDataList(res?.data?.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  //  新增弹框
  const onAdd = () => {
    setEditData(null);
    setVisible(true);
  };

  const toEdit = (record: any) => {
    setEditData(record);
    setVisible(true);
  };

  //  编辑回调
  const onEditCallback = () => {
    setVisible(false);
    getList();
  };

  //  查看弹框回调
  const checkCallback = () => {
    setCheckVisible(false);
  };

  // 导出
  const onDownLoad = () => {
    form.validateFields().then((data) => {
      queryExport(data)
        .then((res: any) => {
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = window.URL.createObjectURL(new Blob([res]));
          link.setAttribute('download', '零售报备列表.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(() => {
          message.error('导出失败');
        });
    });
  };

  // 成交
  const toDeal = (record: any) => {
    Modal.confirm({
      title: '成交',
      content: '是否确认成交？',
      onOk: () => {
        reportHomeSuccess(record.record_id)
          .then((res) => {
            if (res.code === 0) {
              message.success('成交成功');
            } else {
              message.error('成交失败');
            }
            getList();
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  // 放弃
  const toDisable = (record: any) => {
    Modal.confirm({
      title: '放弃',
      content: '是否确认放弃？',
      onOk: () => {
        reportHomeAbandon(record.record_id)
          .then((res) => {
            if (res.code === 0) {
              message.success('放弃成功');
            } else {
              message.error('放弃失败');
            }
            getList();
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  // 查看弹框
  const toCheck = (record: any) => {
    queryReportHomeDetail(record.record_id).then((res) => {
      if (res?.code === 0) {
        setCheckData(res.data);
        setCheckVisible(true);
      }
    });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, _row: any, index: number) => index + 1,
    },
    {
      title: '小区名称',
      dataIndex: 'community_name',
      key: 'community_name',
    },
    {
      title: '门牌号',
      dataIndex: 'doorplate',
      key: 'doorplate',
      render: (_, res: any) =>
        res && (
          <span>
            {res?.building}-{res?.unit}-{res?.doorplate}
          </span>
        ),
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '空调类型',
      dataIndex: 'air_conditioner_type',
      key: 'air_conditioner_type',
    },
    {
      title: '业主姓名',
      dataIndex: 'proprietor_name',
      key: 'proprietor_name',
    },
    {
      title: '成功几率',
      dataIndex: 'success_probability',
      key: 'success_probability',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v) =>
        v && <span>{{ 1: '审核未通过', 2: '审核通过', 3: '成交', 4: '放弃', 5: '丢单' }[v]}</span>,
    },
    {
      title: '跟进人',
      dataIndex: 'follow_people',
      key: 'follow_people',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toEdit(record);
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              toCheck(record);
            }}
          >
            查看
          </a>
          {record?.status === 2 && (
            <a
              style={{ color: 'green' }}
              onClick={() => {
                toDeal(record);
              }}
            >
              成交
            </a>
          )}
          {record?.status === 2 && (
            <a
              style={{ color: 'red' }}
              onClick={() => {
                toDisable(record);
              }}
            >
              放弃
            </a>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <div>
        <Card>
          <Form form={form} layout="inline" onFinish={onFinish}>
            <Form.Item name="like_name" label="小区名称">
              <Input placeholder="请输入小区名称" />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  <SearchOutlined />
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  <ReloadOutlined />
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
          <Button htmlType="button" type="primary" style={{ margin: '20px 0' }} onClick={onAdd}>
            <PlusCircleOutlined />
            新增报备
          </Button>
          <Button htmlType="button" style={{ margin: '20px 10px' }} onClick={onDownLoad}>
            <CloudDownloadOutlined />
            导出
          </Button>
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey={(record) => record.record_id}
            pagination={pagination}
            loading={loading}
            onChange={tableChange}
          />
          {visible && <Edit editCallback={onEditCallback} params={editData} visible={visible} />}
          {checkVisible && (
            <Check visible={checkVisible} data={checkData} checkCallback={checkCallback} />
          )}
        </Card>
      </div>
    </PageContainer>
  );
};
export default CommunityManagement;
