import React, { useEffect, useState } from "react";
import { useIntl } from 'umi';
import { Form, Button, Table, Select, DatePicker, TreeSelect } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { SearchOutlined } from '@ant-design/icons';
import { category, categoryOption } from './services';
import moment from 'moment';

interface Data {
  deptName: string;
  categoryName: string;
  createTime: string;
  exitTime: string;
  exitReason: string;
}

// 将 categoryTree 的字段从 categoryName 和 id 映射到 label 和 value
const transformTreeData = (treeData: any[]): any[] => {
  return treeData.map((item) => ({
    value: item.id,
    label: item.categoryName,
    children: item.children ? transformTreeData(item.children) : undefined,
  }));
};
// 列表头
const columns: ColumnsType<Data> = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    width: 80,
    align: 'center',
    render: (_: any, __: any, index: number) => index + 1,
  },
  {
    title: '准入部门',
    dataIndex: 'deptName',
    key: 'deptName',
  },
  {
    title: '准入品类',
    dataIndex: 'categoryName',
    key: 'categoryName',
  },
  {
    title: '准入时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '退出时间',
    dataIndex: 'exitTime',
    key: 'exitTime',
  },
  {
    title: '退出原因',
    dataIndex: 'exitReason',
    key: 'exitReason',
    ellipsis: true,
  },
];

const CooperateEnterprise: React.FC = () => {
  //双语
  const intl = useIntl();
  //搜索
  const [searchForm] = Form.useForm();
  //列表数据
  const [data, setData] = useState<Data[]>([]);
  //列表加载
  const [loading, setLoading] = useState(false);
  //分页
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 });
  //搜索中树形下拉数据
  const [categoryTree, setCategoryTree] = useState<any[]>([]);
  //列表数据方法
  const getList = async (params: { page: number; pageSize: number; categoryName: string; startTime: string; endTime: string }) => {
    setLoading(true);
    try {
      const { code, data, total } = await category(params);
      if (code === 200) {
        setData(data);
        setPagination({ current: params.page, pageSize: params.pageSize, total});
      }
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };
  //搜索重置
  const handleReset = () => {
    searchForm.resetFields();
    getList({ page: 1, pageSize: pagination.pageSize ?? 10, categoryName: '', startTime: '', endTime: '' });
  };
  //搜索
  const handleSearch = (values: any) => {
    const { categoryName, createTime } = values;
    const startTime = createTime ? moment(createTime[0]).format('YYYY-MM-DD') : '';
    const endTime = createTime ? moment(createTime[1]).format('YYYY-MM-DD') : '';
    getList({
      page: 1,
      pageSize: pagination.pageSize ?? 10,
      categoryName: categoryName || '',
      startTime,
      endTime,
    });
  };
  //初始化
  useEffect(() => {
    categoryOption().then((res:any) => {
      const { code, data } = res;
      if(code == 200) {
        setCategoryTree(transformTreeData(data))
      }
    })
    getList({ page: 1, pageSize: 10, categoryName: '', startTime: '', endTime: '' });
  }, []);
  return (
    <>
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="categoryName" label="准入品类">
          <TreeSelect
            style={{ width: '200px' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={categoryTree}
            placeholder="请选择准入品类"
            treeDefaultExpandAll
          />
        </Form.Item>
        <Form.Item name="createTime" label="准入时间">
          <DatePicker.RangePicker placeholder={['开始时间', '结束时间']} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            搜索
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table
        rowKey="id"
        className="custom-table"
        columns={columns}
        dataSource={data}
        pagination={pagination}
        loading={loading}
        onChange={(pagination) => getList({ page: pagination.current!, pageSize: pagination.pageSize!, categoryName: '', startTime: '', endTime: '' })}
      />
    </>
  );
};

export default CooperateEnterprise;