import React, { useRef, useState } from 'react';
import { useAccess } from '@umijs/max';
import { Button, message, Modal, Tag } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { ExportOutlined, EyeOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { getCompanyReviewList, batchApproveCompany, batchRejectCompany } from '@/services/jobportal/indoorJobFair';
import type { CompanyReviewItem } from '@/services/jobportal/indoorJobFair';

interface Props {
  fairId: number;
}

const CompanyReviewTab: React.FC<Props> = () => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const statusMap: Record<string, { text: string; color: string }> = {
    pending: { text: '待审核', color: 'default' },
    approved: { text: '已通过', color: 'green' },
    rejected: { text: '已拒绝', color: 'red' },
  };

  const handleBatchApprove = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要审核的数据');
      return;
    }
    const res = await batchApproveCompany(selectedRowKeys as number[]);
    if (res.code === 200) {
      message.success('批量审核成功');
      setSelectedRowKeys([]);
      actionRef.current?.reload();
    } else {
      message.error(res.msg);
    }
  };

  const handleBatchReject = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要审核的数据');
      return;
    }
    const res = await batchRejectCompany(selectedRowKeys as number[]);
    if (res.code === 200) {
      message.success('批量审核失败');
      setSelectedRowKeys([]);
      actionRef.current?.reload();
    } else {
      message.error(res.msg);
    }
  };

  const handleExport = async (type: string) => {
    if (type === 'selected' && selectedRowKeys.length === 0) {
      message.warning('请先选择要导出的数据');
      return;
    }
    message.success(`已导出${type === 'selected' ? '选中' : type === 'page' ? '当前页' : '全部'}数据（模拟）`);
  };

  const columns: ProColumns<CompanyReviewItem>[] = [
    { title: '招聘会名称', dataIndex: 'fairName', ellipsis: true, hideInSearch: true },
    {
      title: '招聘会名称',
      dataIndex: 'fairName',
      hideInTable: true,
      order: 1,
    },
    {
      title: '单位名称',
      dataIndex: 'companyName',
      order: 2,
    },
    { title: '单位名称', dataIndex: 'companyName', ellipsis: true, hideInSearch: true },
    { title: '行业', dataIndex: 'industry', width: 100, hideInSearch: true },
    { title: '规模', dataIndex: 'scale', width: 100, hideInSearch: true },
    { title: '联系人', dataIndex: 'contactPerson', width: 100, hideInSearch: true },
    { title: '联系电话', dataIndex: 'contactPhone', width: 130, hideInSearch: true },
    {
      title: '审核状态',
      dataIndex: 'reviewStatus',
      valueType: 'select',
      width: 100,
      hideInSearch: true,
      render: (_, record) => {
        const s = statusMap[record.reviewStatus] || { text: record.reviewStatus, color: 'default' };
        return <Tag color={s.color}>{s.text}</Tag>;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (_, record) => [
        <Button key="viewCompany" type="link" size="small" icon={<EyeOutlined />}
          onClick={() => message.info('查看单位基本信息（模拟）')}
        >单位信息</Button>,
        <Button key="viewFair" type="link" size="small" icon={<EyeOutlined />}
          onClick={() => message.info('查看招聘会详情（模拟）')}
        >查看展会</Button>,
      ],
    },
  ];

  return (
    <div>
      <ProTable
        headerTitle="参会单位审核列表"
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        scroll={{ x: 'max-content' }}
        search={{ labelWidth: 100 }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        request={async (params) => {
          const res = await getCompanyReviewList({
            current: params.current,
            pageSize: params.pageSize,
            fairName: params.fairName,
            companyName: params.companyName,
            reviewStatus: params.reviewStatus,
          });
          return { data: res.rows, total: res.total, success: true };
        }}
        toolBarRender={() => [
          <Button key="batchApprove" type="primary" icon={<CheckOutlined />}
            hidden={!access.hasPerms('cms:indoorJobFair:edit')}
            onClick={handleBatchApprove}
          >批量审核成功</Button>,
          <Button key="batchReject" danger icon={<CloseOutlined />}
            hidden={!access.hasPerms('cms:indoorJobFair:edit')}
            onClick={handleBatchReject}
          >批量审核失败</Button>,
          <Button key="exportSelected" icon={<ExportOutlined />}
            onClick={() => handleExport('selected')}
          >导出选中</Button>,
          <Button key="exportPage" icon={<ExportOutlined />}
            onClick={() => handleExport('page')}
          >导出当前页</Button>,
          <Button key="exportAll" icon={<ExportOutlined />}
            onClick={() => handleExport('all')}
          >导出全部</Button>,
        ]}
      />
    </div>
  );
};

export default CompanyReviewTab;
