package com.engine.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.engine.service.TJBKWorkFlowService;
import com.engine.workflow.util.CommonUtil;
import com.icbc.api.internal.apache.http.impl.cookie.S;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.security.util.SecurityMethodUtil;
import weaver.wechat.util.Utils;
import weaver.workflow.request.todo.OfsSettingObject;
import weaver.workflow.request.todo.RequestUtil;
import weaver.workflow.webservices.WorkflowServiceImpl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static weaver.security.util.SecurityMethodUtil.clearKeywordFromConditon;

public class TJBKWorkFlowServiceImpl implements TJBKWorkFlowService {

    private static final String getIdByWorkCodesql = "SELECT id FROM HRMRESOURCE WHERE workcode = ? ";
    private static final String getToReadwfidsql = "SELECT distinct b.CONTENT content from hpsetting_wfcenter a , workflowcentersettingdetail b where  a.eid = b.eid and a.tabid = b.tabid and a.tabtitle = '我的待阅' and b.TYPE ='flowid'";
    private static final String getToDowfidsql = "SELECT distinct b.CONTENT content from hpsetting_wfcenter a , workflowcentersettingdetail b where  a.eid = b.eid and a.tabid = b.tabid and a.tabtitle = '我的待办' and b.TYPE ='flowid'";
//    private static final String getToReadwfidsql = "SELECT b.* from hpsetting_wfcenter a , workflowcentersettingdetail b where  a.eid = b.eid and a.tabid = b.tabid";
//     private WorkflowServiceImpl workflowService = new WorkflowServiceImpl();
    private RecordSet rs = new RecordSet();


    @Override
    public Integer getToDoCount(Map<String,String>  paramMap) {
        String value = paramMap.get("value");
        String key = paramMap.get("key");
        //User currentUser = null;
        String userId = "";
        try{
        //验证工号是否为空
        if (!StringUtils.isEmpty(value) && !StringUtils.isEmpty(key)){
        //    获取用户
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(getIdByWorkCodesql,value);

            if (recordSet.next()){
                userId = Utils.null2String(recordSet.getString("id"));
                //currentUser = new User(Integer.parseInt(userId));
            }
        }

//        String[] strings = {};
//        new RecordSet()
        String conditionsql = getToDoWfidCondition();
        // new BaseBean().writeLog("getToDoWfidCondition"+conditionsql);
        String[] strings = {conditionsql};

        int toDoWorkflowRequestCount = getToDoWorkflowRequestCount4OS(Integer.parseInt(userId), strings,true);
        paramMap.put("status","COMPLETE");
        paramMap.put("code","S000A000");
        paramMap.put("desc","success");
        //int toDoWorkflowRequestCount = workflowService.getToDoWorkflowRequestCount(Integer.parseInt("1"), strings);
        return toDoWorkflowRequestCount;}catch (Exception E){
            paramMap.put("status","FAIL");
            paramMap.put("code","ESB-E-000002");
            paramMap.put("desc","人员不存在");
            return null;
        }
    }



    @Override
    public Integer getToReadCount(Map<String,String>  paramMap) {
        String value = paramMap.get("value");
        String key = paramMap.get("key");
        User currentUser = null;
        String userId = "";
        try {
            //验证工号是否为空
            if (!StringUtils.isEmpty(value) && !StringUtils.isEmpty(key)) {
                //    获取用户
                RecordSet recordSet = new RecordSet();
                recordSet.executeQuery(getIdByWorkCodesql, value);

                if (recordSet.next()) {
                    userId = Utils.null2String(recordSet.getString("id"));
                    currentUser = new User(Integer.parseInt(userId));
                }
            }
            String conditionsql = getToReadWfidCondition();
            new BaseBean().writeLog("getToReadWfidCondition"+conditionsql);
            String[] strings = {conditionsql};
            int toBeReadWorkflowRequestCount = getToDoWorkflowRequestCount4OS(Integer.parseInt(userId), strings, true);
            paramMap.put("status","COMPLETE");
            paramMap.put("code","S000A000");
            paramMap.put("desc","success");
            //int toBeReadWorkflowRequestCount = workflowService.getToBeReadWorkflowRequestCount(Integer.parseInt("1"), strings, false);
            return toBeReadWorkflowRequestCount;
        }catch (Exception E){
            paramMap.put("status","FAIL");
            paramMap.put("code","ESB-E-000002");
            paramMap.put("desc","人员不存在");
            return null;
        }
    }

    private String getToReadWfidCondition() {
        RecordSet rs = new RecordSet();
        boolean b = rs.executeQuery(getToReadwfidsql);
        String[] arr = new String[rs.getCounts()];
        StringBuilder sqlwhere = new StringBuilder();
        int i = 0;
        while (rs.next()){
            String content = Util.null2String( rs.getString("content"));
            if (!StringUtils.isEmpty(content)){
            arr[i] = "t1.workflowid = "+content;
            i++;
            }
        }
        // 过滤掉空元素
        List<String> nonNullElements = Arrays.stream(arr)
                .filter(element -> element != null && !element.isEmpty())
                .collect(Collectors.toList());
        String result = String.join(" OR ", nonNullElements);
        if (StringUtils.isEmpty(result)){return "";}
        return   "(" + result +")";
    }


    private String getToDoWfidCondition() {
        RecordSet rs = new RecordSet();
        boolean b = rs.executeQuery(getToDowfidsql);
        String[] arr = new String[rs.getCounts()];
        StringBuilder sqlwhere = new StringBuilder();
        int i = 0;
        while (rs.next()){
            String content = Util.null2String( rs.getString("content"));
            if (!StringUtils.isEmpty(content)){
                arr[i] = "t1.workflowid != " + content;
                i++;
            }
        }
        // 过滤掉空元素
        List<String> nonNullElements = Arrays.stream(arr)
                .filter(element -> element != null && !element.isEmpty())
                .collect(Collectors.toList());
        String result = String.join(" AND ", nonNullElements);
        if (StringUtils.isEmpty(result)){return "";}
        return   "(" + result +")";
    }
    public int getToDoWorkflowRequestCount4OS(int var1, String[] var2, boolean var3) {
        String var4 = " select distinct ";
        String var5 = " t1.createdate,t1.createtime,t1.creater,t1.currentnodeid,t1.currentnodetype,t1.lastoperator,t1.creatertype,t1.lastoperatortype,t1.lastoperatedate,t1.lastoperatetime,t1.requestid,t1.requestname,t1.requestlevel,t1.workflowid,t2.receivedate,t2.receivetime ";
        String var6 = " from workflow_requestbase t1,workflow_currentoperator t2 ";
        String var7 = " where t1.requestid=t2.requestid ";
        var7 = var7 + " and ((t2.isremark='0' and (t2.takisremark is null or t2.takisremark=0 )) or t2.isremark in('1','5','8','9','7','11')) and t2.islasttimes=1";
        var7 = var7 + " and (isprocessing = '' or isprocessing is null) ";
        var7 = var7 + " and t1.workflowid in(select id from workflow_base where (isvalid='1' or isvalid='3') and (activeversionid is null or activeversionid=0 or activeversionid in(select id from workflow_base where isvalid='1')) )";
        var7 = var7 + this.sqldelete();
        String var8 = var7;
        var7 = " and t2.usertype = 0 and t2.userid = " + var1;
        String var9 = CommonUtil.getDBJudgeNullFun((new RecordSet()).getDBType());
        var7 = var7 + " and (" + var9 + "(t1.currentstatus,-1) = -1 or (" + var9 + "(t1.currentstatus,-1)=0 and t1.creater in (" + var1 + "))) ";
        String var10 = "";
        if (var2 != null) {
            for(int var11 = 0; var11 < var2.length; ++var11) {
                String var12 = var2[var11];
                var12 = SecurityMethodUtil.clearKeywordFromConditon(var12);
                var10 = var10 + (var12 != null && !"".equals(var12) ? " and " + var12 : "");
            }
        }

        var7 = var7 + var10;
        RequestUtil var16 = new RequestUtil();
        OfsSettingObject var17 = var16.getOfsSetting();
        boolean var13 = var17.getIsuse() == 1;
        String var14 = "";
        if (var3 && var13) {
            String var15 = " select createdate,createtime,creatorid as creater,-1 as currentnodeid,'' as currentnodetype,-1 as lastoperator,0 as creatertype,0 as lastoperatortype,'' as lastoperatedate,'' as lastoperatetime,requestid,requestname,0 as requestlevel,workflowid,receivedate,receivetime from ofs_todo_data where islasttimes=1 and isremark in(0,8,9) and workflowid in (select workflowid from ofs_workflow where (cancel=0 or cancel is null)) and userid=" + var1 + var10.replaceAll("t2.", "").replaceAll("t1.", "");
            var14 = this.getPaginationCountSql(var4, var5, var6, var7, var8, var15);
        } else {
            var14 = this.getPaginationCountSql(var4, var5, var6, var7, var8);
        }

        var14 = var14.replace("t1.deleted", "SpecialHandling");
        return this.getWorkflowRequestCount(var14);
    }

    private String sqldelete() {
        String deletesql = " and (t1.deleted<>1 or t1.deleted is null or t1.deleted='') ";
        if (this.rs.getDBType().equalsIgnoreCase("postgresql")) {
            deletesql = " and (t1.deleted<>1 or t1.deleted is null) ";
        }

        return deletesql;
    }

    private String getPaginationCountSql(String var1, String var2, String var3, String var4, String var5, String var6) {
        return this.getPaginationCountSql(var1, var2, var3, var4, var5, var6, "");
    }

    private String getPaginationCountSql(String var1, String var2, String var3, String var4, String var5, String var6, String var7) {
        var1 = Util.null2String(var1).replaceAll("(?i)(drop|insert|alter|truncate|delete|union|wait|xp_cmdshel|DBMS_PIPE|IIF|UTL_HTTP|SLEEP|net user|--|/\\*.*?\\*/)", "__SQLINJECTION__");
        var2 = SecurityMethodUtil.clearKeywordFromConditon(var2);
        var3 = SecurityMethodUtil.clearKeywordFromConditon(var3);
        var4 = SecurityMethodUtil.clearKeywordFromConditon(var4);
        var4 = var5 + var4;
        String var8 = " select count(*) my_count from ( " + var1 + " " + var2 + " " + var3 + " " + var4 + " SpecialHandUN " + var6 + ("".equals(var7) ? "" : " SpecialHandUN " + var7) + " ) tableA ";
        return var8;
    }
    private String getPaginationCountSql(String var1, String var2, String var3, String var4, String var5) {
        var1 = Util.null2String(var1).replaceAll("(?i)(drop|insert|alter|truncate|delete|union|wait|xp_cmdshel|DBMS_PIPE|IIF|UTL_HTTP|SLEEP|net user|--|/\\*.*?\\*/)", "__SQLINJECTION__");
        var2 = SecurityMethodUtil.clearKeywordFromConditon(var2);
        var3 = SecurityMethodUtil.clearKeywordFromConditon(var3);
        var4 = SecurityMethodUtil.clearKeywordFromConditon(var4);
        var4 = var5 + var4;
        String var6 = " select count(*) my_count from ( " + var1 + " " + var2 + " " + var3 + " " + var4 + " ) tableA ";
        return var6;
    }

    private int getWorkflowRequestCount(String var1) {
        RecordSet var2 = new RecordSet();
        var1 = Util.null2String(var1).replaceAll("(?i)(drop|insert|alter|truncate|delete|union|wait|xp_cmdshel|DBMS_PIPE|IIF|UTL_HTTP|SLEEP|net user|--|/\\*.*?\\*/)", "__SQLINJECTION__");
        var1 = var1.replace("SpecialHandling", "t1.deleted").replaceAll("SpecialHandUN", "union");
        int var3 = 0;

        try {
            var2.executeSql(var1);
            if (var2.next()) {
                var3 = var2.getInt("my_count");
            }
        } catch (Exception var5) {
            var5.printStackTrace();
            new BaseBean().writeLog(var5);
        }

        return var3;
    }
}
