import React, { useEffect, useState } from 'react';
import { Table, Form, Input, Select, Button, DatePicker, Tag, Space, message } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import DetailView from './components/DetailView'; 
import { list } from './services';

const { RangePicker } = DatePicker;

const statusColorMap = {
  '未开始': 'default',
  '进行中': 'processing',
  '已结束': 'success',
};

const resultColorMap = {
  '通过': 'success',
  '驳回': 'error',
};

const regionOptions = [
  { label: '请选择', value: '' },
  { label: '境内', value: '境内' },
  { label: '境外', value: '境外' },
];
const statusOptions = [
  { label: '请选择', value: '' },
  { label: '未开始', value: '未开始' },
  { label: '进行中', value: '进行中' },
  { label: '已结束', value: '已结束' },
];
const resultOptions = [
  { label: '请选择', value: '' },
  { label: '通过', value: '通过' },
  { label: '驳回', value: '驳回' },
];

const SupplierChangeReviewManage: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentDetailId, setCurrentDetailId] = useState<number | null>(null);

  // 获取表格数据
  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      const { code, data, total, msg } = await list({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params,
      });
      if (code === 200) {
        setData(data);
        setPagination(p => ({ ...p, total: total || 0 }));
      } else {
        message.error(msg || '获取数据失败');
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize]);

  // 查询
  const handleSearch = () => {
    setPagination(p => ({ ...p, current: 1 }));
    fetchData(form.getFieldsValue());
  };
  // 重置
  const handleReset = () => {
    form.resetFields();
    setPagination(p => ({ ...p, current: 1 }));
    fetchData();
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 48,
      align: 'center',
      render: (_: any, __: any, idx: number) => (pagination.current - 1) * pagination.pageSize + idx + 1,
    },
    {
      title: '供应商名称',
      dataIndex: 'name',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '境内/境外',
      dataIndex: 'region',
      align: 'center',
    },
    {
      title: '供应商分类',
      dataIndex: 'supplierType',
      align: 'center',
    },
    {
      title: '准入时间',
      dataIndex: 'accessTime',
      align: 'center',
    },
    {
      title: '提交变更时间',
      dataIndex: 'changeTime',
      align: 'center',
    },
    {
      title: '流程状态',
      dataIndex: 'status',
      align: 'center',
      render: (val: any) => <Tag color={statusColorMap[val] || 'default'}>{val}</Tag>,
    },
    {
      title: '审批结果',
      dataIndex: 'result',
      align: 'center',
      render: (val: any) => val ? <Tag color={resultColorMap[val] || 'default'}>{val}</Tag> : null,
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_: any, record: any) => (
        <Button type="link" onClick={() => handleDetail(record)}>
          审批记录
        </Button>
      ),
    },
  ];

  // 弹窗操作
  const handleDetail = (record: any) => {
    setCurrentDetailId(record.id);
    setDetailVisible(true);
  };
  const handleDetailClose = () => {
    setDetailVisible(false);
    setCurrentDetailId(null);
  };

  return (
    <>
      {/* 查询表单 */}
      <Form
        form={form}
        layout="inline"
        style={{ width: '100%', marginBottom: 16 }}
        onFinish={handleSearch}
      >
        <Form.Item name="name" label="供应商名称">
          <Input placeholder="请输入供应商名称关键字" allowClear />
        </Form.Item>
        <Form.Item name="region" label="境内/境外">
          <Select options={regionOptions} allowClear style={{ width: 120 }} />
        </Form.Item>
        <Form.Item name="status" label="流程状态">
          <Select options={statusOptions} allowClear style={{ width: 120 }} />
        </Form.Item>
        <Form.Item name="result" label="审批结果">
          <Select options={resultOptions} allowClear style={{ width: 120 }} />
        </Form.Item>
        <Form.Item name="changeTime" label="提交变更时间">
          <RangePicker style={{ width: 220 }} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" icon={<SearchOutlined />} htmlType="submit">查询</Button>
          <Button icon={<ReloadOutlined />} style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
        </Form.Item>
      </Form>
      {/* 数据表格 */}
      <Table
        columns={columns}
        rowKey="id"
        dataSource={data}
        loading={loading}
        bordered
        pagination={{
          ...pagination,
          showQuickJumper: true,
          showSizeChanger: true,
          onChange: (current, pageSize) => setPagination({ ...pagination, current }),
        }}
      />
      {/* 审批记录弹窗 */}
      <DetailView
        visible={detailVisible}
        onClose={handleDetailClose}
        detailId={currentDetailId || ''}
      />
    </>
  );
};

export default SupplierChangeReviewManage;
