package com.customization.htsc.lhywxz;

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.common.util.ParamUtil;
import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.integration.util.StringUtils;
import com.engine.workflow.cmd.requestForm.RequestSubmitCmd;
import com.engine.workflow.entity.requestForm.RequestOperationResultBean;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@CommandDynamicProxy(target = RequestSubmitCmd.class, desc = "领导审阅意见通知")
public class LeaderSetMessageCmd extends AbstractCommandProxy<Map<String, Object>> {
    BaseBean bs = new BaseBean();
    PropBean pb = new PropBean();
    

    @Override
    public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
        //获取到被代理对象
        RequestSubmitCmd requestSubmitCmd = (RequestSubmitCmd) targetCommand;
        HttpServletRequest request = requestSubmitCmd.getRequest();//从request中可以取到参数，不用以前的方法了
        String src = Util.null2String(request.getParameter("src"));
        //执行标准的业务处理
        Map<String, Object> result = nextExecute(targetCommand);
        RequestOperationResultBean resultBean = (RequestOperationResultBean) result.get("data");
        String type = Util.null2String(resultBean.getType());
        //加工
        bs.writeLog("==========领导审阅意见通知============");
        String workflowid = Util.null2String(request.getParameter("workflowid"));
        String lhqssp_workflowid = Util.null2String(pb.getPropName("lhqssp.workflowid"));
        bs.writeLog("request.workflowid" + workflowid);
        bs.writeLog("lhqssp.workflowid" + lhqssp_workflowid);
        if ((workflowid.equals(lhqssp_workflowid)) && ("submit".equalsIgnoreCase(src) || "reject".equalsIgnoreCase(src)) && "SUCCESS".equalsIgnoreCase(type) && needNotice(request)) {
            bs.writeLog("==========领导审阅意见通知触发============");
            try {
                String remark = Util.null2String(request.getParameter("remark"));
                remark = remark.replaceAll("[\\s\\t\\n\\r]", "");
                if (!("已阅".equals(remark) || "同意".equals(remark))) {
                    bs.writeLog("need notice");
                    getMessageContext(request);
                }
            } catch (Exception e) {
                e.printStackTrace();
                bs.writeLog("send leader notice error:", e);
            }
        }
        return result;
    }


    /**
     * 是否需要通知
     * @param request
     * @return
     */
    private boolean needNotice(HttpServletRequest request) {
        Map<String, Object> map222 = ParamUtil.request2Map(request);
        bs.writeLog("request中的参数："+map222);
        bs.writeLog("=======是否需要通知========");
        bs.writeLog("remark:" + request.getParameter("remark"));
        bs.writeLog("workflowid:" + request.getParameter("workflowid"));
        bs.writeLog("nodeid:" + request.getParameter("nodeid"));
        bs.writeLog("requestid:" + request.getParameter("requestid"));
        try {
            //获取工作流程id
            String workflowid = Util.null2String(request.getParameter("workflowid"));
            //获取操作节点id
            String nodeid = Util.null2String(request.getParameter("nodeid"));
            //从配置信息获取公司收文领导审阅流程的UnNumber
            String gsswldsy_workflowid = pb.getActiveWorkflowIdByUnNumber(pb.getPropName("lhqssp.unnumbe"));
            //从配置信息获取公司收文领导审阅节点
            String gsswldsy_ldsy_nodeid = pb.getActionNodeIdByUnNumber(pb.getPropName("lhqssp.nodeunnumber.lhqssp_gsld"));
            String lhqssq_xgrysh = Util.null2String(pb.getPropName("lhqssp.nodeunnumber.lhqssp_xgrysh"));
            String operator = Util.null2String(request.getParameter("f_weaver_belongto_userid"));
            bs.writeLog("f_weaver_belongto_userid:"+operator);
            String agentorbyagentid = Util.null2String( request.getParameter("agentorByAgentId"));
            bs.writeLog("agentorbyagentid:"+agentorbyagentid);
            List<String> departmentUserId = getDepartmentUserId();
            List<String> xgryLeaderList = new ArrayList();
            //获取相关人员节点ID
            String sql = "select id from workflow_nodebase where 1=1 ";
            if (!StringUtils.isBlank(lhqssq_xgrysh)) {
                sql += "and UNNUMBER ='" + lhqssq_xgrysh + "'";
            }
            bs.writeLog(sql);
            String remark = Util.null2String(request.getParameter("remark").trim());
            bs.writeLog("留言remark:"+remark);
            //相关人员节点操作
            bs.writeLog("nodeid:"+nodeid);
            Map<String, Object> map = JAVATools.GetTableToMap(sql, null);
            String xgryNodeid = Util.null2String(map.get("id"));
            if(xgryNodeid.equals(nodeid) && remark.length()>=5){
                if ((!"".equals(operator) && departmentUserId.contains(operator))){
                    //当前节点操作者为公司领导
                    xgryLeaderList.add(operator);
                    bs.writeLog("========领导直接操作=============");
                }else{
                    bs.writeLog("===========其他人员操作============");
                    if(!"-1".equals(agentorbyagentid) && departmentUserId.contains(agentorbyagentid)){
                        xgryLeaderList.add(agentorbyagentid);
                        bs.writeLog("=====领导代理人操作====");
                    }
                }

            }
            if ((xgryLeaderList.size() > 0) || (workflowid.equals(gsswldsy_workflowid) && nodeid.equals(gsswldsy_ldsy_nodeid) && remark.length() >= 5)) {
                bs.writeLog("====开启通知=====");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            bs.writeLog("check notice need error:", e);
        }
        bs.writeLog("=====没有通知====");
        return false;
    }

    /**
     * 获得接收人id
     *
     * @param request
     * @return
     */
    private Set<String> getSendUserId(HttpServletRequest request) {
        Set<String> sendIdSet = new HashSet<>();
        String lhqssq_xgrysh = Util.null2String(pb.getPropName("lhqssp.nodeunnumber.lhqssp_xgrysh"));
        String lhqssq_gsld = Util.null2String(pb.getPropName("lhqssp.nodeunnumber.lhqssp_gsld"));
        String requestid = Util.null2String(request.getParameter("requestid"));
        //获取领导节点ID
        String sql = "select id from workflow_nodebase where 1=1 ";
        if (!StringUtils.isBlank(lhqssq_gsld)) {
            sql += "and UNNUMBER ='" + lhqssq_gsld + "'";
        }
        bs.writeLog(sql);
        Map<String, Object> leaderIdMap = JAVATools.GetTableToMap(sql, null);
        String leaderId = Util.null2String(leaderIdMap.get("id"));
        //获取相关人员节点ID
        String sql3 = "select id from workflow_nodebase where 1=1 ";
        if (!StringUtils.isBlank(lhqssq_xgrysh)) {
            sql3 += "and UNNUMBER ='" + lhqssq_xgrysh + "'";
        }
        bs.writeLog(sql3);
        Map<String, Object> xgryIdMap = JAVATools.GetTableToMap(sql3, null);
        String xgryId = Util.null2String(xgryIdMap.get("id"));
        //将所有人放入sendIdSet,除去领导，对代理人员进行判断
        String sql1 = " select agentorbyagentid,(select departmentid from hrmresource where id = agentorbyagentid ) as agentdepartmentid, " +
                " nodeid,OPERATOR,(select departmentid from hrmresource where id = OPERATOR ) as userdepartmentid " +
                " from workflow_requestlog " +
                " where requestid='" + requestid + "'and nodeid not in ('" + leaderId + "') ";
        bs.writeLog(sql1);
        List<Map<String, Object>> list = JAVATools.GetTableToListMap(sql1, null);
        for (Map<String, Object> map : list) {
            //操作者用户ID
            String userid = Util.null2String(map.get("operator"));
            sendIdSet.add(userid);
        }
        bs.writeLog(sendIdSet.size());
        //相关人员操作
        String sql2 = " select agentorbyagentid,OPERATOR " +
                "from workflow_requestlog  where REQUESTID='" + requestid + "' and NODEID ='" + xgryId + "'";
        bs.writeLog(sql2);
        List<Map<String, Object>> list1 = JAVATools.GetTableToListMap(sql2, null);
        List<String> useridList = new ArrayList<>();
        for (Map<String, Object> userIdMap : list1) {
            String userid = Util.null2String(userIdMap.get("operator"));
            useridList.add(userid);
        }
        bs.writeLog(useridList.size());
        //得到领导部门的所有用户ID
        List<String> departmentUserIdList = getDepartmentUserId();
        //得到相关人员和领导部门相同的用户ID
        for (String uId : useridList) {
            if (departmentUserIdList.contains(uId)) {
                sendIdSet.remove(uId);
            } else {
                //移除领导代理人
                String sql4 = " select agentorbyagentid from workflow_requestlog where REQUESTID ='" + requestid + "'  and OPERATOR = '" + uId + "' ";
                bs.writeLog(sql4);
                List<Map<String, Object>> agentorMapList = JAVATools.GetTableToListMap(sql4, null);
                for (Map<String, Object> agentorMap : agentorMapList) {
                    String agentorbyagentid = Util.null2String(agentorMap.get("agentorbyagentid"));
                    if (departmentUserIdList.contains(agentorbyagentid)) {
                        sendIdSet.remove(uId);
                    }
                }
            }
        }
        bs.writeLog(sendIdSet.size());
        return sendIdSet;
    }

    /**
     * 配置文件中领导部门id对应的用户id
     *
     * @return
     */
    public List<String> getDepartmentUserId() {
        String deptvalues = Util.null2String(pb.getPropName("lhqssp.leaddeptvalue"));
        String deptvalue = String.join("','", deptvalues.split(","));
        String sql = " select t1.id from HRMRESOURCE t1 " +
                " left join HRMDEPARTMENT t2 " +
                " on t1.DEPARTMENTID = t2.ID " +
                " WHERE t2.DEPARTMENTCODE in ('" + deptvalue + "')";
        bs.writeLog(sql);
        List<Map<String, Object>> list = JAVATools.GetTableToListMap(sql, null);
        List<String> userIdList = new ArrayList<>();
        for (Map<String, Object> userIdMap : list) {
            String leaderUserId = Util.null2String(userIdMap.get("id"));
            userIdList.add(leaderUserId);
        }
        return userIdList;
    }

    /**
     * 获取消息详情
     *
     * @param request
     */
    public void getMessageContext(HttpServletRequest request) {
        //获取主流程ID
        String requestid = Util.null2String(request.getParameter("requestid"));
        String sql = "select REQUESTNAME from WORKFLOW_REQUESTBASE  where REQUESTID = '" + requestid + "' ";
        bs.writeLog(sql);
        Map<String, Object> mianRequestIdMap = JAVATools.GetTableToMap(sql, null);
        String requestName = Util.null2String(mianRequestIdMap.get("requestname"));
        Set<String> sendUserId = getSendUserId(request);
        bs.writeLog("接收人的ID:" + sendUserId);
        String title = "领导审阅意见通知";
        String context = "请及时关注" + requestName + "流程中的公司领导意见！";
        bs.writeLog(context);
        String linkUrl = "";
        String linkMobileUrl = "";
        sendMessage(sendUserId, title, context, linkUrl, linkMobileUrl);
    }

    /**
     * 发送消息提醒
     *
     * @param sendIdSet
     * @param title
     * @param context
     * @param linkUrl
     * @param linkMobileUrl
     */
    private void sendMessage(Set<String> sendIdSet, String title, String context, String linkUrl, String linkMobileUrl) {
        //领导审批意见通知消息类型
        String messageCode = pb.getPropName("ldtzMsgTypeCode");
        MessageType messageType = MessageType.newInstance(Integer.parseInt(messageCode));
        try {
            MessageBean messageBean = Util_Message.createMessage(messageType, sendIdSet, title, context, linkUrl, linkMobileUrl);
            messageBean.setCreater(1);// 创建人id
            Util_Message.store(messageBean);
        } catch (IOException e) {
            e.printStackTrace();
            bs.writeLog("send message error:", e);
        }
    }

}
