import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, Form, Input, Space, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { queryDeviceFaults, queryDeviceFaultsDetail } from '@/services/DeviceFaults';
import moment from 'moment';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import UpdateFaults from '@/pages/DeviceFaults/updateFaults';
import Check from '@/pages/DeviceFaults/check';

interface DataType {
  key: React.ReactNode;
  user_name: string;
  record_id: string;
  device_code: string;
  code: string;
  desc: string;
  created_at: string;
  status: number;
}

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

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

  // 初始化数据
  useEffect(() => {
    setLoading(true);
    getList();
  }, []);

  //  更新
  const toUpdate = (record: any) => {
    queryDeviceFaultsDetail(record.record_id).then((res) => {
      if (res && res.code === 0) {
        setVisible(true);
        setFaultsData(res.data);
      }
    });
  };

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

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

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

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

  // 更新回调
  const onFaultsCallback = () => {
    setVisible(false);
    getList();
    setFaultsData(null);
  };

  //  查看详情
  const onCheck = (record: any) => {
    setCheckVisible(true);
    setCheckData(record);
  };

  const onCheckCallback = () => {
    setCheckVisible(false);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '设备编号',
      dataIndex: 'device_code',
      key: 'device_code',
    },
    {
      title: '故障码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '故障描述',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '故障状态',
      dataIndex: 'status',
      key: 'status',
      render: (v) => <span>{{ 0: '未处理', 1: '已处理' }[v]}</span>,
    },
    {
      title: '上报时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (v) => v && <span>{moment(v).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '客户名称',
      dataIndex: 'user_name',
      key: 'user_name',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toUpdate(record);
            }}
          >
            更新
          </a>
          <a
            onClick={() => {
              onCheck(record);
            }}
          >
            查看详情
          </a>
        </Space>
      ),
    },
  ];

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

  return (
    <PageContainer>
      <div>
        <Card>
          <Form form={form} layout="inline" onFinish={onFinish}>
            <Form.Item name="device_code" 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>
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey={(record) => record.record_id}
            pagination={paginationProps}
            loading={loading}
            onChange={tableChange}
          />

          {visible && faultsData && (
            <UpdateFaults visible={visible} params={faultsData} editCallback={onFaultsCallback} />
          )}
          {checkVisible && (
            <Check params={checkData} visible={checkVisible} callback={onCheckCallback} />
          )}
        </Card>
      </div>
    </PageContainer>
  );
};
export default DeviceFaults;
