package com.engine.htsc.jgxt.service.imp;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.htsc.jgxt.dao.JgxtVDao;
import com.engine.htsc.jgxt.dao.Jgxtbase;
import com.engine.htsc.jgxt.service.JgxtVfServer;
import com.engine.htsc.system.entity.Workflow_attention;
import com.engine.htsc.system.service.WfAttentionTypeSetService;
import com.engine.htsc.system.service.impl.WfAttentionTypeSetServiceImpl;
import org.apache.commons.lang.StringUtils;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.DBTools;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.wechat.util.Utils;

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


public class JgxtVfServerImp extends Service implements JgxtVfServer {

    private WfAttentionTypeSetService getWfattentionTypeSetService(){
        return ServiceUtil.getService(WfAttentionTypeSetServiceImpl.class);
    }


    /**
     * @title deptvf
     * @remark 判断营业部和总部逻辑
     * @author xf
     * @Params：
     * @param: map
     * @updateTime 2021/9/14
     * @return: com.alibaba.fastjson.JSONObject
     */
    @Override
    public JSONObject deptvf(Map<String, Object> map) {
        PropBean propbean=new PropBean();
        JSONObject jsonObject=new JSONObject();
        String deptids= Util.null2String(map.get("deptids"));
        if("".equals(deptids)){
            jsonObject.put("code","-1");
            return jsonObject;
        }
        List<Map<String,Object>> list = JgxtVDao.getdeptvalue(map);
        if(list==null || list.size()<=0){
            jsonObject.put("code","-1");
            return jsonObject;
        }
        String flagtype="";
        String depttype="";
        String djrtype="1";
        String departmentname="";
        boolean abutmentflag=false;
        String abutment=Util.null2String(propbean.getPropName("jgxt.dept.abutment"));
        for (Map<String,Object> model:list ) {
            String depttypecode= Util.null2String(model.get("depttypecode"));
            String deptabutmenttype= Util.null2String(model.get("departmentcode"));
            String deptname=Util.null2String(model.get("departmentname"));
            if("".equals(depttype)){
                depttype=depttypecode;
                if(abutment.indexOf(deptabutmenttype)>=0){
                    abutmentflag=true;
                    departmentname+=departmentname==""?deptname:","+deptname;
                }
            }

            if("JGLX01".equals(depttype)){
                //不允许分支机构或者是另外的四种类型
                if(!"JGLX01".equals(depttypecode)){
                    flagtype="1";
                    break;
                }else{
                    if(abutment.indexOf(deptabutmenttype)>=0){
                        departmentname+=departmentname==""?deptname:","+deptname;
                        djrtype="0";
                    }
                    //判断是否有对接人部门
                    if( (!abutmentflag && abutment.indexOf(deptabutmenttype)>=0)
                            || (abutmentflag && abutment.indexOf(deptabutmenttype)<0)){
                        flagtype="2";
                    }
                }
            }else{
                //不允许存在总部
                if("JGLX01".equals(depttypecode)){
                    flagtype="1";
                    break;
                }
            }
        }
        jsonObject.put("code",flagtype);
        if("2".equals(flagtype)){
            jsonObject.put("msg",departmentname);
        }else if("".equals(flagtype)){
            if(depttype!=""  && "JGLX01".equals(depttype)){
                jsonObject.put("type","0");

            }else{
                jsonObject.put("type","1");
            }
            jsonObject.put("djrtype",djrtype);
            jsonObject.put("code","true");
        }

        return jsonObject;

    }

    @Override
    public JSONObject deptvfValue(Map<String, Object> map) {
        PropBean propbean=new PropBean();
        JSONObject jsonObject=new JSONObject();
        JSONArray supdepnamelist=new JSONArray();
        String deptids= Util.null2String(map.get("deptids"));
        if("".equals(deptids)){
            jsonObject.put("code","-1");
            return jsonObject;
        }
        List<Map<String,Object>> list = JgxtVDao.getdeptvalue(map);
        if(list==null || list.size()<=0){
            jsonObject.put("code","-1");
            return jsonObject;
        }
        String flagtype="";
        String depttype="";
        String departmentname="";
        boolean abutmentflag=false;
        String abutment=Util.null2String(propbean.getPropName("jgxt.dept.abutment"));
        for (Map<String,Object> model:list ) {
            String depttypecode= Util.null2String(model.get("depttypecode"));
            String deptabutmenttype= Util.null2String(model.get("departmentcode"));
            String deptname=Util.null2String(model.get("departmentname"));
            String supdepname=Util.null2String(model.get("supdepname"));
            String id=Util.null2String(model.get("id"));
            if("".equals(depttype)){
                depttype=depttypecode;
                if(abutment.indexOf(deptabutmenttype)>=0){
                    abutmentflag=true;
                    departmentname+=departmentname==""?deptname:","+deptname;
                }
            }

            if("JGLX01".equals(depttype)){
                //不允许分支机构或者是另外的四种类型
                if(!"JGLX01".equals(depttypecode)){
                    flagtype="1";
                    break;
                }else{
                    if(abutment.indexOf(deptabutmenttype)>=0){
                        if("".equals(departmentname) || !deptname.equals(departmentname)){
                            departmentname+=departmentname==""?deptname:","+deptname;

                        }
                    }
                    //判断是否有对接人部门
                    if( (!abutmentflag && abutment.indexOf(deptabutmenttype)>=0)
                            || (abutmentflag && abutment.indexOf(deptabutmenttype)<0)){
                        flagtype="2";
                    }
                }
            }else{
                //不允许存在总部
                if("JGLX01".equals(depttypecode)){
                    flagtype="1";
                    break;
                }

                JSONObject objjson=new JSONObject();
                objjson.put("id",id);
                objjson.put("name",deptname+"-"+supdepname);
                supdepnamelist.add(objjson);



            }
        }
        jsonObject.put("code",flagtype);
        if("2".equals(flagtype)){
            jsonObject.put("msg",departmentname);
        }else if("".equals(flagtype)){

            if(depttype!=""  && "JGLX01".equals(depttype)){
                jsonObject.put("type","0");

            }else{
                jsonObject.put("type","1");
                jsonObject.put("data",supdepnamelist.toString());
            }

            jsonObject.put("code","true");
        }

        return jsonObject;

    }

    /*
     * @title getuser
     * @remark 获取营业部和总部id
     * @author xf
     * @Params：
     * @param: map
     * @updateTime 2021/9/14
     * @return: com.alibaba.fastjson.JSONObject
     **/
    @Override
    public JSONObject getuser(Map<String, Object> map) {
        JSONObject jsonObject=new JSONObject();
        String sql="select wm_concat_old(id) as id from hrmdepartment  where id in (select deptid from hrmdepartmentdefined where depttypecode in ('JGLX03'))";
        String sql2="select wm_concat_old(id) as id  from hrmdepartment  where id in (select deptid from hrmdepartmentdefined where depttypecode in ('JGLX02','JGLX04','JGLX05','JGLX06'))";
        Map<String,Object> BranchOffice=JAVATools.GetTableToMap(sql,null);
        Map<String,Object> yybmap=JAVATools.GetTableToMap(sql2,null);
        jsonObject.put("BranchOffice",Util.null2String(BranchOffice.get("id")));
        jsonObject.put("SalesDepartment",Util.null2String(yybmap.get("id")));
        return jsonObject;
    }

    /**
     * @title createtreenode
     * @remark 创建流程节点
     * @author xf
     * @Params：
     * @param: map
     * @updateTime 2021/9/16 10:40
     * @return: java.lang.String
     */
    @Override
    public String createtreenode(Map<String, Object> map) {
        return null;
    }

    @Override
    public String getleaderuserlist(Map<String, Object> map) {
        String value="";
        String reqid=Util.null2String(map.get("reqid"));
        String nodeunnumber=Util.null2String(map.get("nodeunnumber"));
        if("".equals(reqid) || "".equals(nodeunnumber)){
            return value;
        }
        Map<String,Object> returnmap= JgxtVDao.getleaderuserMap(map);
        if(returnmap==null || returnmap.size()<=0){
            return value;
        }
        value=Util.null2String(returnmap.get("counuserid"));
        return value;
    }


    @Override
    public JSONObject getfreenode(Map<String, Object> map) {
        JSONObject jsonObject=new JSONObject();
        String nodeid=Util.null2String(map.get("nodeid"));
        String requestid=Util.null2String(map.get("requestid"));

        if("".equals(nodeid) || "".equals(requestid)){
            jsonObject.put("msg","参数有误");
            return jsonObject;
        }
        Map<String,Object> returnmap=Jgxtbase.getfreecount(requestid,nodeid);
        String sumcount= Util.null2String(returnmap.get("sumcount"));
        if("1".equals(sumcount))   {
            jsonObject.put("data","false");

        } else{
            jsonObject.put("data","true");
        }
        return jsonObject;
    }

    @Override
    public String feedbacktodetail(Map<String, Object> map, User user) {
        String value="";
        String requestid=Util.null2String(map.get("requestid"));
        String nodeid=Util.null2String(map.get("nodeid"));
        String dt9fkxx=Util.null2String(map.get("dt9fkxx"));
        String dt9fkfj=Util.null2String(map.get("dt9fkfj"));
        JAVATools.SetCmdwritelog("参数查看！！"+requestid+"-"+nodeid+"-"+dt9fkxx
                +"-"+dt9fkfj);
        JSONObject jsonObject=new JSONObject();

        if("".equals(nodeid) || "".equals(requestid) || user==null){
            return "-1";
        }
        Map<String,Object> returnmap=Jgxtbase.getfreecount(requestid,nodeid);
        String sumcount= Util.null2String(returnmap.get("sumcount"));
        JAVATools.SetCmdwritelog("监管协同查看"+sumcount);

        if("1".equals(sumcount))   {
            return "-1";

        }
        //插入数据
        if("".equals(dt9fkxx) || "".equals(dt9fkfj)){
            return "-1";
        }
        Map<String,String> insert=new HashMap<>();
        map.put("fkr",Util.null2String(user.getUID()));
        map.put("sdbm",Util.null2String(user.getUserDepartment()));
        JAVATools.SetCmdwritelog("开始插入数据"+map.toString());

        if(Jgxtbase.insertdetail(map)){
            return "0";
        }else{
            return "-1";
        }

    }

    @Override
    public JSONObject getdeptnametoid(Map<String, Object> map) {

        String deptnames=Util.null2String(map.get("deptnames"));
        if("".equals(deptnames)){
            return null;
        }
        String deptnamenew= Arrays.stream(deptnames.split(",")).map(item->
                "\'"+ item.replace("华泰证券股份有限公司","" )+"\'").collect(Collectors.joining(","));
        String sql = " select id,(select wm_concat_old(dep.departmentname) from hrmdepartment  dep where dep.id=t.supdepid) supdepname,departmentname   from hrmdepartment t where t.departmentname  in (" + deptnamenew + ")";
        List<Map<String,Object>> list= DBTools.getsqltolist(sql);
        if(list==null && list.size()<=0){
            return null;
        }


        String ids="";
        JSONArray jsonArray=new JSONArray();
        for (int i=0;i<list.size();i++){
            JSONObject Jsonobject=new JSONObject();
            Map<String,Object> returnmap= list.get(i);
            String id= Util.null2String(returnmap.get("id"));
            String supdepname= Util.null2String(returnmap.get("supdepname"));
            String departmentname= Util.null2String(returnmap.get("departmentname"));
            ids+="".equals(ids)?id:","+id;
            if("".equals(supdepname)){
                Jsonobject.put("id",id);
                Jsonobject.put("name",departmentname);
            }else{
                Jsonobject.put("id",id);
                Jsonobject.put("name",departmentname+"-"+supdepname);
            }
            jsonArray.add(Jsonobject);
        }
        if(jsonArray.size()<=0 ||  "".equals(ids) ){
            return null;
        }

        JSONObject retjson=new JSONObject();
        retjson.put("value",ids);
        retjson.put("specialobj",jsonArray);

        return retjson;

    }

    /**
     * @title getBusinessName
     * @remark 分公司获取营业部的名称
     * @author xf
     * @updateTime 2022/1/18
     * @return: java.lang.String
     */
    @Override
    public String getBusinessName(Map<String, Object> map) {
        String nodeid=Util.null2String(map.get("nodeid"));
        String requestid=Util.null2String(map.get("requestid"));
        List<String> liststr=new ArrayList<>();
        if(StringUtils.isBlank(nodeid) ||StringUtils.isBlank(requestid)  ){
            return null;
        }
        List<Map<String,Object>> userlist=JgxtVDao.getBusinessName(nodeid,requestid);
        if(userlist==null || userlist.size()<=0){
            return null;
        }
        userlist.forEach((Map<String,Object> userMap)->{
            String operatorids= Util.null2String(userMap.get("operatorids"));
            String agentorbyagentid=Util.null2String(userMap.get("agentorbyagentid"));
            if(StringUtils.isBlank(agentorbyagentid) || "-1".equals(agentorbyagentid)){
                //没有代理
                String deptname= JAVATools.getHrmanddeptName(operatorids);
                liststr.add(deptname);
            }else{
                String deptname= JAVATools.getHrmanddeptName(agentorbyagentid);
                String username= JAVATools.getHrmName(operatorids);
                liststr.add(deptname+"["+username+"授权]");
            }

        });
        if(liststr.size()<=0){
            return  null;
        }

        return liststr.stream().collect(Collectors.joining(","));
    }


    @Override
    public String updatelabeltype(Map<String, Object> map) {
        int type=Util.getIntValue(Util.null2String(map.get("type")));
        int userid=Util.getIntValue(Util.null2String(map.get("userid")));
        int requestid=Util.getIntValue(Util.null2String(map.get("requestid")));
        int nodeid=Util.getIntValue(Util.null2String(map.get("nodeid")));
        if(0>type || 0>=userid || 0>=requestid || nodeid==-1){
            return null;
        }
        //如果类型不一致则直接删除
        if(type!=0 &&  type!=1){
            return null;
        }

        try {
            //做add操作
            if(type==0){
                //节点存在代理人 返回代理人ID 不存在的话返回用户ID
                String aguserid=getuser(requestid,userid,nodeid);
                if(!StringUtils.isBlank(aguserid)){
                    userid=Util.getIntValue(aguserid);
                }
                //标签ID
                String usertypestr=getatypeid(Util.null2String(userid));
                //判断类型是否为空
                if(StringUtils.isBlank(usertypestr) || Util.getIntValue(usertypestr)<0){
                    return null;
                }
                Integer usertype=Util.getIntValue(usertypestr);
                //判断勾选的类型是否为空  （为空操作）
                if(!isfvattention(requestid,userid)) {
                    Workflow_attention workflow_attention = new Workflow_attention();
                    workflow_attention.setUserid(userid);
                    workflow_attention.setUsertype(0);
                    workflow_attention.setRequestid(requestid);
                    workflow_attention.setAtypeid(usertype);
                    workflow_attention.setOperatedate(DateUtil.formatDate(new Date()));
                    workflow_attention.setOperatetime(DateUtil.formatTime(new Date()));
                    workflow_attention.create();
                }
            }else if (type==1){

                    String id=getworkflowAttentionid(requestid,userid,nodeid);
                    if(!StringUtils.isBlank(id)){
                        Workflow_attention workflow_attention=new Workflow_attention().select(id);
                        workflow_attention.delete();
                    }

                //删除操作
            }
        }catch (Exception exo){
            return null;
        }
        return "1";
    }
    private  String getatypeid(String userid){
        Map<String,Object> wfAttentionTypeSetMap=new HashMap<>(2);
        //监管协同流转中
        String showname= new PropBean().getPropName("jgxt.label.showname");
        wfAttentionTypeSetMap.put("userid",userid);
        wfAttentionTypeSetMap.put("showname",showname);
        String usertypestr= Utils.null2String(getWfattentionTypeSetService().getAttentionTypeSet(wfAttentionTypeSetMap));
       // workflow_attentionTypeSet 表中的ID
        return usertypestr;
    }

    //判断
    private  String getworkflowAttentionid(int requestid,int userid,int nodeid){

        String sql="select id from workflow_attention where 1=1  ";
        Map<String,String> map=new HashMap<>(2);
        map.put("requestid",Util.null2String(requestid));
       // map.put("atypeid",usertypestr); 删除不需要
        map.put("userid",getlastid(requestid,userid,nodeid));
        Map<String,Object> retmap=JAVATools.GetTableToMap(sql,map);
        if(retmap==null || retmap.size()<=0){
            return "";
        }
        String id=Util.null2String(retmap.get("id"));
        if(StringUtils.isBlank(id)){
            return "";
        }
        return id;
    }

    private  String getlastid(int requestid,int userid,int nodeid){
        String sql=" select t.userid,t.agentorbyagentid from workflow_currentoperator t  where t.id in ( " +
                "  select t.takid from workflow_currentoperator t where t.nodeid=? and t.requestid=? and isremark!=2 and userid=? " +
                ") ";
       Map<String,Object> map= DBTools.getsqltomap(sql,nodeid,requestid,userid);
       if(map==null || map.size()<=0){
           return Utils.null2String(userid);
       }
       String uservalue= Util.null2String(map.get("userid"));
       String agentorbyagentid=Util.null2String(map.get("agentorbyagentid"));
       if(StringUtils.isBlank(uservalue) && StringUtils.isBlank(agentorbyagentid)){
           return Utils.null2String(userid);
       }
        if(!StringUtils.isBlank(agentorbyagentid) && !"-1".equals(agentorbyagentid)){
            return agentorbyagentid;
        }else{
            return uservalue;
        }

    }


    private  String getuser(int requestid,int userid,int nodeid){
        String sql= "  select t.agentorbyagentid from workflow_currentoperator t where t.nodeid=? and t.requestid=? and isremark!=2 and userid=? " ;

        Map<String,Object> map= DBTools.getsqltomap(sql,nodeid,requestid,userid);
        if(map==null || map.size()<=0){
            return Util.null2String(userid);
        }
        String uservalue= Util.null2String(map.get("agentorbyagentid"));
        if(StringUtils.isBlank(uservalue) || "-1".equals(uservalue)){
            return Util.null2String(userid);
        }
        return uservalue;
    }

    //判断
    private  boolean isfvattention(int requestid,int userid){
        String usertypestr=getatypeid(Util.null2String(userid));
        if(StringUtils.isBlank(usertypestr) || Util.getIntValue(usertypestr)<0){
            return true;
        }
        String sql="select count(*) as sumcount from workflow_attention where 1=1  ";
        Map<String,String> map=new HashMap<>(2);
        map.put("requestid",Util.null2String(requestid));
        map.put("atypeid",usertypestr);
        map.put("userid",Util.null2String(userid));
        Map<String,Object> retmap=JAVATools.GetTableToMap(sql,map);
        if(retmap==null || retmap.size()<=0){
            return false;
        }
        if(Util.getIntValue(Util.null2String(retmap.get("sumcount")))<=0){
            return false;
        }
        return true;
    }


}
