import React, { useRef, useState, useEffect } from 'react';
import { useAccess, history } from '@umijs/max';
import { Button, message, Modal } from 'antd';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, FormOutlined, ExportOutlined, EyeOutlined } from '@ant-design/icons';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import {
  getPublicJobFairList,
  getPublicJobFairDetail,
  addPublicJobFair,
  updatePublicJobFair,
  deletePublicJobFair,
  exportPublicJobFair,
} from '@/services/jobfair/publicJobFair';
import EditModal from './components/EditModal';

const PublicJobFairList: React.FC = () => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<API.PublicJobFair.JobFairItem>();
  const [jobFairTypeEnum, setJobFairTypeEnum] = useState<any>({});
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    getDictValueEnum('job_fair_type', true).then(setJobFairTypeEnum);
  }, []);

  const handleDelete = async (ids: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除选中的招聘会吗？',
      onOk: async () => {
        const res = await deletePublicJobFair(ids);
        if (res.code === 200) {
          message.success('删除成功');
          actionRef.current?.reload();
          setSelectedRowKeys([]);
        } else {
          message.error(res.msg || '删除失败');
        }
      },
    });
  };

  const handleExport = async () => {
    message.loading('正在导出...');
    try {
      await exportPublicJobFair();
      message.success('导出成功');
    } catch {
      message.error('导出失败');
    }
  };

  const columns: ProColumns<API.PublicJobFair.JobFairItem>[] = [
    {
      title: '招聘会标题',
      dataIndex: 'jobFairTitle',
      ellipsis: true,
    },
    {
      title: '地址',
      dataIndex: 'jobFairAddress',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'jobFairType',
      valueType: 'select',
      valueEnum: jobFairTypeEnum,
      render: (_, record) => <DictTag enums={jobFairTypeEnum} value={record.jobFairType} />,
    },
    {
      title: '开始时间',
      dataIndex: 'jobFairStartTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      dataIndex: 'jobFairEndTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => history.push(`/jobfair/public-job-fair/detail?id=${record.jobFairId}`)}
        >
          详情
        </Button>,
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<FormOutlined />}
          hidden={!access.hasPerms('cms:publicJobFair:edit')}
          onClick={async () => {
            const res = await getPublicJobFairDetail(record.jobFairId);
            if (res.code === 200) {
              setCurrentRow(res.data);
              setModalVisible(true);
            }
          }}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          hidden={!access.hasPerms('cms:publicJobFair:remove')}
          onClick={() => handleDelete(record.jobFairId)}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.PublicJobFair.JobFairItem>
        headerTitle="公共招聘会列表"
        actionRef={actionRef}
        rowKey="jobFairId"
        columns={columns}
        scroll={{ x: 'max-content' }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        request={async (params) => {
          const res = await getPublicJobFairList({
            pageNum: params.current,
            pageSize: params.pageSize,
            jobFairTitle: params.jobFairTitle,
            jobFairType: params.jobFairType,
          });
          return { data: res.rows, total: res.total, success: true };
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            hidden={!access.hasPerms('cms:publicJobFair:add')}
            onClick={() => {
              setCurrentRow(undefined);
              setModalVisible(true);
            }}
          >
            新增
          </Button>,
          selectedRowKeys.length > 0 && (
            <Button
              key="batchDelete"
              danger
              icon={<DeleteOutlined />}
              hidden={!access.hasPerms('cms:publicJobFair:remove')}
              onClick={() => handleDelete(selectedRowKeys.join(','))}
            >
              批量删除
            </Button>
          ),
          <Button key="export" icon={<ExportOutlined />} onClick={handleExport}>
            导出
          </Button>,
        ]}
      />
      <EditModal
        open={modalVisible}
        values={currentRow}
        jobFairTypeEnum={jobFairTypeEnum}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        onSubmit={async (values) => {
          const res = values.jobFairId
            ? await updatePublicJobFair(values)
            : await addPublicJobFair(values);
          if (res.code === 200) {
            message.success(values.jobFairId ? '修改成功' : '新增成功');
            setModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
          } else {
            message.error(res.msg || '操作失败');
          }
        }}
      />
    </PageContainer>
  );
};

export default PublicJobFairList;
