package weaver.formmode.recruit.modeexpand.interview;

import com.engine.recruit.conn.ApplicantCommonInfo;
import com.engine.recruit.constant.RecruitConstant;
import com.engine.recruit.enums.InterviewOperateTypeEnum;
import com.weaver.formmodel.data.model.Formfield;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew;
import weaver.formmode.recruit.modeexpand.util.RecruitModeUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

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

/**
 * @author:dxfeng
 * @createTime: 2023/09/27
 * @version: 1.0
 */
public class UpdateInterviewModeExpand extends AbstractModeExpandJavaCodeNew {

    private static final String MODE_TABLE_NAME = "uf_jcl_ms";

    /**
     * 消息来源ID
     */
    private String messageType;

    /**
     * 消息提醒标题
     */
    private String title;

    @Override
    public Map<String, String> doModeExpand(Map<String, Object> params) {
        Map<String, String> result = new HashMap<>();
        try {
            //数据id
            int billId;
            //模块id
            int modeId;
            RequestInfo requestInfo = (RequestInfo) params.get("RequestInfo");
            if (requestInfo != null) {
                billId = Util.getIntValue(requestInfo.getRequestid());
                modeId = Util.getIntValue(requestInfo.getWorkflowid());
                if (billId > 0 && modeId > 0) {
                    User user = (User) params.get("user");
                    MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
                    Property[] properties = mainTableInfo.getProperty();
                    Map<String, Object> mainDataMap = new HashMap<>();
                    for (Property property : properties) {
                        mainDataMap.put(property.getName(), property.getValue());
                    }

                    String operateType = Util.null2String(params.get("operateType"));
                    if (StringUtils.isBlank(operateType)) {
                        // 为空则默认为新建布局、安排面试
                        operateType = InterviewOperateTypeEnum.ARRANGE.getOperateType();
                    }
                    InterviewOperateTypeEnum operateTypeEnum = InterviewOperateTypeEnum.getOperateType(operateType);
                    switch (operateTypeEnum) {
                        case EVALUATE:
                            // 面试评价
                            messageType = RecruitConstant.INTERVIEW_MESSAGE_TYPE;
                            title = RecruitConstant.INTERVIEW_EVALUATE_MESSAGE_TITLE;
                            evaluateInterview(params, requestInfo.getCreatorid(), mainDataMap);
                            break;
                        case CANCEL:
                            // 面试取消
                            messageType = RecruitConstant.INTERVIEW_MESSAGE_TYPE;
                            title = RecruitConstant.INTERVIEW_CANCEL_MESSAGE_TITLE;
                            cancelInterView(params, requestInfo, billId, mainDataMap);
                            // 更新面试评价状态为已取消
                            InterviewEvaluate.cancelEvaluate(billId);
                            // 发送邮件
                            InterviewMsgUtil.sendEmailAndMsg(mainDataMap, billId, false);
                            break;
                        case ADJUSTMENT:
                            // 更新面试评价
                            InterviewEvaluate.updateEvaluate(mainDataMap, billId, user);

                            messageType = RecruitConstant.INTERVIEW_MESSAGE_TYPE;
                            title = RecruitConstant.INTERVIEW_ADJUSTMENT_MESSAGE_TITLE;
                            // 发送消息提醒
                            adjustmentInterView(requestInfo.getCreatorid(), mainDataMap);
                            boolean needFeedback = "1".equals(Util.null2String(mainDataMap.get("sfxyfk")));
                            // 发送邮件、同安排面试
                            InterviewMsgUtil.sendEmailAndMsg(mainDataMap, billId, needFeedback);
                            // 更新反馈状态为未反馈
                            break;
                        default:
                            break;
                    }

                }
            }
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            result.put("errmsg", "自定义出错信息");
            result.put("flag", "false");
        }

        return result;
    }

    /**
     * 面试评价操作拓展动作
     *
     * @param params      params
     * @param creater     creater
     * @param mainDataMap mainDataMap
     */
    private void evaluateInterview(Map<String, Object> params, String creater, Map<String, Object> mainDataMap) {
        String ypz = Util.null2String(mainDataMap.get("ypz"));
        String ypzw = Util.null2String(mainDataMap.get("ypzw"));
        String msfkr = Util.null2String(mainDataMap.get("msfkr"));
        String msrq = Util.null2String(mainDataMap.get("msrq"));
        String msg = Util.null2String(mainDataMap.get("msg"));
        String ptmsg = Util.null2String(mainDataMap.get("ptmsg"));
        String jg = Util.null2String(mainDataMap.get("jg"));
        String formId = Util.null2String(params.get("formId"));

        StringBuilder msgBuilder = new StringBuilder();
        msgBuilder.append(RecruitModeUtil.getResourceNames(msfkr)).append("已经提交了面试评价");
        msgBuilder.append("<br/>");
        msgBuilder.append("应聘者：").append(ApplicantCommonInfo.getApplicantName(ypz)).append("；应聘职位：").append(ApplicantCommonInfo.getApplicantPosition(ypzw));
        msgBuilder.append("<br/>");
        msgBuilder.append("面试时间：").append(msrq).append("；面试官：").append(RecruitModeUtil.getResourceNames(msg)).append("，").append(RecruitModeUtil.getResourceNames(ptmsg));
        msgBuilder.append("<br/>");
        msgBuilder.append("面试结果：").append(ApplicantCommonInfo.getSelectName(formId, "jg", jg));

        User user = (User) params.get("user");

        // 消息发送,通知创建人
        Set<String> userIdSet = new HashSet<>();
        userIdSet.add(creater);
        RecruitModeUtil.messagePush(messageType, title, msgBuilder.toString(), userIdSet, user.getUID());
    }


    /**
     * 取消面试拓展动作
     *
     * @param params      params
     * @param requestInfo requestInfo
     * @param billId      billId
     * @param mainDataMap mainDataMap
     */
    private void cancelInterView(Map<String, Object> params, RequestInfo requestInfo, int billId, Map<String, Object> mainDataMap) {
        // 更新面试状态为“已取消”
        RecordSet rs = new RecordSet();
        rs.executeUpdate("update " + MODE_TABLE_NAME + " set zt = 4 where id = ?", billId);

        // 发送消息
        String msrq = Util.null2String(mainDataMap.get("msrq"));
        String msg = Util.null2String(mainDataMap.get("msg"));
        String ptmsg = Util.null2String(mainDataMap.get("ptmsg"));
        String msdd = Util.null2String(mainDataMap.get("msdd"));
        String formId = Util.null2String(params.get("formId"));

        StringBuilder msgBuilder = new StringBuilder();
        msgBuilder.append(RecruitModeUtil.getResourceNames(requestInfo.getCreatorid())).append("取消了面试，请知悉。取消原因：").append(ApplicantCommonInfo.getSelectName(formId, "qxyy", Util.null2String(mainDataMap.get("qxyy")))).append("<br/>");

        msgBuilder.append("应聘者：").append(ApplicantCommonInfo.getApplicantName(Util.null2String(mainDataMap.get("ypz"))));
        msgBuilder.append("；应聘职位：").append(ApplicantCommonInfo.getApplicantPosition(Util.null2String(mainDataMap.get("ypzw"))));
        msgBuilder.append("<br/>");

        msgBuilder.append("面试时间：").append(msrq).append("；面试官：").append(RecruitModeUtil.getResourceNames(msg)).append("，").append(RecruitModeUtil.getResourceNames(ptmsg)).append("<br/>");
        msgBuilder.append("面试地址：").append(msdd);

        // 消息发送
        Set<String> userIdSet = new HashSet<>();
        userIdSet.addAll(Arrays.asList(msg.split(",")));
        userIdSet.addAll(Arrays.asList(ptmsg.split(",")));
        RecruitModeUtil.messagePush(messageType, title, msgBuilder.toString(), userIdSet, Integer.parseInt(requestInfo.getCreatorid()));

    }

    /**
     * 调整面试拓展动作
     *
     * @param creator     creator
     * @param mainDataMap mainDataMap
     */
    private void adjustmentInterView(String creator, Map<String, Object> mainDataMap) {
        // 发送消息
        String msg = Util.null2String(mainDataMap.get("msg"));
        String ptmsg = Util.null2String(mainDataMap.get("ptmsg"));

        String msgContent = "您有一条面试已调整，调整后的面试信息如下：<br/>" +
                "应聘者：$ypz$；应聘职位：$ypzw$<br/>" +
                "面试官：$msg$；陪同面试官：$ptmsg$<br/>" +
                "面试时间：$msrq$；面试方式：$msfs$<br/>" +
                "面试地址：$msdd$";

        // 消息发送
        Set<String> userIdSet = new HashSet<>();
        userIdSet.addAll(Arrays.asList(msg.split(",")));
        userIdSet.addAll(Arrays.asList(ptmsg.split(",")));
        List<Formfield> fieldList = RecruitModeUtil.getFieldList(MODE_TABLE_NAME);
        Map<String, Formfield> fieldMap = fieldList.stream().collect(Collectors.toMap(Formfield::getFieldname, item -> item, (k1, k2) -> k1));
        String msgStr = RecruitModeUtil.getMsgReplaceStr(msgContent, fieldMap, mainDataMap);
        RecruitModeUtil.messagePush(messageType, title, msgStr, userIdSet, Integer.parseInt(creator));
    }

}
