import React, { useEffect, useState } from "react";
import { useIntl } from 'umi';
import { Form, Button, Table, Select, DatePicker, Input } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { SearchOutlined } from '@ant-design/icons';
import { getSupplierChangePage } from './services';
import moment from 'moment';
import DetailView from './components/DetailView'; 
import { getDictList } from '@/servers/api/dicts'

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

interface Dict {
  dicName: string;
  code: string;
}

const CooperateEnterprise: React.FC = () => {
  //双语
  const intl = useIntl();
  //查询
  const [searchForm] = Form.useForm();
  //列表数据
  const [data, setData] = useState<Data[]>([]);
  //
  const [enterpriseType, setEnterpriseType] = useState<Dict[]>();
  //列表加载
  const [loading, setLoading] = useState(false);
  //列表分页
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 });
  //弹出组件开关状态
  const [detailVisible, setDetailVisible] = useState(false);
  //弹出组件参数
  const [currentDetail, setCurrentDetail] = useState('');
  //列表头部
  const columns: ColumnsType<Data> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      align: 'center',
      render: (_: any, __: any, idx: number) => (((pagination.current ?? 1) - 1) * (pagination.pageSize ?? 10)) + idx + 1,
    },
    {
      title: '变更内容',
      dataIndex: 'changeDesc',
      key: 'changeDesc',
    },
    {
      title: '提交时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
    {
      title: '审批单位',
      dataIndex: 'deptNames',
      key: 'deptNames',
    },
    {
      title: '审批状态',
      dataIndex: 'enterpriseType',
      key: 'enterpriseType',
    },
    {
      title: '审批时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: Data) => (
        <Button type="link" onClick={() => handleDetail(record)}>
          查看
        </Button>
      ),
    },
  ];
  //重置
  const handleReset = () => {
    searchForm.resetFields();
    getList({ pageNo: 1, pageSize: pagination.pageSize ?? 10  });
  };
  //搜索
  const handleSearch = () => {
    getList({
      pageNo: 1,
      pageSize: pagination.pageSize ?? 10,
    });
  };
  //开启弹出
  const handleDetail = (record: Data) => {
    setCurrentDetail(record.id || '');
    setDetailVisible(true);
  };
  //关闭演出
  const handleDetailClose = () => {
    setDetailVisible(false);
  };
  //列表数据请求
  const getList = async (params: { pageNo: number; pageSize: number; }) => {
    setLoading(true);
    try {
      const values = searchForm.getFieldsValue();
      const { changeDesc, createTime, deptNames, enterpriseType } = values;
      const startTime = createTime ? moment(createTime[0]).format('YYYY-MM-DD') : '';
      const endTime = createTime ? moment(createTime[1]).format('YYYY-MM-DD') : '';
      const { code , data } = await getSupplierChangePage({...params, changeDesc, deptNames, enterpriseType,startTime,endTime});
      if (code === 200) {
        setData(data.records);
        setPagination({ current: params.pageNo, pageSize: params.pageSize, total: data.total });
      }
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };
  //初始化
  useEffect(() => {
    getDictList('approve_type').then((res) => {
      if(res.code == 200) {
        setEnterpriseType(res.data)
      }
    })

    getList({ pageNo: 1, pageSize: 10 });
  }, []);

  return (
    <>
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="changeDesc" label="变更内容">
            <Input style={{ width: 160 }} placeholder="请输入变更内容" allowClear maxLength={50} />
        </Form.Item>
        <Form.Item name="deptNames" label="审批单位">
          <Select style={{ width: 160 }} placeholder="请选择审批单位" allowClear>
            <Select.Option value="品类1">品类1</Select.Option>
            <Select.Option value="品类2">品类2</Select.Option>
            <Select.Option value="品类3">品类3</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="createTime" label="提交时间">
          <DatePicker.RangePicker placeholder={['开始时间', '结束时间']} allowClear />
        </Form.Item>
        <Form.Item name="enterpriseType" label="审批状态">
          <Select style={{ width: 160 }} placeholder="请选择审批状态" allowClear>
            {enterpriseType?.map(item => (
              <Select.Option key={item.code} value={item.code}>{item.dicName}</Select.Option>
            ))}
          </Select>
        </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({ pageNo: pagination.current!, pageSize: pagination.pageSize! })}
      />
      <DetailView
        visible={detailVisible}
        onClose={handleDetailClose}
        detailId={currentDetail}
      />
    </>
  );
};

export default CooperateEnterprise;