import React, { useRef, useState } from 'react';
import { Modal, message } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { batchAddJobToJobFair } from '@/services/jobfair/publicJobFair';
import { getCmsJobList } from '@/services/Management/list';

interface JobSelectModalProps {
  open: boolean;
  jobFairId: string;
  company?: API.PublicJobFair.CompanyInfo;
  onCancel: () => void;
  onSuccess: () => void;
}

const JobSelectModal: React.FC<JobSelectModalProps> = ({ open, jobFairId, company, onCancel, onSuccess }) => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);

  const handleOk = async () => {
    if (!selectedRowKeys.length) {
      message.warning('请选择岗位');
      return;
    }
    if (!company) return;
    setLoading(true);
    const data = selectedRowKeys.map((jobId) => ({
      jobFairId,
      jobId: jobId as number,
      companyId: company.companyId,
    }));
    const res = await batchAddJobToJobFair(data);
    setLoading(false);
    if (res.code === 200) {
      message.success('添加成功');
      setSelectedRowKeys([]);
      onSuccess();
    } else {
      message.error(res.msg || '添加失败');
    }
  };

  const columns: ProColumns[] = [
    { title: '岗位名称', dataIndex: 'jobTitle', ellipsis: true },
    { title: '薪资', dataIndex: 'salary', hideInSearch: true, render: (_, r) => `${r.minSalary || 0}K-${r.maxSalary || 0}K` },
    { title: '学历', dataIndex: 'education', hideInSearch: true },
    { title: '经验', dataIndex: 'experience', hideInSearch: true },
    { title: '招聘人数', dataIndex: 'vacancies', hideInSearch: true },
  ];

  return (
    <Modal
      title={`选择岗位 - ${company?.companyName || ''}`}
      open={open}
      width={800}
      onCancel={() => {
        setSelectedRowKeys([]);
        onCancel();
      }}
      onOk={handleOk}
      okText="确定添加"
      confirmLoading={loading}
      destroyOnClose
    >
      <ProTable
        actionRef={actionRef}
        rowKey="jobId"
        columns={columns}
        search={{ labelWidth: 'auto' }}
        pagination={{ pageSize: 5 }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        request={async (params) => {
          if (!company?.companyId) return { data: [], total: 0, success: true };
          const res = await getCmsJobList({
            current: params.current,
            pageSize: params.pageSize,
            companyId: company.companyId,
            jobTitle: params.jobTitle,
          } as any);
          return { data: res.rows, total: res.total, success: true };
        }}
        toolBarRender={false}
      />
    </Modal>
  );
};

export default JobSelectModal;
