import React, { useEffect, useState } from 'react';
import { Table, Form, Select, Button, Tag, message, Space } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { getApprovePage } from './services';
import type { ColumnsType } from 'antd/es/table';
import ViewModal from './components/ViewModal';
const { Option } = Select;
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;
}
const statusColorMap: Record<string, string> = {
  '未开始': 'default',
  '进行中': 'processing',
  '已完成': 'success',
};

const methodOptions = [
  { label: '全部', value: '' },
  { label: '线上准入', value: '线上准入' },
  { label: '线下准入', value: '线下准入' },
];

const statusOptions = [
  { label: '全部', value: '' },
  { label: '未开始', value: '未开始' },
  { label: '进行中', value: '进行中' },
  { label: '已完成', value: '已完成' },
];

const deptOptions = [
  { label: '全部', value: '' },
  { label: '采购部', value: 'DEPT001' },
  { label: '业务部', value: 'DEPT002' },
];


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 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 });
  }, []);

  // 表格分页切换
  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: 48,
      align: 'center',
      render: (_: any, __: any, idx: number) => (((pagination.current ?? 1) - 1) * (pagination.pageSize ?? 10)) + idx + 1,
    },
    {
      title: '准入工作',
      dataIndex: 'accessWorkName',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '准入部门',
      dataIndex: 'deptId',
      align: 'center',
    },
    {
      title: '准入方式',
      dataIndex: 'accessTypeText',
      align: 'center',
    },
    {
      title: '准入品类',
      dataIndex: 'categoryName',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      align: 'center',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      align: 'center',
    },
    {
      title: '流程状态',
      dataIndex: 'reviewStatusText',
      align: 'center',
    },
    {
      title: '审核',
      dataIndex: 'approveStatusText',
      align: 'center',
    },
    {
      title: '操作',
      width: 120,
      render: (_: any, record: any) => {
        console.log(record, 'record');
        return (
          <Space>
            <a onClick={() => openModal(record.id)}>查看</a>
          </Space>
        )

      },
    },
  ];
  return (
    <div>
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 16 }}
        onFinish={handleSearch}
      >
        <Form.Item name="accessType" label="准入方式">
          <Select style={{ width: 150 }} placeholder="请选择准入方式" allowClear >
            <Option value="online">线上准入</Option>
            <Option value="offline">线下准入</Option>
            <Option value="scattered">零星采购/应急采购</Option>
          </Select>
        </Form.Item>
        <Form.Item name="deptId" label="准入部门">
          <Select options={deptOptions} allowClear style={{ width: 120 }} placeholder="请选择准入部门" />
        </Form.Item>

        <Form.Item name="approveStatus" label="流程状态">
          <Select style={{ width: 150 }} placeholder="请选择状态" allowClear>
            <Option value="0">未开始</Option>
            <Option value="1">进行中</Option>
            <Option value="2">结果汇总中</Option>
            <Option value="3">已完成</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />} style={{ marginRight: 8 }}>
            查询
          </Button>
          <Button onClick={handleReset} icon={<ReloadOutlined />}>
            重置
          </Button>
        </Form.Item>
      </Form>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        onChange={handleTableChange}
      />
      <ViewModal
        visible={modalInfo.visible}
        record={modalInfo.record}
        onCancel={closeModal}
      />
    </div>
  );
};

export default SupplierEntryReview;
