package com.engine.recruit.conn;

import com.engine.common.service.HrmCommonService;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.recruit.constant.RecruitConstant;
import com.engine.recruit.entity.message.PositionField;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.recruit.modeexpand.util.RecruitModeUtil;
import weaver.hrm.User;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:dxfeng
 * @createTime: 2024/10/16
 * @version: 1.0
 */
public class StepMsgCommonInfo {

    /**
     * 获取提醒人员
     *
     * @param applicantId 候选人ID
     * @param positionId  职位ID
     * @param flowId      流程ID
     * @param stepId      当前阶段ID
     * @param user        当前操作人
     */
    public static void sendMsg(String applicantId, String positionId, String flowId, String stepId, User user) {
        RecordSet rs = new RecordSet();
        List<String> ids = new ArrayList<>();
        boolean useFlowTips = true;
        String stepName = "";
        if (StringUtils.isNotBlank(stepId)) {
            rs.executeQuery("select id,jdmc,hj from uf_jcl_zpjdsz where sfqy = 0 and id = ? ", stepId);
        } else {
            rs.executeQuery("select id,jdmc,hj from uf_jcl_zpjdsz where sfqy = 0 and zplc = ? and hj = 0", flowId);
        }
        if (rs.next()) {
            stepId = rs.getString("id");
            stepName = rs.getString("jdmc");
        }
        rs.executeQuery("select qyzt from uf_jcl_step_config where zpzw = ?", positionId);
        if (rs.next()) {
            useFlowTips = !"1".equals(rs.getString("qyzt"));
        }
        if (!useFlowTips) {
            // 判断该职位是否设置提醒人员
            rs.executeQuery("select * from uf_jcl_jdtx where zpzw = ?", positionId);
            while (rs.next()) {
                useFlowTips = false;
                String zpjd = rs.getString("zpjd");
                if (StringUtils.isNotBlank(zpjd)) {
                    List<String> strings = Arrays.asList(zpjd.split(","));
                    if (strings.contains(stepId)) {
                        ids.add(rs.getString("id"));
                    }
                }
            }
        }

        if (useFlowTips) {
            // 判断是否启用全部配置，未启用直接跳过
            String qyzt = "";
            rs.executeQuery("select qyzt from uf_jcl_step_config where zpzw = -1");
            if (rs.next()) {
                qyzt = rs.getString("qyzt");
            }
            if ("1".equals(qyzt)) {
                // 查询当前流程的配置
                rs.executeQuery("select * from uf_jcl_jdtx where zpzw is null and zplc = ?", flowId);
                while (rs.next()) {
                    String zpjd = rs.getString("zpjd");
                    if (StringUtils.isNotBlank(zpjd)) {
                        List<String> strings = Arrays.asList(zpjd.split(","));
                        if (strings.contains(stepId)) {
                            ids.add(rs.getString("id"));
                        }
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(ids)) {
            Set<String> userSet = new HashSet<>();
            for (String id : ids) {
                Set<String> receiveUsers = getReceiveUsers(id, positionId);
                userSet.addAll(receiveUsers);
            }
            String applicantName = ApplicantCommonInfo.getApplicantName(applicantId);
            String applicantPosition = ApplicantCommonInfo.getApplicantPosition(positionId);
            // 发送消息提醒
            RecruitModeUtil.messagePush(RecruitConstant.INTERVIEW_MESSAGE_TYPE, "应聘进度通知", "应聘者：" + applicantName + "，应聘职位：" + applicantPosition + "，当前应聘进程已经流转至" + stepName + "阶段，请知悉。", userSet, user.getUID());
        }

    }

    /**
     * 获取当前职位、当前设置的提醒人员
     *
     * @param jdtxId
     * @param positionId
     * @return
     */
    private static Set<String> getReceiveUsers(String jdtxId, String positionId) {
        Set<String> userSet = new HashSet<>();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from uf_jcl_jdtx where id = ?", jdtxId);
        if (rs.next()) {
            // 提醒人员
            String txry = rs.getString("txry");
            getUserByUid(txry, userSet);
            // 提醒分部
            String txfb = rs.getString("txfb");
            getUserByCompany(txfb, userSet);
            // 提醒部门
            String txbm = rs.getString("txbm");
            getUserByDepartment(txbm, userSet);
            // 提醒岗位
            String txgw = rs.getString("txgw");
            getUserByJob(txgw, userSet);
            // 提醒角色
            String txjs = rs.getString("txjs");
            getUserByRole(txjs, userSet);
            String zpzwzd = rs.getString("zpzwzd");
            // 根据选择的字段，获取需要通知的人员ID
            dealPositionField(zpzwzd, positionId, userSet);
        }
        return userSet;
    }

    /**
     * 根据选择的招聘职位字段,获取需要通知的人员ID
     *
     * @param positionFieldIds
     * @param positionId
     * @param userSet
     */
    private static void dealPositionField(String positionFieldIds, String positionId, Set<String> userSet) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from workflow_billfield where id in(" + positionFieldIds + ")");
        List<PositionField> fieldList = new ArrayList<>();
        while (rs.next()) {
            PositionField build = PositionField.builder()
                    .id(rs.getString("id"))
                    .fieldName(rs.getString("fieldname"))
                    .type(rs.getString("type"))
                    .build();
            fieldList.add(build);
        }
        if (CollectionUtils.isNotEmpty(fieldList)) {
            Map<String, List<PositionField>> collect = fieldList.stream().collect(Collectors.groupingBy(PositionField::getMsgType));
            List<PositionField> userFieldList = collect.get("user");
            if (CollectionUtils.isNotEmpty(userFieldList)) {
                for (PositionField positionField : userFieldList) {
                    String positionFieldValue = getPositionFieldValue(positionField, positionId);
                    getUserByUid(positionFieldValue, userSet);
                }
            }
            List<PositionField> companyFieldList = collect.get("company");
            if (CollectionUtils.isNotEmpty(companyFieldList)) {
                for (PositionField positionField : companyFieldList) {
                    String positionFieldValue = getPositionFieldValue(positionField, positionId);
                    getUserByCompany(positionFieldValue, userSet);
                }
            }
            List<PositionField> departmentFieldList = collect.get("department");
            if (CollectionUtils.isNotEmpty(departmentFieldList)) {
                for (PositionField positionField : departmentFieldList) {
                    String positionFieldValue = getPositionFieldValue(positionField, positionId);
                    getUserByDepartment(positionFieldValue, userSet);
                }
            }
            List<PositionField> roleFieldList = collect.get("role");
            if (CollectionUtils.isNotEmpty(roleFieldList)) {
                for (PositionField positionField : roleFieldList) {
                    String positionFieldValue = getPositionFieldValue(positionField, positionId);
                    getUserByRole(positionFieldValue, userSet);
                }
            }
            List<PositionField> jobFieldList = collect.get("job");
            if (CollectionUtils.isNotEmpty(jobFieldList)) {
                for (PositionField positionField : jobFieldList) {
                    String positionFieldValue = getPositionFieldValue(positionField, positionId);
                    getUserByJob(positionFieldValue, userSet);
                }
            }
        }
    }


    private static void getUserByUid(String userStr, Set<String> userSet) {
        if (StringUtils.isNotBlank(userStr)) {
            userSet.addAll(Arrays.asList(userStr.split(",")));
        }
    }

    private static void getUserByCompany(String companyStr, Set<String> userSet) {
        if (StringUtils.isNotBlank(companyStr)) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from hrmresource where subcompanyid1 in(" + companyStr + ")");
            while (rs.next()) {
                userSet.add(rs.getString("id"));
            }
        }
    }

    private static void getUserByDepartment(String departmentStr, Set<String> userSet) {
        if (StringUtils.isNotBlank(departmentStr)) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from hrmresource where departmentid in(" + departmentStr + ")");
            while (rs.next()) {
                userSet.add(rs.getString("id"));
            }
        }
    }

    private static void getUserByRole(String roleStr, Set<String> userSet) {
        if (StringUtils.isNotBlank(roleStr)) {
            String[] split = roleStr.split(",");
            for (String roleId : split) {
                HrmCommonService hrmCommonService = new HrmCommonServiceImpl();
                String hrmIds = hrmCommonService.getRoleMemberIds(roleId, "0");
                if (StringUtils.isNotBlank(hrmIds)) {
                    userSet.addAll(Arrays.asList(hrmIds.split(",")));
                }

            }
        }
    }

    private static void getUserByJob(String jobStr, Set<String> userSet) {
        if (StringUtils.isNotBlank(jobStr)) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from hrmresource where jobtitle in(" + jobStr + ")");
            while (rs.next()) {
                userSet.add(rs.getString("id"));
            }
        }
    }

    /**
     * 获取当前职位的字段值
     *
     * @param positionField 指定字段
     * @param positionId    招聘职位ID
     * @return
     */
    private static String getPositionFieldValue(PositionField positionField, String positionId) {
        RecordSet rs = new RecordSet();
        String sql = "select " + positionField.getFieldName() + " from uf_jcl_zp_zpzw where id = " + positionId;
        rs.executeQuery(sql);
        if (rs.next()) {
            return rs.getString(positionField.getFieldName());
        } else {
            return "";
        }
    }


}
