import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Button, Card, Form, Input, message, Modal, Space, Table } from 'antd';
import { PlusCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import Edit from '@/pages/Infrared/remote/edit';
import type { ColumnsType } from 'antd/es/table';
import { delInfraredRemote, queryInfraredRemote } from '@/services/Infrared/remote';

interface DataType {
  key: React.ReactNode;
  name: string;
  record_id: string;
  remote: string;
  category_name: string;
  brand_name: string;
}

/**
 * 红外 - 码库管理
 * @constructor
 */
const CodeLibrary: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [dataList, setDataList] = useState([]);
  const [searchData, setSearchData] = useState<object | null>({});
  const [visible, setVisible] = useState(false);
  const [editData, setEditData] = useState(null);

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

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

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

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

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

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

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

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

  // 删除
  const toDel = (record: any) => {
    Modal.confirm({
      title: '删除',
      content: `确认删除码库：[${record.name}]`,
      onOk: () => {
        setLoading(true);
        delInfraredRemote(record.record_id)
          .then((res) => {
            if (res && res.code === 0) {
              message.success('删除成功');
              getList();
            } else {
              message.error('删除失败');
            }
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

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

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '控制编码',
      dataIndex: 'remote',
      key: 'remote',
    },
    {
      title: '编码对应文件名称',
      dataIndex: 'remote_map',
      key: 'remote_map',
    },
    {
      title: '所属类型',
      dataIndex: 'category_name',
      key: 'category_name',
    },
    {
      title: '所属品牌',
      dataIndex: 'brand_name',
      key: 'brand_name',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toEdit(record);
            }}
          >
            编辑
          </a>
          <a
            style={{ color: 'red' }}
            onClick={() => {
              toDel(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="category_name" label="类型名称">
              <Input placeholder="请输入类型名称" />
            </Form.Item>
            <Form.Item name="brand_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>
        </Card>
        <Button htmlType="button" type="primary" style={{ margin: '20px 0' }} onClick={onAdd}>
          <PlusCircleOutlined />
          新增码库
        </Button>
        <Table
          columns={columns}
          dataSource={dataList}
          rowKey={(record) => record.record_id}
          loading={loading}
          pagination={paginationProps}
          onChange={tableChange}
        />
        {visible && <Edit visible={visible} editCallback={editCallback} detailData={editData} />}
      </div>
    </PageContainer>
  );
};
export default CodeLibrary;
