package com.engine.recruit.conn;

import com.engine.recruit.enums.ApplicationStatusEnum;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author:dxfeng
 * @createTime: 2023/10/26
 * @version: 1.0
 */
public class CheckRepeatResume {

    private static CheckRepeatResume instance = new CheckRepeatResume();

    private CheckRepeatResume() {
        // 私有化构造方法
    }

    public static CheckRepeatResume getInstance() {
        return instance;
    }


    /**
     * 校验简历是否加入黑名单
     *
     * @param name   姓名
     * @param mobile 手机号
     * @return
     */
    public static boolean joinBlackList(String name, String mobile) {
        // 在这里编写你的方法逻辑
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from uf_jcl_rck where sfjrhmd =0 and xm = ? and sjhm = ?", name, mobile);
        return rs.next();
    }

    /**
     * @param name
     * @param mobile
     * @param positionId
     * @return
     */
    public static List<Map<String, Object>> getRepeatPositionResumeList(String name, String mobile, String positionId) {
        return getRepeatPositionResumeList(name, mobile, positionId, "");
    }

    /**
     * @param name
     * @param mobile
     * @param positionId
     * @param billId
     * @return
     */
    public static List<Map<String, Object>> getRepeatPositionResumeList(String name, String mobile, String positionId, String billId) {
        RecordSet rs = new RecordSet();
        // 查询状态为待分配、候选中的且未隐藏的数据
        String whereSql = "";
        if (StringUtils.isBlank(positionId)) {
            whereSql = " and (ypzw = ? or ypzw is null) ";
        } else {
            whereSql = " and ypzw = ? ";
        }
        rs.executeQuery("select * from uf_jcl_yppc where formmodeid is not null and zt != 2 and zt != 3 and xm = ? and sjhm = ? " + whereSql + " and id != ? order by zt", name, mobile, positionId, billId);
        return RecruitRecordSet.getRecordMapList(rs);
    }

    /**
     * 根据姓名、手机号查询重复的简历数据
     *
     * @param name   姓名
     * @param mobile 手机号
     * @return
     */
    private List<Map<String, Object>> getRepeatResumeList(String name, String mobile) {
        RecordSet rs = new RecordSet();
        // 查询状态为待分配、候选中的且未隐藏的数据
        rs.executeQuery("select * from uf_jcl_yppc where formmodeid is not null and zt != 2 and zt != 3 and xm = ? and sjhm =? order by zt", name, mobile);
        return RecruitRecordSet.getRecordMapList(rs);
    }

    /**
     * 插入简历数据
     *
     * @param param 数据集合
     * @return 新插入简历的ID
     */
    public int insertResumeMainTable(int creator, Map<String, Object> param) {
        Map<String, Object> map = insertResumeAndReturn(creator, param);
        return Util.getIntValue(Util.null2String(map.get("mainId")));
    }


    /**
     * 插入、更新明细表数据
     *
     * @param detailDataList
     * @param tableName
     * @param mainId
     * @param sourceId
     */
    public synchronized void insertResumeDetailTable(List<RecruitDataMap<Object>> detailDataList, String tableName, String mainId, String sourceId) {
        if (CollectionUtils.isEmpty(detailDataList)) {
            return;
        }
        boolean isUpdate = false;
        if (StringUtils.isNotBlank(sourceId)) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select * from " + tableName + " where mainid = ? ", sourceId);
            isUpdate = rs.getCounts() == 0;
        }
        try {
            for (RecruitDataMap<Object> dataMap : detailDataList) {
                // 明细表关联新数据
                dataMap.put("mainid", mainId);
                RecruitRecordSet.insertData(dataMap, tableName);
                // 明细表关联已有数据
                if (isUpdate) {
                    dataMap.put("mainid", sourceId);
                    RecruitRecordSet.insertData(dataMap, tableName);
                }

            }
        } catch (Exception e) {
            new BaseBean().writeLog(tableName + "明细表数据插入失败", e);
        }
    }

    /**
     * 插入简历数据
     *
     * @param param 数据集合
     * @return 简历插入信息
     */
    public synchronized Map<String, Object> insertResumeAndReturn(int creator, Map<String, Object> param) {
        Map<String, Object> returnMap = new HashMap<>();
        int mainId = -1;
        String sourceId;
        String name = Util.null2String(param.get("xm"));
        String mobile = Util.null2String(param.get("sjhm"));
        String status = Util.null2String(param.get("zt"));
        String positionId = Util.null2String(param.get("ypzw"));
        // 黑名单校验，黑名单人员不入库
        boolean joinBlackList = joinBlackList(name, mobile);
        returnMap.put("joinBlackList", joinBlackList);
        returnMap.put("isUpdate", false);
        returnMap.put("mainId", mainId);
        returnMap.put("isSendStep", false);
        if (joinBlackList) {
            return returnMap;
        }

        // 按照姓名+手机号查询正常展示的简历数据
        List<Map<String, Object>> repeatResumeList = getRepeatResumeList(name, mobile);
        if (CollectionUtils.isEmpty(repeatResumeList)) {
            // 不存在重复数据，直接插入数据库
            mainId = insertData(creator, param);
            returnMap.put("mainId", mainId);
            returnMap.put("isSendStep", true);
            return returnMap;
        }

        // 新接收的简历为待分配
        if (ApplicationStatusEnum.DISTRIBUTION.getValue().equals(status)) {
            Map<String, Object> sourceResume = repeatResumeList.get(0);
            if (ApplicationStatusEnum.DISTRIBUTION.getValue().equals(Util.null2String(sourceResume.get("zt")))) {
                // 当前存在待分配的简历
                sourceId = Util.null2String(sourceResume.get("id"));
                //取新简历有值的字段，更新已入库简历没有值的字段，已入库简历有值的字段不做更新，新简历入库并隐藏
                mainId = updateSourceResume(creator, param, sourceResume);
                returnMap.put("mainId", mainId);
                returnMap.put("sourceId", sourceId);
                returnMap.put("isUpdate", true);
                returnMap.put("isSendStep", false);
                return returnMap;
            } else {
                // 直接入库，不做任何处理
                mainId = insertData(creator, param);
                returnMap.put("mainId", mainId);
                returnMap.put("isSendStep", true);
                return returnMap;
            }
        } else if (ApplicationStatusEnum.CANDIDATE.getValue().equals(status)) {
            // 新简历为候选中
            boolean hasSamePosition = false;
            for (Map<String, Object> sourceResume : repeatResumeList) {
                if (positionId.equals(Util.null2String(sourceResume.get("ypzw")))) {
                    hasSamePosition = true;
                }
            }
            if (hasSamePosition) {
                // 若有相同职位的数据，新简历直接入库并隐藏
                mainId = insertHideData(creator, param);
                returnMap.put("mainId", mainId);
                returnMap.put("isSendStep", false);
                return returnMap;
            } else {
                // 没有相同职位的数据，新简历直接入库，不做任何处理
                mainId = insertData(creator, param);
                returnMap.put("mainId", mainId);
                returnMap.put("isSendStep", true);
                return returnMap;
            }
        }
        return returnMap;
    }


    /**
     * 直接插入简历信息
     *
     * @param dataMap 数据集合
     * @return
     */
    private int insertData(int creator, Map<String, Object> dataMap) {
        String uuid = UUID.randomUUID().toString();
        dataMap.put("modeuuid", uuid);
        int formModeId = ApplicantCommonInfo.getModeIdByTableName("uf_jcl_yppc");
        dataMap.put("formmodeid", formModeId);
        RecruitRecordSet.buildModeInsertFields(dataMap, creator);
        RecruitRecordSet.insertData(dataMap, "uf_jcl_yppc");
        return RecruitRecordSet.refreshRight(uuid, "uf_jcl_yppc", formModeId, creator);
    }

    /**
     * 插入数据库并隐藏
     *
     * @param dataMap 数据集合
     * @return
     */
    private int insertHideData(int creator, Map<String, Object> dataMap) {
        String uuid = UUID.randomUUID().toString();
        dataMap.put("modeuuid", uuid);
        RecordSet rs = new RecordSet();
        RecruitRecordSet.buildModeInsertFields(dataMap, creator);
        RecruitRecordSet.insertData(dataMap, "uf_jcl_yppc");
        rs.executeQuery("select id from uf_jcl_yppc where modeuuid='" + uuid + "'");
        if (rs.next()) {
            return Util.getIntValue(rs.getString("id"));
        }
        return -1;
    }

    /**
     * 更新简历信息
     *
     * @param param        新简历数据集合
     * @param sourceResume 源简历数据集合
     * @return
     */
    private int updateSourceResume(int creator, Map<String, Object> param, Map<String, Object> sourceResume) {
        replaceNullValues(param, sourceResume);
        // 更新投递时间为最新的 by zsy 20240704 待分配的投递时间要根据最新的去更新
        sourceResume.put("tdsj", DateUtil.getDateTime());
        // 处理操作人员、操作时间
        RecruitRecordSet.buildModeUpdateFields(sourceResume, creator);
        RecruitRecordSet.updateDataById(sourceResume, "uf_jcl_yppc");
        // 更新数据
        RecruitRecordSet.buildModeInsertFields(param, creator);
        return insertHideData(creator, param);
    }


    /**
     * 替换sourceResume中为null或者为空的值
     *
     * @param param        新简历数据集合
     * @param sourceResume 源简历数据集合
     */
    private void replaceNullValues(Map<String, Object> param, Map<String, Object> sourceResume) {
        for (Map.Entry<String, Object> entry : sourceResume.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (value == null || "".equals(value)) {
                if (param.containsKey(key)) {
                    sourceResume.put(key, param.get(key));
                }
            }
        }
    }


    /**
     * 获取开始时间和结束时间
     *
     * @param date
     * @return
     */
    public static RecruitDataMap<Object> getDateRange(String date, boolean isStudy) {
        RecruitDataMap<Object> dataRangeMap = new RecruitDataMap();
        if (StringUtils.isBlank(date)) {
            return dataRangeMap;
        } else {
            String[] split = date.split("-");
            String end;
            if (split.length > 0) {
                end = getFormatDate(split[0]);
                if (end.length() == 4) {
                    if (isStudy) {
                        end = end + "-09-01";
                    } else {
                        end = "";
                    }
                }

                dataRangeMap.put("kssj", end);
            }

            if (split.length > 1) {
                end = getFormatDate(split[1]);
                if (end.length() == 4) {
                    if (isStudy) {
                        end = end + "-07-01";
                    } else {
                        end = "";
                    }
                }

                dataRangeMap.put("jssj", end);
            }

            return dataRangeMap;
        }
    }

    /**
     * 获取yyyy-MM-dd时间格式日期
     *
     * @param dateStr
     * @return
     */
    private static String getFormatDate(String dateStr) {
        //
        dateStr = dateStr.replace(".", "-").replace("\\/", "-");
        if (dateStr.length() == 7) {
            return dateStr + "-01";
        } else if (dateStr.length() == 10) {
            return dateStr;
        } else if (dateStr.length() == 4) {
            return dateStr;
        }
        return "";
    }


}
