import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, DatePicker, Form, Input, message, Space, Table } from 'antd';
import { ReloadOutlined, SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { queryAfterSalesSupport } from '@/services/afterSales/afterSalesSupport';
import moment from 'moment';
import { queryExport } from '@/services/afterSales/afterSalesSupport';
import Check from '@/pages/AfterSales/AfterSalesSupport/check';

interface DataType {
  name: string;
  phone: string;
  address: string;
  dealer_name: string;
  record_id: string;
}

/**
 * 售后支持
 * @constructor
 */
const AfterSalesSupport: React.FC = () => {
  const [form] = Form.useForm();
  const [dataList, setDataList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [searchData, setSearchData] = useState<object | null>({});
  const [checkVisible, setCheckVisible] = useState(false);
  const [checkData, setCheckData] = useState(null);

  // 获取列表信息
  const getList = () => {
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryAfterSalesSupport(params).then((res) => {
      if (res && res.code === 0) {
        setDataList(res.data.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

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

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

  // 搜索
  const onFinish = () => {
    form.validateFields().then((data) => {
      setLoading(true);
      const time = moment(data.time).format('YYYY-MM-DD');
      setSearchData({
        ...searchData,
        ...data,
        time: time,
      });
    });
  };

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

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

  // 导出
  const onExport = () => {
    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 toDetail = (record: any) => {
    setCheckVisible(true);
    setCheckData(record.record_id);
  };

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

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      width: 80,
      render: (_: any, _row: any, index: number) => index + 1,
    },
    {
      title: '用户名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '用户电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 100,
    },
    {
      title: '用户地址',
      dataIndex: 'address',
      key: 'address',
      width: 300,
      render: (v) => {
        const item = JSON.parse(v).join(' ');
        return <div>{item}</div>;
      },
    },
    {
      title: '经销商单位',
      dataIndex: 'dealer_name',
      key: 'dealer_name',
      width: 300,
    },
    {
      title: '机器条码编号',
      dataIndex: 'machine_code',
      key: 'machine_code',
      width: 300,
    },
    {
      title: '录入人',
      dataIndex: 'installer_name',
      key: 'installer_name',
      width: 300,
    },
    {
      title: '提交时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (v) => v && <span>{moment(v).format('YYYY-MM-DD HH:mm')}</span>,
      width: 300,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 300,
      render: (v) =>
        v && (
          <span style={{ color: `${{ 1: 'red', 2: '#00a650', 3: '#d78f11' }[v]}` }}>
            {{ 1: '草稿', 2: '已完成', 3: '隐蔽验收完成' }[v]}
          </span>
        ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toDetail(record);
            }}
          >
            详情
          </a>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <div>
        <Card>
          <Form form={form} layout="inline" onFinish={onFinish}>
            <Form.Item name="user_name" label="用户名称">
              <Input placeholder="请输入用户名称" />
            </Form.Item>
            <Form.Item name="user_phone" label="用户电话">
              <Input placeholder="请输入用户电话" />
            </Form.Item>
            <Form.Item name="user_address" label="地址">
              <Input placeholder="请输入地址" />
            </Form.Item>
            <Form.Item name="machine_code" label="机器条码编号">
              <Input placeholder="请输入机器条码编号" />
            </Form.Item>
            <Form.Item name="dealer_name" label="经销商单位">
              <Input placeholder="请输入经销商单位" />
            </Form.Item>
            <Form.Item name="time" label="经销商单位">
              <DatePicker />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  <SearchOutlined />
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  <ReloadOutlined />
                  重置
                </Button>
                <Button type="dashed" onClick={onExport}>
                  <DownloadOutlined />
                  导出
                </Button>
              </Space>
            </Form.Item>
          </Form>
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey={(record) => record.record_id}
            pagination={pagination}
            loading={loading}
            onChange={tableChange}
          />

          {checkVisible && (
            <Check params={checkData} visible={checkVisible} callback={onCheckCallback} />
          )}
        </Card>
      </div>
    </PageContainer>
  );
};
export default AfterSalesSupport;
