package weaver.interfaces.recruit.action;

import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.engine.recruit.conn.ApplicantCommonInfo;
import com.engine.recruit.conn.RecruitRecordSet;
import com.engine.recruit.constant.RecruitConstant;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSetTrans;
import weaver.formmode.recruit.modeexpand.util.RecruitModeUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.io.IOException;
import java.util.*;

/**
 * <p>聚才林招聘</p>
 * 招聘需求流程明细表数据转建模台账
 *
 * @author:dxfeng
 * @createTime: 2023/09/01
 * @version: 1.0
 */
public class RecruitFlowToModeAction implements Action {

    private static String messageType;

    private static String title;

    private static String linkUrl;

    private static String linkMobileUrl;

    /**
     * 建模台账表表名(uf_jcl_zp_zpxq)
     */
    private static final String MODE_TABLE_NAME = "uf_jcl_zp_zpxq";

    @Override
    public String execute(RequestInfo requestInfo) {
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        int billId = requestInfo.getRequestManager().getBillid();
        int formid = requestInfo.getRequestManager().getFormid();
        User user = requestInfo.getRequestManager().getUser();

        DetailTableInfo detailTableInfo = requestInfo.getDetailTableInfo();
        DetailTable detailTable = detailTableInfo.getDetailTable(0);

        Map<String, Object> mainMap = new HashMap<>(16);
        // 需求审批流程ID
        mainMap.put("xqsplc", requestInfo.getRequestid());
        int formModeId = ApplicantCommonInfo.getModeIdByTableName(MODE_TABLE_NAME);

        Property[] propertyArray = mainTableInfo.getProperty();
        for (Property property : propertyArray) {
            mainMap.put(property.getName(), property.getValue());
        }

        mainMap.put("formmodeid", formModeId);
        mainMap.put("modedatacreater", requestInfo.getRequestManager().getCreater());
        String dateTime = DateUtil.getFullDate();
        String[] split = dateTime.split(" ");
        mainMap.put("modedatacreatedate", split[0]);
        mainMap.put("modedatacreatetime", split[1]);
        mainMap.put("modedatamodifier", null);
        mainMap.put("modedatamodifydatetime", null);
        mainMap.put("modedatacreatertype", "0");

        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("billId", String.valueOf(billId));
        messageMap.put("formId", String.valueOf(formid));
        messageMap.put("modeId", String.valueOf(formModeId));

        List<Map<String, Object>> insertList = new ArrayList<>();
        Row[] rows = detailTable.getRow();
        for (Row row : rows) {
            Map<String, Object> detailMap = new HashMap<>(16);
            detailMap.putAll(mainMap);
            Cell[] cells = row.getCell();
            for (Cell cell : cells) {
                detailMap.put(cell.getName(), RecruitModeUtil.parseBlankToNull(cell.getValue()));
            }
            insertList.add(detailMap);
        }

        // 数据插入处理
        if (CollectionUtils.isNotEmpty(insertList)) {
            // 插入建模表
            RecordSetTrans rst = new RecordSetTrans();
            rst.setAutoCommit(false);
            String sql = " insert into " + MODE_TABLE_NAME + "(modeuuid,modedatacreatertype,formmodeid,modedatacreater,modedatacreatedate,modedatacreatetime,modedatamodifier,modedatamodifydatetime,xqsplc,xqzt,sqr,sqsj,sqbm,nd,spfs,xqlx,bz,xqmc,zpyy,zpxqfzr,szfb,szbm,gw,gwzz,rzyq,zwxz,gzdd,gznx,zdxlyq,zprs,hcye,xqzhjd,qwdgsj)" +
                    " values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            try {

                for (Map<String, Object> map : insertList) {
                    List<Object> objects = buildParamList(map);
                    String uuid = UUID.randomUUID().toString();
                    objects.add(0, uuid);
                    rst.executeUpdate(sql, objects);
                    RecruitRecordSet.refreshRight(uuid, MODE_TABLE_NAME, formModeId, requestInfo.getRequestManager().getCreater());

                    // 申请人ID
                    String applicant = Util.null2String(map.get("sqr"));
                    // 申请人名称
                    String applicantName = new ResourceComInfo().getLastname(applicant);
                    // 需求名称
                    String requirementName = Util.null2String(map.get("xqmc"));
                    // 招聘需求负责人ID
                    String manager = Util.null2String(map.get("zpxqfzr"));
                    // 申请人集合
                    Set<String> applicantSet = new HashSet<>();
                    applicantSet.add(applicant);
                    // 需求负责人集合
                    Set<String> managerSet = new HashSet<>();
                    managerSet.add(manager);

                    // 获取消息类型默认值
                    if (StringUtils.isBlank(messageType)) {
                        messageType = RecruitConstant.RECRUIT_MESSAGE_TYPE;
                    }
                    if (StringUtils.isBlank(title)) {
                        title = "【招聘需求管理】";
                    }
                    if (StringUtils.isBlank(linkUrl)) {
                        linkUrl = "/spa/cube/index.html#/main/cube/card?type=0&modeId=$modeId$&formId=$formId$&billid=$billid$";
                    }
                    if (StringUtils.isBlank(linkMobileUrl)) {
                        linkMobileUrl = "/mobilemode/browserLinkTransit.jsp?billid=$billid$&modeId=$modeId$&formId=$formId$";
                    }
                    String url = replaceUrlKeys(linkUrl, messageMap);
                    String mobileUrl = replaceUrlKeys(linkMobileUrl, messageMap);
                    // 消息提醒
                    RecruitModeUtil.messagePush(messageType, applicantName + "，你申请的“" + requirementName + "”招聘需求，正在进行中，请知悉。", title, applicantSet, user.getUID(), url, mobileUrl);
                    RecruitModeUtil.messagePush(messageType, "您有一个新的”" + requirementName + "“招聘需求，请查收。", title, managerSet, user.getUID(), url, mobileUrl);
                }
                rst.commit();
            } catch (Exception e) {
                rst.rollback();
                new BaseBean().writeLog(e);
                requestInfo.getRequestManager().setMessagecontent("接口动作【RecruitFlowToModeAction】执行异常");
                return FAILURE_AND_CONTINUE;
            }
        }

        return SUCCESS;
    }


    /**
     * 构建插入参数集合
     *
     * @param map 表单数据集合
     * @return 待插入参数集合
     */
    private List<Object> buildParamList(Map<String, Object> map) {
        List<Object> param = new ArrayList<>();
        // 填充建模表相关字段
        param.add(map.get("modedatacreatertype"));
        param.add(map.get("formmodeid"));
        param.add(map.get("modedatacreater"));
        param.add(map.get("modedatacreatedate"));
        param.add(map.get("modedatacreatetime"));
        param.add(map.get("modedatamodifier"));
        param.add(map.get("modedatamodifydatetime"));
        // 需求审批流程
        param.add(map.get("xqsplc"));
        // 需求状态
        param.add(map.get("xqzt"));
        // 申请人
        param.add(map.get("sqr"));
        // 申请时间
        param.add(map.get("sqsj"));
        // 申请部门
        param.add(map.get("sqbm"));
        // 年度
        param.add(map.get("nd"));
        // 审批方式
        param.add(map.get("spfs"));
        // 需求类型
        param.add(map.get("xqlx"));
        // 备注
        param.add(map.get("bz"));
        // 需求名称
        param.add(map.get("xqmc"));
        // 招聘原因
        param.add(map.get("zpyy"));
        // 招聘需求负责人
        param.add(map.get("zpxqfzr"));
        // 所属分部
        param.add(map.get("szfb"));
        // 所属部门
        param.add(map.get("szbm"));
        // 岗位
        param.add(map.get("gw"));
        // 岗位职责
        param.add(map.get("gwzz"));
        // 任职要求
        param.add(map.get("rzyq"));
        // 职位性质
        param.add(map.get("zwxz"));
        // 工作地点
        param.add(map.get("gzdd"));
        // 工作年限
        param.add(map.get("gznx"));
        // 最低学历要求
        param.add(map.get("zdxlyq"));
        // 招聘人数
        param.add(map.get("zprs"));
        // 	hc余额
        param.add(map.get("zprs"));
        // 需求执行进度
        param.add(0);
        // 期望到岗时间
        param.add(map.get("qwdgsj"));
        return param;
    }


    /**
     * 消息推送
     *
     * @param context    消息内容
     * @param messageMap 消息 相关key
     * @param userIdList 消息接收人ID集合
     */
    private static void messagePush(String context, Map<String, String> messageMap, Set<String> userIdList) {

        // 替换context内容信息;

        // 替换URL内容信息
        linkUrl = replaceUrlKeys(linkUrl, messageMap);
        linkMobileUrl = replaceUrlKeys(linkMobileUrl, messageMap);

        MessageType message = MessageType.newInstance(Integer.parseInt(messageType));
        try {
            MessageBean messageBean = Util_Message.createMessage(message, userIdList, title, context, linkUrl, linkMobileUrl);
            messageBean.setCreater(1);
            //message.setBizState("0");// 需要修改消息为已处理等状态时传入,表示消息最初状态为待处理
            Util_Message.store(messageBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 替换url的相关key
     *
     * @param url        链接地址
     * @param messageMap key集合
     */
    private static String replaceUrlKeys(String url, Map<String, String> messageMap) {
        return url.replace("$modeId$", messageMap.get("modeId")).replace("$formId$", messageMap.get("formId")).replace("$billid$", messageMap.get("billId"));
    }

    public static String getMessageType() {
        return messageType;
    }

    public static void setMessageType(String messageType) {
        RecruitFlowToModeAction.messageType = messageType;
    }

    public static String getTitle() {
        return title;
    }

    public static void setTitle(String title) {
        RecruitFlowToModeAction.title = title;
    }

    public static String getLinkUrl() {
        return linkUrl;
    }

    public static void setLinkUrl(String linkUrl) {
        RecruitFlowToModeAction.linkUrl = linkUrl;
    }

    public static String getLinkMobileUrl() {
        return linkMobileUrl;
    }

    public static void setLinkMobileUrl(String linkMobileUrl) {
        RecruitFlowToModeAction.linkMobileUrl = linkMobileUrl;
    }
}
