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';
import ViewModal from './components/ViewModal';

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

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

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, view:false });

  const openModal = (type: 'teamMembers' | 'groupLeader' | 'view', record: Data, view = false ) => {
    setModalInfo({ type, visible: true, record, view });
  };
  //提交关闭审核
  const closeModal = () => {
    setModalInfo({ type: null, visible: false, record: null, view:false  });
  };
  //提交审核
  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',
      width: 120,
    },
    {
      title: '操作',
      width: 120,
      render: (_: any, record: any) => {
        //  已完成 3  、结果汇总中 2 、进行中1  、 未开始0
        // 显示评审 按钮
        const showAudit = (
          (['0', '1'].includes(record.reviewStatus) && record.isLeader === '0') ||
          (['2'].includes(record.reviewStatus) && record.isLeader === '1')
        );
        // 进行中1 、未开始0 弹出组员组件 否则弹出组长组件
        const type = ['0', '1'].includes(record.reviewStatus)?  'teamMembers': 'groupLeader';

        //评审结果  结果汇总中2 弹出组员组件,  已完成3弹出组长组件
        const isLeader = (record.reviewStatus === '2' && record.isLeader === '0')?  'teamMembers': 
                         (record.reviewStatus === '3' && record.isLeader === '1')?  'groupLeader':'';
       return (
        <Space>
           {showAudit && <a onClick={() => openModal(type, record)}>评审</a>}
           <a onClick={() => openModal('view', record)}>查看</a>
           { isLeader != '' && <a onClick={() => openModal(isLeader, record, true)}>评审结果</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} 
          view={modalInfo.view}
          record={modalInfo.record} 
          onCancel={closeModal} 
          onSubmit={submitModal} 
        />
      )}
      { modalInfo.type && modalInfo.type === 'groupLeader' && (
        <GroupLeaderModal 
          visible={modalInfo.visible} 
          view={modalInfo.view}
          record={modalInfo.record} 
          onCancel={closeModal} 
          onSubmit={submitModal} 
        />
      )}
      { modalInfo.type && modalInfo.type === 'view' && (
        <ViewModal
          visible={modalInfo.visible} 
          record={modalInfo.record} 
          onCancel={closeModal} 
        />
      )}
      
    </>
  );
};

export default CooperateEnterprise;