import React, { Fragment, useEffect, useRef, useState } from 'react';
import { FormattedMessage, useAccess, useParams } from '@umijs/max';
import { Button, FormInstance, message } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { FormOutlined, PlusOutlined } from '@ant-design/icons';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import { exportCmsAppUserExport } from '@/services/mobileusers/list';
import { exportCmsJobCandidates, getCmsJobIds,getJobCompetitiveness  } from '@/services/Management/list';
import similarityJobs from '@/utils/similarity_Job';
import Detail from './detail';

const handleExport = async (values: API.MobileUser.ListParams) => {
  const hide = message.loading('正在导出');
  try {
    await exportCmsAppUserExport(values);
    hide();
    message.success('导出成功');
    return true;
  } catch (error) {
    hide();
    message.error('导出失败，请重试');
    return false;
  }
};

function ManagementList() {
  const access = useAccess();
  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [jobId, setJobId] = useState<string>();
  const [educationEnum, setEducationEnum] = useState<any>([]);
  const [experienceEnum, setExperienceEnum] = useState<any>([]);
  const [areaEnum, setAreaEnum] = useState<any>([]);
  const [sexEnum, setSexEnum] = useState<any>([]);
  const [politicalEnum, setPoliticalEnum] = useState<any>([]);
  const [currentRow, setCurrentRow] = useState<API.MobileUser.ListRow>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [jobInfo, setJobInfo] = useState({});
  const [competitivenessData, setCompetitivenessData] = useState<API.ManagementList.CompetitivenessData>({});
  const [competitivenessLoading, setCompetitivenessLoading] = useState<boolean>(false);
  const params = useParams();
  const id = params.id || '0';

  useEffect(() => {
    if (jobId !== id) {
      setJobId(id);
      getJobInfo(id);
    }
  }, [jobId, params]);

  const getJobInfo = async (jobId: string) => {
    let resData = await getCmsJobIds(jobId);
    if (resData.code === 200) {
      similarityJobs.setJobInfo(resData.data);
      setJobInfo(resData.data);
    }
  };

  // 获取竞争力分析数据
  const fetchCompetitivenessData = async (userId: string, jobId: string) => {
    try {
      setCompetitivenessLoading(true)
      const res = await getJobCompetitiveness({ userId, jobId });
      if (res.code === 200) {
        setCompetitivenessLoading(false)
        setCompetitivenessData(res.data);
        return res.data;
      }
      setCompetitivenessLoading(false)
      return null;
    } catch (error) {
      setCompetitivenessLoading(false)
      console.error('获取竞争力分析数据失败:', error);
      return null;
    }
  };

  useEffect(() => {
    getDictValueEnum('education', true, true).then((data) => {
      setEducationEnum(data);
    });
    getDictValueEnum('experience', true, true).then((data) => {
      setExperienceEnum(data);
    });
    getDictValueEnum('area', true, true).then((data) => {
      setAreaEnum(data);
    });
    getDictValueEnum('sys_user_sex', true).then((data) => {
      setSexEnum(data);
    });
    getDictValueEnum('political_affiliation', true, true).then((data) => {
      setPoliticalEnum(data);
    });
  }, []);

  const columns: ProColumns<API.MobileUser.ListRow>[] = [
    {
      title: '用户名',
      dataIndex: 'name',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '期望薪资',
      dataIndex: 'minSalary',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => (
        <>
          {record.salaryMin}-{record.salaryMax}
        </>
      ),
    },
    {
      title: '出生日期',
      dataIndex: 'birthDate',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '学历要求',
      dataIndex: 'education',
      valueType: 'select',
      align: 'center',
      valueEnum: educationEnum,
      render: (_, record) => {
        return <DictTag enums={educationEnum} value={record.education} />;
      },
    },
    {
      title: '区域',
      dataIndex: 'area',
      valueType: 'select',
      align: 'center',
      valueEnum: areaEnum,
      render: (_, record) => {
        return <DictTag enums={areaEnum} value={record.area} />;
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueType: 'select',
      align: 'center',
      valueEnum: sexEnum,
      render: (_, record) => {
        return <DictTag enums={sexEnum} value={record.sex} />;
      },
    },
    {
      title: '政治面貌',
      dataIndex: 'politicalAffiliation',
      valueType: 'select',
      align: 'center',
      valueEnum: politicalEnum,
      render: (_, record) => {
        return <DictTag enums={politicalEnum} value={record.politicalAffiliation} />;
      },
    },
    {
      title: '投递时间',
      dataIndex: 'applyDate',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'jobId',
      width: 200,
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          key="edit"
          icon={<FormOutlined />}
          hidden={!access.hasPerms('area:business:List.update')}
          onClick={async () => {
            setModalVisible(true);
            const data = await fetchCompetitivenessData(record.userId, jobId);
            if (data) {
              setCompetitivenessData(data);
            }
          }}
        >
          查看竞争力分析
        </Button>,
      ],
    },
  ];

  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.MobileUser.ListRow>
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="jobId"
          key="index"
          columns={columns}
          request={(params) =>
            exportCmsJobCandidates(jobId).then((res) => {
              const result = {
                data: res.rows,
                total: res.total,
                success: true,
              };
              return result;
            })
          }
          toolBarRender={() => [
            <Button
              type="primary"
              key="export"
              hidden={!access.hasPerms('system:user:export')}
              onClick={async () => {
                const searchVal = formTableRef.current && formTableRef.current.getFieldsValue();
                handleExport(searchVal as API.MobileUser.ListParams);
              }}
            >
              <PlusOutlined />
              <FormattedMessage id="pages.searchTable.export" defaultMessage="导出" />
            </Button>,
          ]}
        />
        <Detail
          open={modalVisible}
          loading={competitivenessLoading}
          competitivenessData={competitivenessData}
          onClose={() => {
            setModalVisible(false);
            setCurrentRow(undefined);
            setCompetitivenessData({});
          }}
        ></Detail>
      </div>
    </Fragment>
  );
}

export default ManagementList;
