import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, DatePicker, Form, Input, message, Modal, Select, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { PlusCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  infoQuery,
  reportingAbandon,
  reportingDetailQuery,
  reportingQuery,
  reportingSuccess,
  salesQuery,
} from '@/services/ReportingManagement';
import Edit from './edit';
import Check from './check';
import moment from 'moment';

const { RangePicker } = DatePicker;

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

/**
 * 报备管理
 * @constructor
 */
const ReportingManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [detailData, setDetailData] = useState<object | null>({});
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState([]);
  const [searchData, setSearchData] = useState<object | null>({});
  const [visible, setVisible] = useState(false);
  const [salesmanList, setSalesmanList] = useState([]);
  const [checkVisible, setCheckVisible] = useState(false);
  const [checkData, setCheckData] = useState<object | null>({});

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

  const getSalesList = (id: string) => {
    const params = {
      q: 'list',
      status: 1,
      parent_id: id,
    };
    salesQuery(params).then((res) => {
      if (res?.code === 0) {
        setSalesmanList(res?.data || []);
      }
    });
  };

  const getUserInfo = () => {
    infoQuery().then((res) => {
      if (res?.code === 0) {
        getSalesList(res.data.record_id);
      }
    });
  };

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

  // 搜索
  const onFinish = () => {
    form.validateFields().then((data) => {
      const params: any = {};
      if (data.project_name) {
        params.project_name = data.project_name;
      }
      if (data.status) {
        params.status = data.status;
      }
      if (data.user_id) {
        params.user_id = data.user_id;
      }
      if (data.time) {
        params.time_start = moment(data.time[0]).format('YYYY-MM-DD');
        params.time_end = moment(data.time[1]).format('YYYY-MM-DD');
      }
      setLoading(true);
      setSearchData(params);
    });
  };

  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,
    };
    reportingQuery(params).then((res) => {
      if (res?.code === 0) {
        setDataList(res?.data?.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  // 新增
  const onAdd = () => {
    setVisible(true);
    setDetailData(null);
  };

  // 编辑弹框
  const toEdit = (record: any) => {
    reportingDetailQuery(record.record_id).then((res) => {
      if (res?.code === 0) {
        setDetailData(record || null);
        setVisible(true);
      }
    });
  };

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

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

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

  // 成交
  const toDeal = (record: any) => {
    Modal.confirm({
      title: '成交',
      content: '是否确认成交？',
      onOk: () => {
        reportingSuccess(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: () => {
        reportingAbandon(record.record_id)
          .then((res) => {
            if (res.code === 0) {
              message.success('放弃成功');
            } else {
              message.error('放弃失败');
            }
            getList();
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '工程名称',
      dataIndex: 'project_name',
      key: 'project_name',
    },
    {
      title: '城市',
      dataIndex: 'city',
      key: 'city',
      render: (_, data: any) => (
        <span>{`${data.province}` + ' ' + `${data.city}` + ' ' + `${data.district}`}</span>
      ),
    },
    {
      title: '甲方联系人',
      dataIndex: 'contact_person',
      key: 'contact_person',
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '跟进人',
      dataIndex: 'follow_people',
      key: 'follow_people',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v) =>
        v && <span>{{ 1: '审核未通过', 2: '审核通过', 3: '成交', 4: '放弃', 5: '丢单' }[v]}</span>,
    },
    {
      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>
      ),
    },
  ];

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => {
      return <span> 共 {total}条 </span>;
    },
    ...pagination,
  };

  return (
    <PageContainer>
      <Card>
        <Form form={form} layout="inline" onFinish={onFinish}>
          <Form.Item name="project_name" label="工程名称">
            <Input placeholder="请输入工程名称" />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select style={{ width: '175px' }} placeholder="请选择状态">
              <Select.Option key={2} value={2}>
                审核通过
              </Select.Option>
              <Select.Option key={3} value={3}>
                成交
              </Select.Option>
              <Select.Option key={4} value={4}>
                放弃
              </Select.Option>
              <Select.Option key={5} value={5}>
                丢单
              </Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="user_id" label="业务员">
            <Select style={{ width: '175px' }} placeholder="请选择业务员">
              {salesmanList && salesmanList.length
                ? salesmanList.map((res: any) => {
                    return (
                      <Select.Option key={res?.record_id} value={res?.record_id}>
                        {res?.user_name}
                      </Select.Option>
                    );
                  })
                : null}
            </Select>
          </Form.Item>
          <Form.Item name="time" label="时间">
            <RangePicker />
          </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>
        <Table
          columns={columns}
          dataSource={dataList}
          rowKey={(record) => record.record_id}
          pagination={paginationProps}
          loading={loading}
          onChange={tableChange}
        />
      </Card>
      {visible && <Edit detailData={detailData} editCallback={onEditCallback} visible={visible} />}
      {checkVisible && (
        <Check visible={checkVisible} data={checkData} checkCallback={checkCallback} />
      )}
    </PageContainer>
  );
};
export default ReportingManagement;
