package com.engine.recruit.thread;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.engine.recruit.conn.*;
import com.engine.recruit.constant.RecruitConstant;
import com.engine.recruit.entity.position.PositionSdkInstance;
import com.engine.recruit.enums.ApplicationStatusEnum;
import com.engine.recruit.enums.CommonBrowserTypeEnum;
import com.engine.recruit.enums.HighestDegreeEnum;
import com.weaver.rpa.sdk.clients.application.resume.ERPAResumeSDKClient;
import com.weaver.util.threadPool.entity.LocalRunnable;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.erpa.apps.entity.application.resume.dto.*;
import weaver.formmode.recruit.modeexpand.util.RecruitModeUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author:dxfeng
 * @createTime: 2023/10/16
 * @version: 1.0
 */
public class SdkResumeSavedThread extends LocalRunnable {

    private ResumeMqMessage resumeMqMessage;
    private static final int SEC_CATEGORY = Convert.toInt(RecruitConstant.APPLICANTS_RESUMES_CATEGORY);

    public SdkResumeSavedThread(ResumeMqMessage resumeMqMessage) {
        this.resumeMqMessage = resumeMqMessage;
    }

    @Override
    public void execute() throws Exception {
        parseResume(resumeMqMessage);
    }

    /**
     * 解析建立，并入库
     *
     * @param resumeMqMessage
     * @throws Exception
     */
    private void parseResume(ResumeMqMessage resumeMqMessage) throws Exception {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("千里聆SDK简历开始解析------");
        baseBean.writeLog("resumeMqMessage===" + JSON.toJSONString(resumeMqMessage));
        String userId = resumeMqMessage.getUserId();
        User user = new User();
        if (StringUtils.isNotBlank(userId)) {
            user.setUid(Convert.toInt(userId));
        } else {
            user.setUid(1);
        }
        // 千里聆简历ID
        Long resumeId = resumeMqMessage.getResumeId();

        ResumeInfoDto resumeInfoDto = resumeMqMessage.getResumeInfoDto();
        Map<String, Object> params = new RecruitDataMap<>();
        // 姓名
        params.put("xm", resumeInfoDto.getName());
        // 性别
        params.put("xb", resumeInfoDto.getSex());
        // 年龄
        params.put("nl", resumeInfoDto.getAge());
        // 工作经验
        params.put("gzjy", getCommonBrowserKey(getExperienceText(resumeInfoDto.getExperience()), CommonBrowserTypeEnum.WORK_EXPERIENCE.getDesc()));
        // 手机号码
        params.put("sjhm", resumeInfoDto.getPhone());
        // 电子邮箱
        params.put("dzyx", resumeInfoDto.getEmail());
        // 期望税前月薪
        params.put("qwsqyxk", resumeInfoDto.getExpectSalaryStart());
        // 最高学历
        params.put("zgxl", HighestDegreeEnum.getDegreeId(resumeInfoDto.getHighestDegree()).getId());
        // 原始简历
        params.put("ysjl", convertStreamToE9DocId(resumeMqMessage.getResumeInfoDto().getResumeFileId(), user));
        // 千里聆简历ID
        params.put("qlljl", resumeId);
        params.put("tdsj", DateUtil.getDateTime());
        // 判断是否有发布职位信息，如有发布职位信息，完善招聘流程信息，并指定为待分配状态
        String positionId = PositionCommonInfo.getPositionIdByQll(resumeInfoDto.getJobId());
        String zt = ApplicationStatusEnum.DISTRIBUTION.getValue();
        // 应聘职位
        if (StringUtils.isNotBlank(positionId)) {
            String flowId = PositionCommonInfo.getRecruitFlowId(positionId);
            Map<String, String> initialStage = ApplicantCommonInfo.getInitialStage(flowId);
            if (null != initialStage) {
                String zpjd = initialStage.get("zpjd");
                String dqypjd = initialStage.get("jdlx");
                if (StringUtils.isNotBlank(zpjd) && StringUtils.isNotBlank(dqypjd)) {
                    params.put("ypzw", positionId);
                    params.put("zplc", flowId);
                    params.put("zpjd", zpjd);
                    params.put("dqypjd", dqypjd);
                    zt = ApplicationStatusEnum.CANDIDATE.getValue();
                }
            }
        }
        // 应聘状态
        params.put("zt", zt);

        // 判断简历是否重复,插入主表
        CheckRepeatResume instance = CheckRepeatResume.getInstance();
        Map<String, Object> checkMap = instance.insertResumeAndReturn(1, params);
        String mainId = Util.null2String(checkMap.get("mainId"));
        String sourceId = Util.null2String(checkMap.get("sourceId"));
        boolean isSendStep = (boolean) checkMap.get("isSendStep");

        Thread.sleep(1000);
        if ("-1".equals(mainId)) {
            return;
        }
        if (isSendStep) {
            // 发送阶段提醒
            StepMsgCommonInfo.sendMsg(String.valueOf(mainId), Util.null2String(params.get("ypzw")), Util.null2String(params.get("zplc")), Util.null2String(params.get("zpjd")), user);
        }

        // 插入明细表数据
        List<RecruitDataMap<Object>> jyjl = new ArrayList<>();
        List<ResumeInfoEducationExperienceDto> educationExperience = resumeInfoDto.getEducationExperience();
        for (ResumeInfoEducationExperienceDto educationExperienceDto : educationExperience) {
            RecruitDataMap<Object> map = new RecruitDataMap<>();
            map.put("xxmc", educationExperienceDto.getSchoolName());
            map.put("xl", HighestDegreeEnum.getDegreeId(educationExperienceDto.getDegree()).getId());
            map.put("zy", educationExperienceDto.getMajor());
            map.put("kssj", DateUtil.getDate(educationExperienceDto.getBeginTime()));
            map.put("jssj", DateUtil.getDate(educationExperienceDto.getEndTime()));
            jyjl.add(map);
        }
        instance.insertResumeDetailTable(jyjl, "uf_jcl_yppc_dt1", mainId, sourceId);

        List<RecruitDataMap<Object>> gzjl = new ArrayList<>();
        List<ResumeInfoWorkExperienceDto> workExperience = resumeInfoDto.getWorkExperience();
        for (ResumeInfoWorkExperienceDto workExperienceDto : workExperience) {
            RecruitDataMap<Object> map = new RecruitDataMap<>();
            map.put("gsmc", workExperienceDto.getCompanyName());
            map.put("gw", workExperienceDto.getJobName());
            map.put("gzzz", workExperienceDto.getContent());
            map.put("kssj", DateUtil.getDate(workExperienceDto.getBeginTime()));
            map.put("jssj", DateUtil.getDate(workExperienceDto.getEndTime()));
            gzjl.add(map);

        }
        instance.insertResumeDetailTable(gzjl, "uf_jcl_yppc_dt2", mainId, sourceId);

        List<RecruitDataMap<Object>> xmjl = new ArrayList<>();
        List<ResumeInfoProjectExperienceDto> projectExperience = resumeInfoDto.getProjectExperience();
        for (ResumeInfoProjectExperienceDto projectExperienceDto : projectExperience) {
            RecruitDataMap<Object> map = new RecruitDataMap<>();
            map.put("xmmc", projectExperienceDto.getProjectName());
            map.put("xmms", projectExperienceDto.getContent());
            map.put("kssj", DateUtil.getDate(projectExperienceDto.getBeginTime()));
            map.put("jssj", DateUtil.getDate(projectExperienceDto.getEndTime()));
            xmjl.add(map);
        }
        instance.insertResumeDetailTable(xmjl, "uf_jcl_yppc_dt3", mainId, sourceId);

    }


    private String getCommonBrowserKey(String value, String commonBrowserType) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from uf_sjzd where zdlxmc = (select id from uf_zdlx where zdmc = ?) and xxnr =?", commonBrowserType, value);
        if (rs.next()) {
            return rs.getString("id");
        }
        return "";
    }

    private String getExperienceText(Integer experience) {
        String experienceText = "不限";
        switch (experience) {
            case -1:
                experienceText = "不限";
                break;
            case 1:
                experienceText = "1年以内";
                break;
            case 2:
                experienceText = "1-3年";
                break;
            case 3:
                experienceText = "3-5年";
                break;
            case 5:
                experienceText = "5-10年";
                break;
            case 6:
                experienceText = "10年以上";
                break;
            default:
                break;
        }
        return experienceText;
    }

    /**
     * 将文件流转换为文档ID
     *
     * @param resumeFileId
     * @param user
     * @return
     */
    private String convertStreamToE9DocId(Long resumeFileId, User user) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("解析千里聆SDK原始简历，resumeFileId===" + resumeFileId);
        List<Integer> docIdList = new ArrayList<>();
        ERPAResumeSDKClient client = PositionSdkInstance.getPositionSdkInstance().getResumeSDKClient();
        client.downloadResumeFile(resumeFileId, (fileName, stream) -> {
            try {
                baseBean.writeLog("解析千里聆SDK原始简历，fileName===" + fileName);
                int imageFileId = RecruitModeUtil.generateImageFileId(stream, fileName);
                baseBean.writeLog("解析千里聆SDK原始简历，imageFileId===" + imageFileId);
                if (imageFileId > 0) {
                    int docId = RecruitModeUtil.createDocId(SEC_CATEGORY, imageFileId, user);
                    if (docId > 0) {
                        docIdList.add(docId);
                    }
                }
            } catch (Exception e) {
                baseBean.writeLog("解析千里聆SDK原始简历失败", e);
                throw new RuntimeException(e);
            }
        });

        return CollectionUtils.isNotEmpty(docIdList) ? Integer.toString(docIdList.get(0)) : "";
    }


    public ResumeMqMessage getResumeMqMessage() {
        return this.resumeMqMessage;
    }

    public void setResumeMqMessage(ResumeMqMessage resumeMqMessage) {
        this.resumeMqMessage = resumeMqMessage;
    }
}
