package com.engine.htsc.lhhtsq.Serivce.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.lhhtsq.Serivce.LhhtsqBaseService;
import com.weaver.general.TimeUtil;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import com.engine.htsc.lhhtsq.Dao.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xf
 * @version 1.0.0
 * @ClassName LhhtsqService.java
 * @createTime 2021年12月10日 20:12:00
 */
public class LhhtsqBaseServiceImpl extends Service implements LhhtsqBaseService {

    @Override
    public Map<String, Object> workflowdone(Map<String, Object> map) {
        PropBean pb = new PropBean();
        String requestid=Util.null2String(map.get("requestid"));
        Map<String,Object> resultMap = new HashMap<>();

        String lhhtsq_xgrysh_unnumber = pb.getPropName("lhht.nodeunnumber.lhht_xgrysh");
        String lhhtsq_hq_unnumber = pb.getPropName("lhht.nodeunnumber.lhht_hq");
        String lhhtsq_kgshq_unnumber = pb.getPropName("lhht.nodeunnumber.lhht_kgshq");
        String lhhtsq_gsld_unnumber = pb.getPropName("lhht.nodeunnumber.lhht_gsld");

        List<Map<String,String>> xgryshMap = getPassUserByNodeid(requestid,lhhtsq_xgrysh_unnumber);
        resultMap.put("xgrysh",xgryshMap);
        List<Map<String,String>> hqMap = getPassUserByNodeid(requestid,lhhtsq_hq_unnumber);
        resultMap.put("hq",hqMap);
        List<Map<String,String>> kgshqMap = getPassUserByNodeid(requestid,lhhtsq_kgshq_unnumber);
        resultMap.put("kgshq",kgshqMap);
        List<Map<String,String>> gsldMap = getPassUserByNodeid(requestid,lhhtsq_gsld_unnumber);
        resultMap.put("gsld",gsldMap);


        return resultMap;

    }


    @Override
    public JSONObject gettypetoReaduserids(Map<String, Object> map) {
        PropBean pb = new PropBean();
        JSONObject returnObj = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        try {
         String htlx = Util.null2String(map.get("htlx"));
         if ("".equals(htlx)) {
             return returnObj;
         }
         Map<String, Object> mapobj = LhhtsqbaseDao.getmodelvalue(htlx);
         if (mapobj == null && mapobj.size() <= 0) {
             return returnObj;
         }
         String tzyddx = Util.null2String(mapobj.get("tzyddx"));
         if ("".equals(tzyddx)) {
             return returnObj;
         }
         List<String> list = new ArrayList<>();
         Arrays.stream(tzyddx.split(",")).forEach(item-> {
             if (!"".equals(item)) {
               try {
                   list.add(item);
                   JSONObject jsonObject = new JSONObject();
                   jsonObject.put("id", item);
                   jsonObject.put("name", JAVATools.getHrmName(item));
                   jsonArray.add(jsonObject);
               }catch (Exception exo){

               }
             }
         });
         returnObj.put("value", list.stream().collect(Collectors.joining(",")));
         returnObj.put("specialobj", jsonArray);
         return returnObj;
     }catch (Exception exo){
            return returnObj;
     }


    }


    private List<Map<String,String>>  getPassUserByNodeid(String requestid, String nodenumbber){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();
        List<Map<String,String>> userMapList = new ArrayList<>();

        Set<String> useridSet = new HashSet<>();
        String sql = "select operator,agentorbyagentid from workflow_requestlog where requestid = '"+requestid+"'  " +
                "  and nodeid in ( select id from workflow_nodebase where unnumber='"+nodenumbber+"')   order by  to_date((operatedate || ' ' || OPERATETIME),'yyyy-MM-dd hh24:mi:ss')  desc";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            String agentorbyagentid = Util.null2String(rs.getString("agentorbyagentid"));
            if("-1".equals(agentorbyagentid)){//授权，获取原处理人
                String operator = Util.null2String(rs.getString("operator"));
                useridSet.add(operator);
            }else{
                useridSet.add(agentorbyagentid);
            }
        }

        for(String userid:useridSet){
            if(StringUtils.isNotEmpty(userid)){
                Map<String,String> userMap = new HashMap<>();
                sql = "select t1.id as userid,t1.lastname,t2.id as deptid,t2.departmentname from hrmresource t1,hrmdepartment t2 where t1.departmentid = t2.id and t1.id = '"+userid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    userMap.put("id",Util.null2String(rs.getString("userid")));
                    userMap.put("name",Util.null2String(rs.getString("lastname")));
                    userMap.put("deptid",Util.null2String(rs.getString("deptid")));
                    userMap.put("deptname",Util.null2String(rs.getString("departmentname")));
                }
                userMapList.add(userMap);
            }
        }

        return userMapList;
    }



    @Override
    public Map<String, Object> getsealadmin(Map<String, Object> map) {
        return null;
    }


    /**
     * 校验联席负责人是否阅签
     * @param requestid
     * @param nodename
     * @return
     */
    @Override
    public Map<String,Object> checkCoDirectorNotice(String requestid, String nodename){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        Map<String,Object> resultMap = new HashMap<>();

        try{
            ResourceComInfo resourceComInfo = new ResourceComInfo();

            String nodeid = "";
            if("bmfzr".equals(nodename)){

                nodeid = pb.getNodeIdsByUnNumber(pb.getPropName("lhht.nodeunnumber.lhht_bmfzr"));

            }else if("hq".equals(nodename)){
                nodeid = pb.getNodeIdsByUnNumber(pb.getPropName("lhht.nodeunnumber.lhht_hq"));

          //      nodeid = pb.getNodeIdsByUnNumber("lhht.nodeunnumber.lhht_hq");
            }

            List<Map<String,String>> userMapList = new ArrayList<>();
            String sql = "select userid from workflow_currentoperator where requestid = '"+requestid+"' and nodeid = '"+nodeid+"' and isremark = '9'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                Map<String,String> userMap = new HashMap<>();
                String userid = Util.null2String(rs.getString("userid"));
                userMap.put("id",userid);
                userMap.put("name",resourceComInfo.getLastname(userid));
                userMapList.add(userMap);
            }

            resultMap.put("result",userMapList);
        }catch (Exception e){
            e.printStackTrace();
        }

        return resultMap;
    }

    /**
     * 会签部门联席负责人抄送
     * @param requestid
     * @param nodeid
     * @param deptid
     */
    @Override
    public Map<String,Object> noticeSignDeptCoDirector(String requestid, String nodeid, String deptid){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();
        Map<String,Object> resultMap = new HashMap<>();

        //联席负责人
        String cohead = "";
        String sql = "select cohead from hrmdepartmentdefined where deptid = '"+deptid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            cohead = Util.null2String(rs.getString("cohead"));
        }

        if(StringUtils.isNotEmpty(cohead)){
            for(String id:cohead.split(",")){
                String workflowid = "";
                String workflowtype = "";
                sql = "select t1.id,t1.workflowtype from workflow_base t1,workflow_requestbase t2 where t2.workflowid = t1.id and t2.requestid = '"+requestid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    workflowid = Util.null2String(rs.getString("id"));
                    workflowtype = Util.null2String(rs.getString("workflowtype"));
                }

                char flag = com.weaver.general.Util.getSeparator();
                String operatorgroup = "0";
                String creatertype = "0";
                String currentdate = TimeUtil.getCurrentDateString();
                String currenttime =  TimeUtil.getCurrentTimeString().substring(11,19);
                String isremarktemp = "9";
                String lastnodeid = ""+nodeid;
                String groupdetailid = "-1";
                String useridtemp = id;//抄送人
                String Procparatemp = "" + requestid + flag + useridtemp + flag + operatorgroup + flag + workflowid + flag
                        + workflowtype + flag + creatertype + flag + isremarktemp + flag + lastnodeid + flag + -1
                        + flag + "0" + flag + -1 + flag + groupdetailid+flag+currentdate+flag+currenttime;
                bs.writeLog("chaosong Procparatemp====="+Procparatemp);
                boolean executesuccess = rs.executeProc("workflow_CurrentOperator_I2", Procparatemp);
                resultMap.put("result",executesuccess);

                if(executesuccess){
                    bs.writeLog("CC SUCCESS:"+executesuccess);
                }else{
                    bs.writeLog("CC FAIL:"+executesuccess);
                }
            }
        }
        return resultMap;
    }

    @Override
    public boolean worklfowisend(Map<String, Object> map) {
        String requestid =Util.null2String(map.get("requestid"));
        if("".equals(requestid)){
            return false;
        }
        String sql="select currentnodetype from workflow_requestbase t where 1=1 ";
        Map<String,String> params=new HashMap<>();
        params.put("requestid",requestid);
        Map<String,Object> returnobj=JAVATools.GetTableToMap(sql,params);
       if(returnobj==null && returnobj.size()<=0){
           return false;
       }
       if("3".equals(Util.null2String(returnobj.get("currentnodetype")))){
           return true;
        }else{
           return false;
       }
    }
    @Override
    public JSONObject firstseal(Map<String, Object> map) {
        PropBean pb=new PropBean();
        JSONObject jsonObject=new JSONObject();
        String requestid=Util.null2String(map.get("requestid"));
        if("".equals(requestid)){
            jsonObject.put("message","参数有误");
            return jsonObject;
        }

        Map<String,Object> tablevalue=JAVATools.gettablevalue(requestid);
        if(tablevalue==null || tablevalue.size()<=0){
            jsonObject.put("message","参数有误");
            return jsonObject;
        }
        String lhhtsq_xgrysh_unnumber =pb.getNodeIdsByUnNumber(pb.getPropName("lhht.nodeunnumber.lhht_xgrysh"));
        String lhhtsq_hq_unnumber = pb.getNodeIdsByUnNumber(pb.getPropName("lhht.nodeunnumber.lhht_hq"));
        String lhhtsq_gsld_unnumber = pb.getNodeIdsByUnNumber(pb.getPropName("lhht.nodeunnumber.lhht_gsld"));

        if(!iscwglb(tablevalue,lhhtsq_hq_unnumber)){
            jsonObject.put("message","请选择财务管理部进行审批");
            return jsonObject;
        }


        //财务管理部门
        if(!ishgandfx(tablevalue,lhhtsq_hq_unnumber)){
            jsonObject.put("message","请选择合规与风险管理部审批");
            return jsonObject;
        }

        if(!isldsh(tablevalue,lhhtsq_gsld_unnumber)){
            jsonObject.put("message","请选择合规总监审批");
            return jsonObject;
        }
        if(!isxgryzww(tablevalue,lhhtsq_xgrysh_unnumber)){
            jsonObject.put("message","请选择合同审核员审批");
            return jsonObject;
        }

        /**/
        jsonObject.put("status",true);

        return jsonObject;
    }


    /*
     * @title iscwglb
     * @remar 经过合规与风险管理部审核
     * @author xf
     * @Params：
     * @param: map
     * @param: nodeid
     * @updateTime 2022/1/6 14:48
     * @return: boolean
     **/
    private  boolean isxgryzww(Map<String,Object> map,String nodeid){
        boolean flag=false;
        String htlx=Util.null2String(map.get("htlx"));
        String requestid=Util.null2String(map.get("requestid"));
        String lhtuserid=new PropBean().getPropName("lhht.user.zww");



            Map<String,Set<String>> valueMap= firstsealworkflow(requestid,nodeid);
            if(valueMap==null || valueMap.size()<=0){
                return flag;
            }
            Set<String> userset= valueMap.get("userid");
            if(userset==null || userset.size()<=0){
                return flag;
            }
            flag= userset.contains(lhtuserid);

        return flag;
    }


    /*
     * @title iscwglb
     * @remar 经过合规与风险管理部审核
     * @author xf
     * @Params：
     * @param: map
     * @param: nodeid
     * @updateTime 2022/1/6 14:48
     * @return: boolean
     **/
    private  boolean isldsh(Map<String,Object> map,String nodeid){
        boolean flag=false;
        String htlx=Util.null2String(map.get("htlx"));
        String requestid=Util.null2String(map.get("requestid"));
        String lhtuserid=new PropBean().getPropName("lhht.user.lht");



            Map<String,Set<String>> valueMap= firstsealworkflow(requestid,nodeid);
            if(valueMap==null || valueMap.size()<=0){
                return flag;
            }
            Set<String> userset= valueMap.get("userid");
            if(userset==null || userset.size()<=0){
                return flag;
            }
            flag= userset.contains(lhtuserid);

        return flag;
    }

    /*
     * @title ishgandfx
     * @remar 经过合规与风险管理部审核
     * @author xf
     * @Params：
       * @param: map
     * @param: nodeid
     * @updateTime 2022/1/6 14:48
     * @return: boolean
     **/
    private  boolean ishgandfx(Map<String,Object> map,String nodeid){
        boolean flag=false;
        String htlx=Util.null2String(map.get("htlx"));
        String requestid=Util.null2String(map.get("requestid"));
        String hgfxglb=Util.null2String(new PropBean().getPropName("lhht.dept.hgfxglb"));
          String hgfxglbdeptid=JAVATools.getdepartmentcodetoid(hgfxglb);

            //获取财务管理部
            Map<String,Set<String>> valueMap= firstsealworkflow(requestid,nodeid);
            if(valueMap==null || valueMap.size()<=0){
                return flag;
            }
            Set<String> deptset= valueMap.get("deptid");
            if(deptset==null || deptset.size()<=0){
                return flag;
            }
            flag= deptset.contains(hgfxglbdeptid);

        return flag;

    }

    /*
     * @title iscwglb
     * @remark 判断是否经过财务管理部审核
     * @author xf
     * @Params：
       * @param: map
     * @param: nodeid
     * @updateTime 2022/1/6 14:47
     * @return: boolean
     **/
    private  boolean iscwglb(Map<String,Object> map,String nodeid){
        boolean flag=false;
        String htlx=Util.null2String(map.get("htlx"));
        String requestid=Util.null2String(map.get("requestid"));
        String cwglb=Util.null2String(new PropBean().getPropName("lhht.dept.cwglbcode"));
        String deptid=JAVATools.getdepartmentcodetoid(cwglb);
        if(!"3".equals(htlx)){
            //获取财务管理部
           Map<String,Set<String>> valueMap= firstsealworkflow(requestid,nodeid);
            if(valueMap==null || valueMap.size()<=0){
                return flag;
            }
           Set<String> deptset= valueMap.get("deptid");
            if(deptset==null || deptset.size()<=0){
                return flag;
            }
           flag= deptset.contains(deptid);
        }else{
            flag=true;
        }
        return flag;

    }

    // by gettablevalue
    private  Map<String,Set<String>> firstsealworkflow(String requestid,String nodeid){
        String sql = "select operator,agentorbyagentid from workflow_requestlog where 1=1 and nodeid in ("+nodeid+") ";
        Map<String,String> wheremap=new HashMap<>();
        wheremap.put("requestid",requestid);

        Set<String> useridSet=new HashSet<>();
        Set<String> deptidSet=new HashSet<>();
        List<Map<String,Object>> list= JAVATools.GetTableToListMap(sql,wheremap);
        list.forEach((Map<String,Object> map)->{
            String agentorbyagentid=Util.null2String(map.get("agentorbyagentid"));
             String operator=Util.null2String(map.get("operator"));
            if("-1".equals(agentorbyagentid)){//授权，获取原处理人
                 useridSet.add(operator);
                 deptidSet.add(JAVATools.getHrmtodeptid(operator));
            }else{
                useridSet.add(agentorbyagentid);
                deptidSet.add(JAVATools.getHrmtodeptid(agentorbyagentid));
            }
        });
        Map<String,Set<String>> map=new HashMap<>();
        map.put("userid",useridSet);
        map.put("deptid",deptidSet);
        return map;
    }
}
