package weaver.interfaces.recruit.thread;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.engine.recruit.conn.*;
import com.engine.recruit.entity.resume.QllResumePo;
import com.engine.recruit.enums.ApplicationStatusEnum;
import com.engine.recruit.util.RecruitUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author:dxfeng
 * @createTime: 2023/11/10
 * @version: 1.0
 */
public class ExtractQllResumeThread extends Thread {
    BaseBean baseBean = new BaseBean();

    @Override
    public void run() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id,xm,xb,nl,gzjy,xjzd,sjhm,yx,ypzw,grys,qzyx,gzjl,xmjl,jyjl,zgxl,zyjn,yynl,zs,jlfj,rksj,tdsj,lyqd,gjrsjh from uf_jcl_jlzjb where ocr is null and cqzt is null order by modedatacreatedate, modedatacreatetime");
        List<Map<String, Object>> mapList = RecruitRecordSet.getRecordMapList(rs);
        if (CollectionUtils.isEmpty(mapList)) {
            return;
        }
        for (Map<String, Object> map : mapList) {
            QllResumePo qllResumePo = RecruitUtil.parseMap2Object(map, QllResumePo.class);
            try {
                String email = "";
                rs.executeQuery("select lyyx from uf_jcl_jlzjb where id = ? ", qllResumePo.getId());
                if (rs.next()) {
                    email = rs.getString("lyyx");
                }
                int creator = getCreator(rs, qllResumePo.getGjrsjh(), email);
                qllResumePo.setUserId(creator);
                baseBean.writeLog("千里聆简历解析开始，中间表ID=【" + qllResumePo.getId() + "】");
                RecruitDataMap<Object> dataMap = buildApplicantMap(qllResumePo);
                baseBean.writeLog("千里聆简历主表数据解析完成==" + JSON.toJSONString(dataMap));
                // 校验简历信息、并插入
                CheckRepeatResume instance = CheckRepeatResume.getInstance();
                Map<String, Object> checkMap = instance.insertResumeAndReturn(creator, dataMap);

                String mainId = Util.null2String(checkMap.get("mainId"));
                String sourceId = Util.null2String(checkMap.get("sourceId"));
                baseBean.writeLog("千里聆简历主表数据插入完成，mainId==【" + mainId + "】，sourceId==【" + sourceId + "】");

                boolean isSendStep = (boolean) checkMap.get("isSendStep");

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

                // 数据写入完成后，更新抽取状态为新插入的数据ID
                rs.executeUpdate("update uf_jcl_jlzjb set cqzt = 1 ,mainid = ? ,sourceid = ? where id = ? ", Convert.toInt(mainId), Convert.toInt(sourceId), qllResumePo.getId());

                // 插入明细表数据
                instance.insertResumeDetailTable(qllResumePo.getJyjl(), "uf_jcl_yppc_dt1", mainId, sourceId);
                instance.insertResumeDetailTable(qllResumePo.getGzjl(), "uf_jcl_yppc_dt2", mainId, sourceId);
                instance.insertResumeDetailTable(qllResumePo.getXmjl(), "uf_jcl_yppc_dt3", mainId, sourceId);
                baseBean.writeLog("千里聆简历解析完成，mainId==【" + mainId + "】，sourceId==【" + sourceId + "】");
            } catch (Exception e) {
                baseBean.writeLog("简历解析失败" + JSON.toJSONString(qllResumePo), e);
            }

        }
    }

    /**
     * 构建应聘者数据集合
     *
     * @param qllResumePo
     * @return
     */
    private RecruitDataMap<Object> buildApplicantMap(QllResumePo qllResumePo) {
        RecruitDataMap<Object> insertMap = new RecruitDataMap<>();
        // 姓名
        insertMap.put("xm", qllResumePo.getXm());
        // 性别
        insertMap.put("xb", qllResumePo.getXb());
        // 年龄
        insertMap.put("nl", qllResumePo.getNl());
        // 工作经验
        insertMap.put("gzjy", qllResumePo.getGzjy());
        // 手机号码
        insertMap.put("sjhm", qllResumePo.getSjhm());
        // 电子邮箱
        insertMap.put("dzyx", qllResumePo.getYx());
        // 自我评价
        insertMap.put("zwpj", qllResumePo.getGrys());
        // 最高学历
        insertMap.put("zgxl", qllResumePo.getZgxl());
        // 简历来源
        insertMap.put("jlly", qllResumePo.getLyqd());
        // 投递时间
        insertMap.put("tdsj", DateUtil.getDateTime());
        // 原始简历
        insertMap.put("ysjl", qllResumePo.getJlfj());
        // 投递职位（第三方）
        insertMap.put("tdzwdsf", qllResumePo.getYpzw());


        String zt = ApplicationStatusEnum.DISTRIBUTION.getValue();
        // 应聘职位
        String ypzw = PositionCommonInfo.getPositionIdByName(qllResumePo.getYpzw(), qllResumePo.getGjrsjh());
        baseBean.writeLog("投递职位==【" + qllResumePo.getYpzw() + "】,投递职位ID==【" + ypzw + "】");
        if (StringUtils.isNotBlank(ypzw)) {
            String flowId = PositionCommonInfo.getRecruitFlowId(ypzw);
            Map<String, String> initialStage = ApplicantCommonInfo.getInitialStage(flowId);
            if (null != initialStage) {
                baseBean.writeLog("initialStage===" + JSON.toJSONString(initialStage));
                String zpjd = initialStage.get("zpjd");
                String dqypjd = initialStage.get("jdlx");
                if (StringUtils.isNotBlank(zpjd) && StringUtils.isNotBlank(dqypjd)) {
                    insertMap.put("ypzw", ypzw);
                    insertMap.put("zplc", flowId);
                    insertMap.put("zpjd", zpjd);
                    insertMap.put("dqypjd", dqypjd);
                    zt = ApplicationStatusEnum.CANDIDATE.getValue();
                }
            }
        }
        // 应聘状态
        insertMap.put("zt", zt);

        // 更新毕业院校
        List<RecruitDataMap<Object>> studyList = qllResumePo.getJyjl();
        if (CollectionUtils.isNotEmpty(studyList)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<RecruitDataMap<Object>> sortedList = studyList.stream()
                    .sorted((map1, map2) -> {
                        String dateStr1 = Util.null2String(map1.get("bysj"));
                        String dateStr2 = Util.null2String(map2.get("bysj"));
                        if (StringUtils.isBlank(dateStr1)&& StringUtils.isBlank(dateStr2)) {
                            return 0;
                        }
                        if (StringUtils.isBlank(dateStr1)) {
                            return 1;
                        }
                        if (StringUtils.isBlank(dateStr2)) {
                            return -1;
                        }
                        try {
                            Date date1 = dateFormat.parse(dateStr1);
                            Date date2 = dateFormat.parse(dateStr2);
                            return date1.compareTo(date2);
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                    })
                    .collect(Collectors.toList());
            RecruitDataMap<Object> lastMap = sortedList.get(sortedList.size() - 1);
            String xxmc = Util.null2String(lastMap.get("xxmc"));
            if(StringUtils.isNotBlank(xxmc)){
                insertMap.put("byyx",xxmc);
            }
        }
        return insertMap;
    }


    private int getCreator(RecordSet rs, String phone, String email) {
        int uid = 1;
        if (StringUtils.isNotBlank(phone)) {
            rs.executeQuery("select id from hrmresource where mobile = ?", phone);
            if (rs.next()) {
                uid = Math.max(uid, rs.getInt("id"));
            }
        }

        if (StringUtils.isNotBlank(email)) {
            rs.executeQuery("select id from hrmresource where email = ?", email);
            if (rs.next()) {
                uid = Math.max(uid, rs.getInt("id"));
            }
        }

        return uid;
    }

}
