package com.customization.htsc.cus;

import com.alibaba.fastjson.JSONObject;
import com.api.workflow.service.WorkflowShareService;
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.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.workflow.cmd.requestForm.RequestSubmitCmd;
import com.engine.workflow.entity.requestForm.RequestOperationResultBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.docx4j.wml.R;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

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

/**
 * Author:wanxq
 * Date:2021/1/05 14:53
 * Description: 流程提交根据领导意见发送消息通知
 * Copyright:上海泛微网络科技股份有限公司
 */
@CommandDynamicProxy(target = RequestSubmitCmd.class, desc = "流程提交处理业务")
public class LeaderNoticeRequestSubCmd extends AbstractCommandProxy<Map<String, Object>> {
    @Override
    public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
        RequestSubmitCmd requestSubmitCmd = (RequestSubmitCmd) targetCommand;
        HttpServletRequest request = requestSubmitCmd.getRequest();//从request中可以取到参数，不用以前的方法了
        String requestid = Util.null2String(request.getParameter("requestid"));
        String workflowid = Util.null2String(request.getParameter("workflowid"));
        String nodetype = Util.null2String(request.getParameter("nodetype"));
        String nodeid = Util.null2String(request.getParameter("nodeid"));
        String src = Util.null2String(request.getParameter("src"));
        String remark = Util.HTMLtoTxt(Util.null2String(request.getParameter("remark"))).trim();
        String operator = Util.null2String(request.getParameter("f_weaver_belongto_userid"));
        //执行标准的业务处理
        Map<String, Object> result = nextExecute(targetCommand);
        RequestOperationResultBean resultBean = (RequestOperationResultBean) result.get("data");
        String executeResult = resultBean.getType().name();

        if("SUCCESS".equals(executeResult) && !"save".equals(src)){
            RecordSet rs = new RecordSet();
            //查询当前流程节点对应的提交人提交意见是否需要发送通知
            rs.executeQuery(" select a.* from uf_ldsyyjtz a,workflow_base b,workflow_nodebase c " +
                    " where a.lc=b.unnumber and a.lcjd=c.unnumber and ','||cfld||',' like '%,"+operator+",%' " +
                    " and b.id=? and c.id=? ",new Object[]{workflowid,nodeid});
            if(rs.next()){
                if(!"同意".equals(remark) && !"同意.".equals(remark) && !"同意。".equals(remark)
                        && !"已阅".equals(remark)  && !"已阅.".equals(remark)  && !"已阅。".equals(remark)){
                    Set<String> userIdSet = new HashSet<String>(); // 消息接收人员集合
                    String tstzry = Util.null2String(rs.getString("tstzry"));
                    //特殊通知人员
                    if(!"".equals(tstzry)){
                        Set<String> set= new HashSet<String>(Arrays.asList(tstzry.split(",")));
                        userIdSet.addAll(set);
                        addWfShare(workflowid,requestid,nodeid,tstzry);
                    }

                    //流程监控人员
                    String sql =  " select * from workflow_monitor_info where id in ( " +
                            "  select distinct infoid from workflow_monitor_detail where workflowid=?  )";
                    rs.executeQuery(sql,workflowid);
                    while(rs.next()){
                        String jktype = Util.null2String(rs.getString("jktype"));
                        String jkvalue = Util.null2String(rs.getString("jkvalue"));
                        if("1".equals(jktype) || "3".equals(jktype) ){//人力资源和系统管理员类型
                            userIdSet.add(jkvalue);
                        }else{//角色类型
                            Set<String> roleMembersSet = getRoleMembers(jkvalue);
                            userIdSet.addAll(roleMembersSet);
                        }
                    }

                    //流程参与人员
                    rs.executeQuery(" select distinct userid from workflow_currentoperator where requestid=? and userid!=? ",new Object[]{requestid,operator});
                    while(rs.next()){
                        String userid = Util.null2String(rs.getString("userid"));
                        userIdSet.add(userid);
                    }

                    //发送消息
                    sendNotice(requestid,operator,remark,userIdSet);


                }

            }

        }

        return result;
    }


    /**
     * 添加流程监控角色中的人员
     * @param roleid
     * @return
     */
    public Set<String> getRoleMembers(String roleid){
        RecordSet rs = new RecordSet();
        Set<String> set = new HashSet<String>();
        rs.executeQuery(" select * from hrmrolemembers where roleid=? ");
        while(rs.next()){
            String resourceid = Util.null2String(rs.getString("resourceid"));
            set.add(resourceid);
        }
        return set;
    }


    /**
     * 发送通知
     * @param requestid
     * @param operator
     * @param remark
     * @param userIdSet
     */
    public void sendNotice(String requestid,String operator,String remark,Set<String> userIdSet){

        try {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select * from workflow_requestbase where requestid=? ",new Object[]{requestid});
            rs.next();
            String requestmark = Util.null2String(rs.getString("requestmark"));
            String requestName = Util.null2String(rs.getString("requestname"));
            if(requestName.length()>20){
                requestName = requestName.substring(0,20);
            }

            if(remark.length()>30){
                remark = remark.substring(0,30);
            }

            DateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH时");
            String operatetime = df.format(new Date());

            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String operatorName = resourceComInfo.getLastname(operator);

            PropBean propBean = new PropBean();
            int typecode = Util.getIntValue(propBean.getPropName("ldtzMsgTypeCode"),1169);
            MessageType messageType = MessageType.newInstance(typecode); // 消息来源
            String title = "领导审批意见通知"; // 标题
            String context = operatorName+"于"+operatetime+"对“"+requestName+"”（"+requestmark+"）" +
                    "签署意见“"+remark+"”，请知悉。"; // 内容
            String linkUrl = "/spa/workflow/static4form/index.html#/main/workflow/req?requestid="+requestid+"&ismonitor=1"; // PC端链接
            String linkMobileUrl = "/spa/workflow/static4mobileform/index.html#/req?requestid="+requestid+"&ismonitor=1"; // 移动端链接

            MessageBean messageBean = Util_Message.createMessage(messageType, userIdSet, title, context, linkUrl, linkMobileUrl);
            messageBean.setCreater(1);// 创建人id
            Util_Message.store(messageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给流程添加共享人员
     * @param workflowid
     * @param requestid
     * @param currentnodeid
     * @param tstzry
     */
    public void addWfShare(String workflowid,String requestid,String currentnodeid,String tstzry){
        String currentSql = " select id from workflow_currentoperator where requestid="+requestid+" AND nodeid="+currentnodeid;
        RecordSet rs = new RecordSet();
        rs.execute(currentSql);
        rs.next();
        int currentid = rs.getInt("id");
        WorkflowShareService wss = new WorkflowShareService();
        String userids[] = Util.TokenizerString2(tstzry,",");
        wss.saveShareInfo("5",null,0,0,0,null,userids,null,null,"",currentnodeid,requestid,workflowid,1,"1",currentid);
    }



    public static void main(String[] args) {

    }
}
