import React, { useEffect, useState } from 'react';
import { Table, Form, Select, Button, message, Space, Tooltip } from 'antd';
import { SearchOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
//接口
import { getApprovePage } from './services';
import { getDictList } from '@/servers/api/dicts'
//组件
import AccessDepartmentSelect from '@/components/AccessDepartmentSelect';
import ViewModal from './components/ViewModal';
import AdmissionTypeSelect from '@/components/CommonSelect/AdmissionTypeSelect';
//统一列表分页
import tableProps from '@/utils/tableProps'

interface SupplierEntryReviewRecord {
  id: string;
  accessWorkName: string;    // 准入工作
  deptId: string;            // 准入部门ID
  accessTypeText: string;    // 准入方式
  reviewStatusText: string;  // 流程状态
  categoryName: string;      // 品类名称
  startTime: string;         // 申请时间
  endTime: string;
  createTime: string;        // 创建时间
  updateTime: string;        // 更新时间
  [key: string]: any;        // 允许有其它字段
}

interface ModalInfo {
  visible: boolean;
  record: string | null;
}

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

const SupplierEntryReview: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<any[]>([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [loading, setLoading] = useState(false);
  const [modalInfo, setModalInfo] = useState<ModalInfo>({ visible: false, record: null });
  //
    const [enterpriseType, setEnterpriseType] = useState<Dict[]>();
  // 查询数据
  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      const res = await getApprovePage({
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        ...form.getFieldsValue(),
        ...params,
      });
      if (res.code === 200) {
        setData(res.data.records);
        setPagination({
          ...pagination,
          current: res.data.current,
          total: res.data.total,
          pageSize: res.data.size,
        });
      } else {
        setData([]);
        setPagination({ ...pagination, total: 0 });
      }
    } catch (err) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData({ pageNo: 1 });
     getDictList('approve_type').then((res) => {
          if (res.code == 200) {
            setEnterpriseType(res.data)
          }
        })
  }, []);

  // 表格分页切换
  const handleTableChange = (pag: any) => {
    setPagination({
      ...pagination,
      current: pag.current,
      pageSize: pag.pageSize,
    });
    fetchData({
      pageNo: pag.current,
      pageSize: pag.pageSize,
    });
  };

  // 搜索
  const handleSearch = () => {
    setPagination({ ...pagination, current: 1 });
    fetchData({ pageNo: 1 });
  };

  // 重置
  const handleReset = () => {
    form.resetFields();
    setPagination({ ...pagination, current: 1 });
    fetchData({ pageNo: 1 });
  };
  const openModal = (record: string) => {
    setModalInfo({ visible: true, record });
  };
  const closeModal = () => {
    setModalInfo({ visible: false, record: null });
  };
  const columns: ColumnsType<SupplierEntryReviewRecord> = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      align: 'center',
      render: (_: any, __: any, idx: number) => (((pagination.current ?? 1) - 1) * (pagination.pageSize ?? 10)) + idx + 1,
    },
    {
      title: '准入工作',
      dataIndex: 'accessWorkName',
      align: 'center',
      ellipsis: true,
      width: 120,
    },
    {
      title: '准入部门',
      dataIndex: 'deptName',
      align: 'center',
      width: 120,
    },
    {
      title: '准入方式',
      dataIndex: 'accessTypeText',
      align: 'center',
      ellipsis: true,
      width: 120,
    },
    {
      title: '准入品类',
      dataIndex: 'categoryNameList',
      width: 120,
      align: 'center',
      render: (value: { item: string }[] = []) => {
        if (!value || value.length === 0) return '-';
        if (value.length === 1) {
          return <span>{value[0].item}</span>;
        }
        // 多于1条
        const allNames = value.map(item => item).join('、');
        return (
          <Tooltip title={allNames} overlayStyle={{ zIndex: 1200 }}>
            <span>
              {value[0]}
              <span>等</span>
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '开始时间',
      dataIndex: 'createTime',
      align: 'center',
      ellipsis: true,
      width: 180,
    },
    {
      title: '结束时间',
      dataIndex: 'lastUpdateTime',
      align: 'center',
      ellipsis: true,
      width: 180,
    },
    {
      title: '评审状态',
      dataIndex: 'reviewStatusText',
      align: 'center',
      width: 120,
    },
    {
      title: '审批状态',
      dataIndex: 'approveStatusText',
      align: 'center',
      width: 120,
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      render: (_: any, record: any) => {
        return (
          <Space>
            <a onClick={() => openModal(record.id)}>查看</a>
          </Space>
        )

      },
    },
  ];
  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Form
          form={form}
          layout="inline"
          className="filter-form"
          onFinish={handleSearch}
        >
          <Form.Item name="accessType" label="准入方式">
            <AdmissionTypeSelect/>
          </Form.Item>
          <Form.Item name="deptId" label="准入部门">
            <AccessDepartmentSelect orgCategory='' />
          </Form.Item>

          <Form.Item name="approveStatus" label="审批状态">
            <Select style={{ width: 150 }} placeholder="请选择状态" allowClear>
              {enterpriseType?.map(item => (
                <Select.Option key={item.code} value={item.code}>{item.dicName}</Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item>
            <Button className="buttonSubmit" type="primary" htmlType="submit" icon={<SearchOutlined />} >
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button className="buttonReset" icon={<DeleteOutlined />} onClick={handleReset} >重置</Button>
          </Form.Item>


        </Form>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{ ...tableProps.pagination, total: pagination.total }}
        onChange={handleTableChange}
        style={{ flex: 1, minHeight: 0 }}
        scroll={{ y: 'calc(100vh - 350px)' }}
      />
      <ViewModal
        visible={modalInfo.visible}
        record={modalInfo.record}
        onCancel={closeModal}
      />
    </div>
  );
};

export default SupplierEntryReview;
