import React, { useEffect, useState } from "react";
import {  useIntl } from 'umi';
import { Form, Button, Table, Space, Input } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { SearchOutlined } from '@ant-design/icons';
import { getPage } from './services';
//查看评审结果 弹窗
import ResultModal from './components/ResultModal';
import GroupLeaderModal from './components/GroupLeaderModal';

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

interface ModalInfo {
  type: 'teamMembers' | 'groupLeader' | null;
  visible: boolean;
  record: Data | null;
}


const CooperateEnterprise: React.FC = () => {
  const [searchForm] = Form.useForm();
  const intl = useIntl();
  const [data, setData] = useState<Data[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 });
  const [modalInfo, setModalInfo] = useState<ModalInfo>({ type: null, visible: false, record: null });

  const openModal = (type: 'teamMembers' | 'groupLeader', record: Data) => {
    setModalInfo({ type, visible: true, record });
  };
  //提交关闭审核
  const closeModal = () => {
    setModalInfo({ type: null, visible: false, record: null });
  };
  //提交审核
  const submitModal = () => {
    closeModal();
    handleReset();
  };
  
  // 列表数据
  const getList = async (params: { pageNo: number; pageSize: number; parentCode: string; }) => {
    setLoading(true);
    try {
      const { code, data } = await getPage({...params });
      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);
    }
  };

  const handleReset = () => {
    searchForm.resetFields();
    getList({ pageNo: 1, pageSize: pagination.pageSize ?? 10, parentCode: '' });
  };

  const handleSearch = (values: any) => {
    const { parentCode } = values;
    getList({
      pageNo: 1,
      pageSize: pagination.pageSize ?? 10,
      parentCode: parentCode || ''
    });
  };

  useEffect(() => {
    getList({ pageNo: 1, pageSize: 10, parentCode: '' });
  }, []);

  const columns: ColumnsType<Data> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '准入工作',
      dataIndex: 'accessWorkName',
      key: 'accessWorkName',
    },
    {
      title: '发起单位',
      dataIndex: 'deptId',
      key: 'deptId',
    },
    {
      title: '准入部门',
      dataIndex: 'deptId',
      key: 'deptId',
    },
    {
      title: '品类',
      dataIndex: 'categoryName',
      key: 'categoryName',
    },
    {
      title: '准入方式',
      dataIndex: 'accessTypeText',
      key: 'accessTypeText',
    },
    {
      title: '评审时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '评审状态',
      dataIndex: 'reviewStatusText',
      key: 'reviewStatusText',
    },
    {
      title: '操作',
      render: (_: any, record: any) => {
        const showAudit = (
          (['未开始', '进行中'].includes(record.reviewStatusText) && record.isLeader === '0') ||
          (['结果汇总中'].includes(record.reviewStatusText) && record.isLeader === '1')
        );
        const type = ['未开始', '进行中'].includes(record.reviewStatusText)?  'teamMembers': 'groupLeader';
       return (
        <Space>
           {showAudit && <a onClick={() => openModal(type, record)}>审核</a>}
          </Space>
       )
        
      },
    },
  ];
  return (
    <>
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="parentCode" label="准入工作">
          <Input 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({ pageNo: pagination.current!, pageSize: pagination.pageSize!, parentCode: '', })}
      />
      { modalInfo.type && modalInfo.type === 'teamMembers' && (
        <ResultModal 
          visible={modalInfo.visible} 
          record={modalInfo.record} 
          onCancel={closeModal} 
          onSubmit={submitModal} 
        />
      )}
      { modalInfo.type && modalInfo.type === 'groupLeader' && (
        <GroupLeaderModal 
          visible={modalInfo.visible} 
          record={modalInfo.record} 
          onCancel={closeModal} 
          onSubmit={submitModal} 
        />
      )}
      
    </>
  );
};

export default CooperateEnterprise;