package com.engine.htsc.jgzxzysx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.jgzxzysx.cmd.JgzxzdsywknumberCmd;
import com.engine.htsc.jgzxzysx.service.JgzxzysxService;
import com.engine.htsc.jgzxzysx.util.JgzxzysxUtil;
import com.engine.integration.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;

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

/**
 * @author K1810015
 * @version 1.0.0
 * @ClassName JgzxzysxServiceImp.java
 * @createTime 2022年05月11日 13:48:00
 */
public class JgzxzysxServiceImp extends Service implements JgzxzysxService {


    private PropBean pb=new PropBean();
    @Override
    public boolean donewkconfidential(User user, Map<String, Object> map) {
        if(map==null || map.size()<=0){
            return false;
        }
        String requestid= Util.null2String(map.get("requestid"));

        if(StringUtils.isBlank(requestid) )
        {
            return false;
        }
       return JgzxzysxUtil.getworkflowflag(map);

    }


    @Override
    public Set<String> getwkdonetosuer(User user, Map<String,Object> map){
        Set<String> useridSet = new HashSet<>();
        if(map==null || map.size()<=0){
            return useridSet;
        }
        String requestid=Util.null2String(map.get("requestid"));
        String nodeunnumber=Util.null2String(map.get("nodeunnumber"));
        if(StringUtils.isBlank(requestid) || StringUtils.isBlank(nodeunnumber) ){
            return useridSet;
        }
        String nodeid = pb.getActionNodeIdByUnNumber(nodeunnumber);
        String sql = "select operator,agentorbyagentid from workflow_requestlog where requestid = '"+requestid+"' and nodeid = '"+nodeid+"'";
        List<Map<String,Object>> list= JAVATools.GetTableToListMap(sql,null);
        if(list!=null && list.size()>0){
            list.forEach((Map<String,Object> retmap)->{
                String agentorbyagentid = Util.null2String(retmap.get("agentorbyagentid"));
                if("-1".equals(agentorbyagentid)){//授权，获取原处理人
                    String operator = Util.null2String(retmap.get("operator"));
                    useridSet.addAll(getAllUserid(operator));
                }else{
                    useridSet.addAll(getAllUserid(agentorbyagentid));
                }
            });
        }
        return useridSet;
    }

    @Override
    public JSONObject getDataRange(User user, Map<String,Object> map){
       String sblb= Util.null2String(map.get("sblb"));
        String sblx= Util.null2String(map.get("sblx"));
        JSONObject jsonObject=new JSONObject();
        JSONArray jsonnullArray=new JSONArray();
        jsonObject.put("ywzgbmfzr",jsonnullArray);
        jsonObject.put("ywzgbmns",jsonnullArray);
        jsonObject.put("hqbm",jsonnullArray);
        jsonObject.put("gsld",jsonnullArray);
        if(StringUtils.isBlank(sblb) || StringUtils.isBlank(sblx)){
            return jsonObject;
        }
        String sql="select * from uf_jgzxsyfw where 1=1 ";
        Map<String,String> wheremap=new HashMap<>();
        wheremap.put("sblb",sblb);
        wheremap.put("sblx",sblx);
        Map<String,Object> selectmap= JAVATools.GetTableToMap(sql,wheremap);
        if(selectmap==null || selectmap.size()<=0){
            return jsonObject;
        }
        String gsld=Util.null2String(selectmap.get("gsld"));

        if(!StringUtils.isBlank(gsld)){
          JSONArray jsonArray=  getusermap(gsld);
          if(jsonArray!=null && jsonArray.size()>0){
              jsonObject.put("gsld",jsonArray);
          }
        }


        //业务主管部门负责人(ywzgbmfzr)、
     //   会签部门(hqbm)

        String ywzgbmns=Util.null2String(selectmap.get("ywzgbmns"));
        if(!StringUtils.isBlank(ywzgbmns)){
            JSONArray jsonArray=  getusermap(ywzgbmns);
            if(jsonArray!=null && jsonArray.size()>0){
                jsonObject.put("ywzgbmns",jsonArray);
            }
        }


        String hqbm=Util.null2String(selectmap.get("hqbm"));
        if(!StringUtils.isBlank(hqbm)){
            JSONArray jsonArray=  getdeptmap(hqbm);
            if(jsonArray!=null && jsonArray.size()>0){
                jsonObject.put("hqbm",jsonArray);
            }

        }



        String ywzgbmldbq=Util.null2String(selectmap.get("ywzgbmldbq"));

        if(!StringUtils.isBlank(ywzgbmldbq)){
            if ("0".equals(ywzgbmldbq)){
                String ywzgbm=Util.null2String(selectmap.get("ywzgbm"));
                if (!StringUtils.isBlank(ywzgbm)){
                    ywzgbm = Arrays.stream(ywzgbm.split(",")).distinct().collect(Collectors.joining(","));
                    String sql02="select wm_concat_old( distinct DEPTDIRECTORS) as userid from hrmdepartmentdefined where deptid in （ "+ywzgbm+" )";
                    Map<String,Object> selectmap02= JAVATools.GetTableToMap(sql02,null);
                    if(selectmap02==null || selectmap02.size()<=0){
                        jsonObject.put("ywzgbmfzr",jsonnullArray);
                    }else {
                        String userid=Util.null2String(selectmap02.get("userid"));
                        if(!StringUtils.isBlank(userid)){
                            JSONArray jsonArray02=  getusermap(userid);
                            if(jsonArray02==null || jsonArray02.size()<=0){
                                jsonObject.put("ywzgbmfzr",jsonnullArray);
                            }
                            jsonObject.put("ywzgbmfzr",jsonArray02);
                        }
                    }
                }
            }
        }


       String  qzsyrys = Util.null2String(selectmap.get("qzsyry"));

        if(!StringUtils.isBlank(qzsyrys)){
            jsonObject.put("qztzyd",getDefaultNotice(qzsyrys));
        }

        return jsonObject;
    }

    @Override
    public String getnumber(User user, Map<String, Object> map) {
        Map<String,Object> retmap= commandExecutor.execute(new JgzxzdsywknumberCmd(user,map));
        if(retmap==null || retmap.size()<=0){
            return "";
        }
        return Util.null2String(retmap.get("data"));
    }

    @Override
    public JSONObject getleaderallname(User user, Map<String, Object> map) {
       String type=Util.null2String(map.get("type"));
       JSONObject jsonObject=new JSONObject();
        if(StringUtils.isBlank(type)){
            return jsonObject;
        }
        type= Arrays.stream(type.split(",")).distinct().collect(Collectors.joining(","));
        String sql="select id,hqld,gwry from uf_jgzxhqld  where 1=1 and id in ("+type+")";
        List<Map<String,Object>> mainlistmap=JAVATools.GetTableToListMap(sql,null);
        if(mainlistmap==null || mainlistmap.size()<=0){
            return jsonObject;
        }
        mainlistmap.forEach((item)->{
            Map<String,Object> detaimap=(Map<String,Object>)item;
            String id=Util.null2String(detaimap.get("id"));
            String hqld=Util.null2String(detaimap.get("hqld"));
            String gwry=Util.null2String(detaimap.get("gwry"));
            String name=JAVATools.getHrmName(gwry);
            if(StringUtils.isBlank(name)){
                jsonObject.put(id,hqld);
            }else{
                jsonObject.put(id,name+"("+hqld+")");
            }

        });
        return jsonObject;
    }

    @Override
    public boolean getleadercflag(User user, Map<String, Object> map) {
       String requestid=Util.null2String(map.get("requestid"));
       String hqld=Util.null2String(map.get("hqld"));
       String userdeptid=Util.null2String(user.getUserDepartment());
        if(StringUtils.isBlank(requestid) || StringUtils.isBlank(hqld)){
            return false;
        }
       String jsonpb= new PropBean().getPropName("jgzxzysy.leaderflag");
       JSONObject jsonobject=reloadleaderjson(JSONObject.parseObject(jsonpb));
       if(jsonobject==null || jsonobject.size()<=0){
           return false;
       }
        String sql="select wm_concat_old(distinct operatordept) as operatordepts from workflow_requestlog where  nodeid<0 ";
        Map<String,String> wheremap=new HashMap<>();
        wheremap.put("requestid",requestid);
        Map<String,Object> retmap=JAVATools.GetTableToMap(sql,wheremap);
        String operatordepts=Util.null2String(retmap.get("operatordepts"));
        boolean flag= Arrays.stream(hqld.split(",")).distinct().anyMatch((item)->{
            String value=Util.null2String(jsonobject.get(item));
            if(StringUtils.isBlank(value)){
                return true;
            }
            if((","+value+",").indexOf(","+userdeptid+",")>=0){
                return false;
            }else{
                if(StringUtils.isBlank(operatordepts)){
                    return  true;
                }
                Set<String> set=new HashSet<>();
                set.addAll(Arrays.stream(operatordepts.split(",")).collect(Collectors.toSet()));
                set.retainAll(Arrays.stream(value.split(",")).collect(Collectors.toSet()));
                if(set==null || set.size()<=0){
                    return true;
                }
            }
            return false;
       });
        return !flag;
    }

    public JSONObject reloadleaderjson(JSONObject jsonobject){
        if(jsonobject==null || jsonobject.size()<=0){
            return null;
        }
        JSONObject jsonObject1=new JSONObject();
        jsonobject.forEach((key,value)->{
            jsonObject1.put(Util.null2String(key),getdeptcodetoids(Util.null2String(value)));
        });
        return jsonObject1;
    }
    public String getdeptcodetoids(String deptcode){
        if(StringUtils.isBlank(deptcode)){
            return "";
        }
        try {
            deptcode= Arrays.stream(deptcode.split(",")).distinct().map(item->"'"+item+"'").collect(Collectors.joining(","));
            String sql ="select wm_concat_old(id) as id from hrmdepartment  where 1=1 and departmentcode in ("+deptcode+")";
            Map<String,Object> mapitem = JAVATools.GetTableToMap(sql, null);
            if (mapitem == null || mapitem.size() <= 0) {
                return "";
            }
            return Util.null2String(mapitem.get("id"));
        }catch (Exception e){
            return "";
        }
    }

    public JSONArray getusermap(String userids){
        if(StringUtils.isBlank(userids)){
            return null;
        }
        try {
            userids = Arrays.stream(userids.split(",")).distinct().collect(Collectors.joining(","));
            String sql = "select id,lastname as name from hrmresource where id in (" + userids + ")";
            List list = JAVATools.GetTableToListMap(sql, null);
            if (list == null || list.size() <= 0) {
                return null;
            }
            JSONArray retlist = new JSONArray(list);
            if (retlist == null || retlist.size() <= 0) {
                return null;
            }
            return retlist;
        }catch (Exception e){
            return null;
        }

        }

    public JSONArray getdeptmap(String userids){
        if(StringUtils.isBlank(userids)){
            return null;
        }
        try {
            userids = Arrays.stream(userids.split(",")).distinct().collect(Collectors.joining(","));
            String sql = "select id,departmentname as name from hrmdepartment where id in (" + userids + ")";
            List list = JAVATools.GetTableToListMap(sql, null);
            if (list == null || list.size() <= 0) {
                return null;
            }
            JSONArray retlist = new JSONArray(list);
            if (retlist == null || retlist.size() <= 0) {
                return null;
            }
            return retlist;
        }catch (Exception e){
            return null;
        }

    }

    private List<String> getAllUserid(String id){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        List<String> idList = new ArrayList<>();

        String mainUserid = JAVATools.getmainhrmid(id);
        idList.add(mainUserid);
        String sql="select id from hrmresource where belongto = '"+mainUserid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            idList.add(Util.null2String(rs.getString("id")));
        }
        return idList;
    }

    /**
     * 获得强制通知阅读对象
     * @param qzsyrys
     * @return
     */
    public JSONObject getDefaultNotice(String qzsyrys){
        JSONObject jsonObject=new JSONObject();
        try{
            jsonObject.put( "qzsyryid", getusermap(qzsyrys));
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }

}
