package com.engine.workflow.biz;

import com.api.browser.bean.BrowserValueInfo;
import com.api.browser.service.BrowserValueInfoService;
import com.api.browser.service.impl.WorkflowFieldBrowserService;
import com.engine.workflow.biz.newRule.RuleCompareBiz;
import com.engine.workflow.biz.newRule.RuleSetBiz;
import com.engine.workflow.biz.newRule.RuleValueManager;
import com.engine.workflow.constant.newRule.RuleSource;
import com.engine.workflow.entity.newRule.RuleCompareDetail;
import com.engine.workflow.entity.newRule.RuleCompareResult;
import com.engine.workflow.entity.newRule.RuleValueEntity;
import com.engine.workflow.entity.newRule.WeaFieldTemplateSelectOptions;
import com.engine.workflow.util.RuleCompareUtil;
import weaver.conn.RecordSet;
import weaver.crm.Maint.CustomerInfoComInfo;
import weaver.general.BaseBean;
import weaver.general.LabelUtil;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.workflow.WorkflowAllComInfo;
import weaver.workflow.workflow.WorkflowNodeComInfo;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConformCheckBiz {

    /**
     * 重置合规比对信息
     */
    public void resetCompareInfo(int requestId, RuleSource ruleSource, String srcId, User user) {
        RecordSet rs = new RecordSet();
        //删除规则比对明细
        rs.executeUpdate("delete from newrule_CompareLogDetail where compareLogId in (select compareLogId from newrule_CompareLog where requestid = ? and userid = ? and mapsrc = ? and srcid = ?)", requestId, user.getUID(), ruleSource.getType(), srcId);
        //删除规则比对信息
        rs.executeUpdate("delete from newrule_CompareLog where requestid = ? and userid = ? and mapsrc = ? and srcid = ?", requestId, user.getUID(), ruleSource.getType(), srcId);
    }


    /**
     * 节点字段校验，通用比对方法
     * @param requestId
     * @param workflowId
     * @param nodeId
     * @param user
     * @return
     */
    public RuleCompareResult compareRules4NodeCheck(int requestId, int workflowId, String nodeId, User user) {
        return compareRules4Workflow(requestId, workflowId, RuleSource.NODE_CHECK, nodeId, user);
    }

    /**
     * 合规规则校验，从数据库中取字段信息
     * @param requestId
     * @param workflowId
     * @param ruleSource
     * @param srcId
     * @param user
     * @return
     */
    public RuleCompareResult compareRules4Workflow(int requestId, int workflowId, RuleSource ruleSource, String srcId, User user) {
        Map<String, Object> valueMap = RuleCompareUtil.getValueMapByRequestId(requestId, workflowId);
        return compareRules4Workflow(requestId, workflowId, ruleSource, srcId, valueMap, user);
    }
    /**
     * 后台合规规则校验
     * @param requestId
     * @param workflowId
     * @param ruleSource
     * @param nodeId
     * @param user
     * @return
     */
    public RuleCompareResult compareRules4NodeCheck(int requestId, int workflowId,RuleSource ruleSource, String nodeId, User user, boolean needConformCheck) {
        //如果是前台提交的通过另一个接口已经进校验逻辑的,后台不做第二次校验
        RuleCompareResult resultEntity = new RuleCompareResult();
        if(needConformCheck){
            RecordSet rs = new RecordSet();
            if (ruleSource == RuleSource.NODE_CHECK) {
                rs.executeQuery("select openNodeCheck from workflow_flownode where nodeid = ?", nodeId);
                if (rs.next()) {
                    resultEntity.setOpenNodeCheck(Util.getIntValue(rs.getString("openNodeCheck")) == 1);
                }
                if(!resultEntity.isOpenNodeCheck()) {
                    resultEntity.setResult(true);
                    return resultEntity;
                }
            }
            resetCompareInfo(requestId, ruleSource, nodeId, user);
            return compareRules4NodeCheck(requestId,workflowId, nodeId, user);
        }else{
            resultEntity.setResult(true);
            return resultEntity;
        }
    }

    /**
     * 流程合规规则校验，外部传入字段信息
     * @param requestId
     * @param ruleSource
     * @param srcId
     * @param valueMap
     * @param user
     * @return
     */
    public RuleCompareResult compareRules4Workflow(int requestId, int workflowId, RuleSource ruleSource, String srcId, Map<String, Object> valueMap, User user) {

        RecordSet rs = new RecordSet();

        int relation = getRuleRelation(ruleSource, srcId);//规则间关系 0:or  1:and
        int compareProcessType = 1; // 0 ：禁止提交  1：仅提醒
        boolean compareResult = (relation == 1);

        //规则校验日志Id
        String compareLogId = RuleSetBiz.generateNewId();
        RuleCompareResult resultEntity = new RuleCompareResult();
        resultEntity.setCompareLogId(compareLogId);
        resultEntity.setRequestId(requestId);
        resultEntity.setUserId(user.getUID());
        resultEntity.setMapSrc(ruleSource.getType());
        resultEntity.setSrcId(srcId);
        resultEntity.setProcessDate(TimeUtil.getCurrentDateString());
        resultEntity.setProcessTime(TimeUtil.getCurrentTimeString().substring(11));
        resultEntity.setRelation(relation);
        resultEntity.setEnd(false);

        //节点字段校验，需检查是否开启
        if (ruleSource == RuleSource.NODE_CHECK) {
            rs.executeQuery("select openNodeCheck, openNodeCheckRemark from workflow_flownode where nodeid = ?", srcId);
            if (rs.next()) {
                resultEntity.setOpenNodeCheck(Util.getIntValue(rs.getString("openNodeCheck")) == 1);
                resultEntity.setOpenNodeCheckRemark(resultEntity.isOpenNodeCheck() && Util.getIntValue(rs.getString("openNodeCheckRemark")) == 1);
            }
            if(!resultEntity.isOpenNodeCheck()) {
                resultEntity.setEnd(true);
                resultEntity.setResult(true);
                return resultEntity;
            }
        }

        //添加系统变量信息
        appendSystemParams(requestId, workflowId, user, valueMap);

        //获取字段类型信息
        Map<String, Map<String, String>> fieldTypeInfo = getFieldTypeInfo(workflowId);

        //重置规则比对信息
        resetCompareInfo(requestId, ruleSource, srcId, user);
        //记录规则校验日志信息
        resultEntity.insert2DB();

        boolean allPass = true;
        RecordSet rs1 = new RecordSet();
        List<Integer> processTypes = new ArrayList<>();
        //获取当前配置的所有规则映射
        rs.executeQuery("select a.*, b.rulename from newrule_maplist a, newrule_base b where a.mapsrc = ? and a.srcid = ? and a.ruleid = b.ruleid order by a.mapid", ruleSource.getType(), srcId);
        while (rs.next()) {
            String ruleName = rs.getString("ruleName");
            String ruleId = rs.getString("ruleId");
            String mapId = rs.getString("mapid");
            String rulePassedTip = rs.getString("rulePassedTip");
            String ruleNoPassTip = rs.getString("ruleNoPassTip");
            int orderId = rs.getInt("orderid");
            int ruleProcessType = Util.getIntValue(rs.getString("processType"));

            int hasDetail = 0;
            List<String> detailFields = new ArrayList();
            Map<String,String> detailFieldsMap = new HashMap<>();
            rs1.executeQuery("select a.valueid,a.objvalue from newrule_valueMap a,newrule_valueBase b where a.mapid = ? and a.valueid = b.valueid and b.ruleid = ? and a.objtype = 0", mapId,ruleId);
            while (rs1.next()) {
                String valueid = rs1.getString("valueid");
                String objId = rs1.getString("objvalue");
                if(hasDetail(valueMap,objId)>0){
                    detailFields.add(objId);
                    detailFieldsMap.put(objId,valueid);
                    hasDetail = hasDetail(valueMap,objId);
                }
            }
            List<String> rownums = new ArrayList<>();
            RuleValueManager ruleValueManager = null;
            Map<String, List> detailValueMap = new HashMap<>();
            boolean result = false;
            boolean isDetailNoDatas = false;
            if(hasDetail>0){
                rownums = getEntityMapDetailDatas(valueMap,hasDetail);
                if(hasDetail>0 && rownums.size()==0){//表达式中有明细字段,但是前台没有传明细数据
                    isDetailNoDatas = true;
                }else{
                    for(int index=0;index<rownums.size();index++){
                        Map<String, Object> valueMapNew = new HashMap<>();
                        valueMapNew.putAll(valueMap);
                        for(String detailField : detailFields){
                            valueMapNew.put("field"+detailField,valueMap.get("field"+detailField+"_"+rownums.get(index)));
                        }
                        ruleValueManager = RuleCompareBiz.compareRule(ruleId, mapId, valueMapNew, user);
                        List<String> addedValueList = new ArrayList<>();
                        for(String detailField : detailFields){
                            try{
                                String key = detailFieldsMap.get(detailField);
                                Object showValue = Util.null2String(ruleValueManager.getShowValue(key));
                                if(detailValueMap.get(key)!=null){
                                    if(!addedValueList.contains(key)){
                                        detailValueMap.get(key).add(showValue);
                                        addedValueList.add(key);//加进去表示此轮循环已经加过key了,因为函数中多个字段间的valueid相同,此轮循环这个key不再往里面加值
                                    }
                                }else{
                                    List<Object> detailValueList = new ArrayList<>();
                                    detailValueList.add(showValue);
                                    detailValueMap.put(key,detailValueList);
                                    addedValueList.add(key);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                        if(!ruleValueManager.isRulePass()){
                            break;
                        }
                    }
                    ruleValueManager.setDetailValueMap(detailValueMap);
                    result = ruleValueManager.isRulePass();
                }
            }else{
                //进行规则比较
                ruleValueManager = RuleCompareBiz.compareRule(ruleId, mapId, valueMap, user);
                result = ruleValueManager.isRulePass();
            }
            //提示信息
            String ruleTip = "";
            if(result) {
                ruleTip = !"".equals(rulePassedTip) ? rulePassedTip : (ruleName + SystemEnv.getHtmlLabelName(129793, user.getLanguage()));
            } else {
                ruleTip = !"".equals(ruleNoPassTip) ? ruleNoPassTip : (ruleName + SystemEnv.getHtmlLabelName(10003618, user.getLanguage()));
            }

            RuleSetBiz rulesetBiz = new RuleSetBiz();
            Map<String, Object> selectOptionsInfo = rulesetBiz.getSelectOptionsInfo(true, Util.null2String(workflowId), srcId, ruleId, user);

            if(isDetailNoDatas){
                ruleTip = SystemEnv.getHtmlLabelName(19325, user.getLanguage()) + hasDetail + SystemEnv.getHtmlLabelName(533458, user.getLanguage());
                ruleProcessType = 1;
            }else{
                ruleTip = generateRuleTip(ruleTip, ruleValueManager, selectOptionsInfo, user, fieldTypeInfo);
            }

            //记录规则校验明细信息
            RuleCompareDetail compareDetail = new RuleCompareDetail();
            compareDetail.setCompareLogId(compareLogId);
            compareDetail.setMapId(mapId);
            compareDetail.setRuleId(ruleId);
            compareDetail.setRuleName(ruleName);
            compareDetail.setRuleResult(result);
            compareDetail.setProcessType(ruleProcessType);
            compareDetail.setRuleTip(ruleTip);
            compareDetail.setOrderId(orderId);
            compareDetail.insert2DB();

            resultEntity.getDetailList().add(compareDetail);

            //规则比对不通过，存入处理方式
            if (!result && processTypes.indexOf(ruleProcessType) == -1) {
                processTypes.add(ruleProcessType);
            }

            //规则比对AND, 一条规则不通过，则整个不通过
            if(relation == 1 && !result) {
                compareResult = false;
            }

            //规则比对OR，一条通过，则整个通过
            if (relation == 0 && result) {
                compareResult = true;
            }

            if(compareResult){
                allPass = false;
            }
        }

        //规则比对失败，返回处理方式
        if (!compareResult && processTypes.size() > 0) {
            processTypes.sort(Comparator.naturalOrder());
            if (relation == 1) {
                //规则关系AND，优先取禁止提交
                compareProcessType = processTypes.get(0);
            } else {
                //规则关系OR，优先取仅提醒
                compareProcessType = processTypes.get(processTypes.size() - 1);
            }
        }

        //更新规则校验日志，记录比对结果
        resultEntity.setEnd(true);
        resultEntity.setResult(compareResult);
        resultEntity.setProcessType(compareProcessType);
        resultEntity.setIsAllPass(allPass);
        resultEntity.updateResult2DB();

        //生成校验的签字意见
        if (resultEntity.isOpenNodeCheckRemark()) {
            resultEntity.setCompareRemark(getSignRemarkByResult(resultEntity));
        }
        return resultEntity;
    }

    /**
     * 获取规则校验结果对象
     * @param requestId
     * @param ruleSource
     * @param srcId
     * @param user
     * @return
     */
    public RuleCompareResult getRuleCompareResult(int requestId, RuleSource ruleSource, String srcId, User user) {
        RuleCompareResult resultEntity = new RuleCompareResult();

        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from newrule_CompareLog where requestid = ? and userid = ? and mapsrc = ? and srcid = ?", requestId, user.getUID(), ruleSource.getType(), srcId);
        if (rs.next()) {
            resultEntity.setCompareLogId(rs.getString("compareLogId"));
            resultEntity.setRequestId(rs.getInt("requestid"));
            resultEntity.setUserId(rs.getInt("userid"));
            resultEntity.setMapSrc(rs.getInt("mapsrc"));
            resultEntity.setSrcId(rs.getString(srcId));
            resultEntity.setProcessDate(rs.getString("processDate"));
            resultEntity.setProcessTime(rs.getString("processTime"));
            resultEntity.setRelation(rs.getInt("relation"));
            resultEntity.setProcessType(rs.getInt("processType"));
            resultEntity.setResult(rs.getString("result").equals("1"));
            resultEntity.setEnd(rs.getString("isEnd").equals("1"));
        }else{
            rs.executeQuery("select relation from newrule_mapinfo where srcid = ?",srcId);
            if(rs.next()){
                resultEntity.setRelation(rs.getInt("relation"));
            }
        }
        String relation = Util.null2String(resultEntity.getRelation());
        List<List<Object>> ruleResultsList = new ArrayList<>();

        //获取规则比对明细
        rs.executeQuery("select * from newrule_CompareLogDetail where comparelogid = ? order by mapid", resultEntity.getCompareLogId());
        while (rs.next()) {
            RuleCompareDetail compareDetail = new RuleCompareDetail();
            compareDetail.setCompareLogId(resultEntity.getCompareLogId());
            compareDetail.setMapId(rs.getString("mapId"));
            compareDetail.setRuleId(rs.getString("ruleId"));
            compareDetail.setRuleName(rs.getString("ruleName"));
            boolean ruleResult = rs.getString("ruleResult").equals("1");
            compareDetail.setRuleResult(ruleResult);
            compareDetail.setRuleTip(rs.getString("ruleTip"));
            int processType = rs.getInt("processType");
            compareDetail.setProcessType(processType);
            compareDetail.setOrderId(rs.getInt("orderid"));
            resultEntity.getDetailList().add(compareDetail);

            List<Object> ruleResultTmp = new ArrayList<>();
            ruleResultTmp.add(ruleResult);
            ruleResultTmp.add(processType);
            ruleResultsList.add(ruleResultTmp);
        }
        String resultType= getResultType(relation,ruleResultsList);
        resultEntity.setTitle(getTitle(resultType,user.getLanguage()));
        resultEntity.setIsAllPass("1".equals(resultType));

        return resultEntity;
    }


    /**
     * 生成规则提示语
     * @return
     */
    private static String generateRuleTip(String ruleTip, RuleValueManager ruleValueManager, Map<String, Object> selectOptionsInfo, User user, Map<String, Map<String, String>> fieldTypeInfos) {

        Map<String, String> labelMap = new HashMap<>();
        for (String key : selectOptionsInfo.keySet()) {
            List<WeaFieldTemplateSelectOptions> options = (List<WeaFieldTemplateSelectOptions>)((Map<String, Object>)selectOptionsInfo.get(key)).get("options");
            for (WeaFieldTemplateSelectOptions option : options) {
                labelMap.put(option.getValueKey(), option.getShowname());
            }
        }

        String regex = "\\$_[\\s\\S]+?_\\$";
        Pattern r = Pattern.compile(regex);
        Matcher m = r.matcher(ruleTip);
        while (m.find()) {
            String value = Util.null2String(m.group());
            if (value.startsWith("$_fieldLabel") || value.startsWith("$_variableName")) {//字段名或变量名
                ruleTip = ruleTip.replace(value, Util.null2String(labelMap.get(value)));
            } else if(value.startsWith("$_field")) {//字段值
                String fieldKey = value.replace("$_", "").replace("_$", "");
                String fieldId = fieldKey.replace("field", "");
                String fieldValue = Util.null2String(ruleValueManager.getValueParams().get(fieldKey));

                if(Util.getIntValue(fieldId,0)<0){
                    ruleTip = ruleTip.replace(value, fieldValue);
                    continue;
                }
                Map<String, String> fieldTypeInfo = fieldTypeInfos.get(fieldId);


                if (fieldTypeInfo != null) {
                    String fieldHtmlType = Util.null2String(fieldTypeInfo.get("httype"));
                    String fieldType = Util.null2String(fieldTypeInfo.get("type"));
                    String dbtype = Util.null2String(fieldTypeInfo.get("dbtype"));


                    try {
                        //浏览按钮，取显示名替换
                        if("5".equals(fieldHtmlType) && !"".equals(Util.null2String(fieldValue))){
                            String browserShowName = "";
                            RecordSet rs = new RecordSet();
                            rs.executeQuery("select selectname from workflow_selectitem  where fieldid = ? and selectvalue in("+fieldValue+") order by listorder,selectvalue",fieldId);
                            while(rs.next()){
                                browserShowName += rs.getString(1) + ",";
                            }
                            if(browserShowName.length()>0){
                                browserShowName = browserShowName.substring(0,browserShowName.length()-1);
                            }
                            ruleTip = ruleTip.replace(value, browserShowName);
                            continue;
                        }else if ("3".equals(fieldHtmlType)) {
                            String browserShowName = "";
                            List<BrowserValueInfo> list = new BrowserValueInfoService().getBrowserValueInfo(fieldType, dbtype, Util.getIntValue(fieldId), fieldValue, user.getLanguage(), "", "");
                            for (BrowserValueInfo browserValueInfo : list) {
                                browserShowName += "," + browserValueInfo.getName();
                            }
                            if (browserShowName.length() > 0) {
                                browserShowName = browserShowName.substring(1);
                            }
                            ruleTip = ruleTip.replace(value, browserShowName);
                            continue;
                        }else if("4".equals(fieldHtmlType)){
                            String browserShowName = "";
                            browserShowName = LabelUtil.getMultiLangLabel("1".equals(fieldValue) ? "533863" : "533864");
                            ruleTip = ruleTip.replace(value, browserShowName);
                            continue;
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ruleTip = ruleTip.replace(value, fieldValue);
                }
            } else if (value.startsWith("$_variable")) {//变量值
                try {
                    String variableKey = value.replace("$_variable", "").replace("_$", "");
                    ruleTip = ruleTip.replace(value, Util.null2String(ruleValueManager.getShowValue(variableKey)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ruleTip;
    }

    /**
     * 获取规则间关系
     * @param ruleSource
     * @param srcId
     * @return
     */
    public int getRuleRelation(RuleSource ruleSource, String srcId) {
        RecordSet rs = new RecordSet();
        int relation = 1;//规则间关系 0:or  1:and
        rs.executeQuery("select * from newrule_mapinfo where mapsrc = ? and srcid = ?", ruleSource.getType(), srcId);
        if (rs.next()) {
            relation = Util.getIntValue(rs.getString("relation"), 1);
        }
        return relation;
    }


    /**
     * 节点规则校验，添加系统变量
     * @param requestId
     * @param workflowId
     * @param user
     * @param valueMap
     */
    private static void appendSystemParams(int requestId, int workflowId, User user, Map<String, Object> valueMap) {

        RecordSet rs = new RecordSet();
        ResourceComInfo resourceComInfo = new ResourceComInfo(true);
        CustomerInfoComInfo customerInfoComInfo = new CustomerInfoComInfo();

        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

        String currentNodeId = "";
        String createrId = "";
        String createrDep = "";
        String notOperator = "";
        String createDate = dateFormat.format(date);
        String createTime = timeFormat.format(date);
        if (requestId > 0) {
            rs.executeQuery("select currentnodeid, creater,createdate,createtime from workflow_requestbase where requestid = ?", requestId);
            if (rs.next()) {
                currentNodeId = rs.getString(1);
                createrId = rs.getString(2);
                createDate = rs.getString(3);
                createTime = rs.getString(4);
                createrDep = new User(Util.getIntValue(createrId)).getUserDepartment() + "";
            }
            rs.executeQuery("select userid, usertype from workflow_currentoperator where requestid = ? and isremark = '0'", requestId);
            while (rs.next()) {
                int userType = rs.getInt(2);
                if(userType == 0) {
                    notOperator += "," + resourceComInfo.getResourcename(rs.getString(1));
                } else {
                    notOperator += "," + customerInfoComInfo.getCustomerInfoname(rs.getString(1));
                }
            }
            if (!"".equals(notOperator)) {
                notOperator = notOperator.substring(1);
            }
        } else {
            //requestid不存在，则取创建节点id
            rs.executeQuery("select nodeid from workflow_flownode where workflowid = ? and nodetype = ?", workflowId, "0");
            if (rs.next()) {
                currentNodeId = rs.getString(1);
            }
            createrId = user.getUID() + "";
            createrDep = user.getUserDepartment() + "";
            notOperator = user.getUsername();
        }

        //自定义SQL使用，传id
        valueMap.put("requestid", requestId);
        valueMap.put("workflowid", workflowId);
        valueMap.put("nodeid", currentNodeId);
        valueMap.put("creater", createrId);
        valueMap.put("createrdepartment", createrDep);
        valueMap.put("userid", user.getUID());
        valueMap.put("usersubcompany", user.getUserSubCompany1());
        valueMap.put("userdepartment", user.getUserDepartment());

        //前台提示语使用
        DepartmentComInfo departmentComInfo = new DepartmentComInfo();
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        User createrUser = new User(Util.getIntValue(createrId));
        valueMap.put("field-1", requestId);
        valueMap.put("field-2", workflowId);
        valueMap.put("field-3", new WorkflowNodeComInfo().getNodename(currentNodeId));
        valueMap.put("field-4", user.getUsername());
        valueMap.put("field-5", notOperator);
        valueMap.put("field-6", createrUser.getUsername());
        valueMap.put("field-7", departmentComInfo.getDepartmentname(createrUser.getUserDepartment() + ""));
        valueMap.put("field-8", subCompanyComInfo.getSubCompanyname(createrUser.getUserSubCompany1() + ""));
        valueMap.put("field-9", createDate);
        valueMap.put("field-10", createTime);
    }

    private String getSignRemarkByResult(RuleCompareResult resuleEntity) {
        StringBuilder remarkBuild = new StringBuilder();
        //remarkBuild.append("<div>"+ LabelUtil.getMultiLangLabel("529788") +"<div><br>");
        remarkBuild.append("<table cellpadding=\"1\" cellspacing=\"1\" style=\"width:100%;border-top:1px solid #D1D1D1;border-left:1px solid #D1D1D1;border-spacing:0;word-break:break-word;max-width:910px;\">\n" +
                "<tbody>\n" +
                "<tr style=\"height:40px;\">\n" +
                "   <td colspan=\"2\" style=\"padding-left: 20px;border-bottom:1px solid #D1D1D1 !important;border-right:1px solid #D1D1D1 !important;border-top:0 !important;border-left:0 !important;\">" +
                "       <span class=\"icon-coms02-Full-selection\" style=\"color: #80BCFF;font-size: 16px;\"></span>\n" +
                "       <span style=\"color: #1E88FD;\">"+LabelUtil.getMultiLangLabel(resuleEntity.getRelation() == 0 ? "531935" : "531934")+"</span></td></tr>\n" +
                "<tr style=\"height:40px;background: #F9FCFF;\">\n" +
                "   <td style=\"width:30%;padding-left: 20px;border-bottom:2px solid #E2ECF2 !important;border-right:1px solid #D1D1D1 !important;border-top:0 !important;border-left:0 !important;\">" +
                "       <span>"+LabelUtil.getMultiLangLabel("19829")+"</span></td>\n" +
                "   <td style=\"width:70%;border-bottom:2px solid #E2ECF2 !important;border-right:1px solid #D1D1D1 !important;border-top:0 !important;border-left:0 !important;\">" +
                "       <span style=\"padding-left: 20px;\">"+LabelUtil.getMultiLangLabel("82876")+"</span></td></tr>");
        for (RuleCompareDetail detail : resuleEntity.getDetailList()) {
            String iconClass = "";
            String iconColor = "";
            if(detail.isRuleResult()) {//通过
                iconClass = "conform-rule-icon icon-conform-rule-check";
                iconColor = "#24ce20";
            } else if(detail.getProcessType() == 0){//禁止提交
                iconClass = "conform-rule-icon icon-conform-rule-error";
                iconColor = "red";
            } else if(detail.getProcessType() == 1){//仅提醒
                iconClass = "conform-rule-icon icon-conform-rule-warning";
                iconColor = "#ff9917";
            }
            remarkBuild.append("<tr style=\"height:40px;\"><td style=\"padding-left:20px;position:relative;border-bottom:1px solid #D1D1D1 !important;border-right:1px solid #D1D1D1 !important;border-top:0 !important;border-left:0 !important;\">\n" +
                    "<i class=\""+iconClass+"\" style=\"color: "+iconColor+";font-size: 16px;position:absolute;top:10px;\"></i>\n" +
                    "<span style=\"margin-left: 36px;display: inline-block;\">"+detail.getRuleName()+"</span></td>\n" +
                    "<td style=\"padding-left: 20px;border-bottom:1px solid #D1D1D1 !important;border-right:1px solid #D1D1D1 !important;border-top:0 !important;border-left:0 !important;\"><span>"+detail.getRuleTip()+"</span></td></tr>");
        }
        remarkBuild.append("</tbody>\n" +
                "</table>");
        return remarkBuild.toString();
    }

    /**
     * 获取表单字段类型信息
     * @param workflowId
     * @return
     */
    private Map<String, Map<String, String>> getFieldTypeInfo(int workflowId) {

        Map<String, Map<String, String>> fieldTypeInfos = new HashMap<>();

        WorkflowAllComInfo workflowAllComInfo = new WorkflowAllComInfo();
        int formId = Util.getIntValue(workflowAllComInfo.getFormId(workflowId+""));
        int isBill = Util.getIntValue(workflowAllComInfo.getIsBill(workflowId + ""));

        String fieldSql = WorkflowFieldBrowserService.getQueryFormFieldSQL(formId, isBill);
        RecordSet rs = new RecordSet();
        rs.executeQuery(fieldSql);
        while (rs.next()) {
            Map<String, String> fieldTypeInfo = new HashMap<>();
            String id = rs.getString("id");
            String httype = rs.getString("httype");
            String type = rs.getString("type");
            String dbtype = rs.getString("dbtype");

            fieldTypeInfo.put("httype", httype);
            fieldTypeInfo.put("type", type);
            fieldTypeInfo.put("dbtype", dbtype);
            fieldTypeInfos.put(id, fieldTypeInfo);
        }

        return fieldTypeInfos;
    }

    public int hasDetail(Map<String, Object> valueParams,String fieldid) {
        String isbill = Util.null2String(valueParams.get("isbill"));
        RecordSet rs = new RecordSet();
        if("1".equals(isbill)){
            int index = 0;
            rs.executeQuery("select a.detailtable,b.tablename from workflow_billdetailtable b left join workflow_billfield a on a.billid = b.billid where a.id = ? and a.viewtype = 1 order by b.id", fieldid);
            while (rs.next()){
                index++;
                String detailtable = Util.null2String(rs.getString("detailtable"));
                String tablename = Util.null2String(rs.getString("tablename"));
                if(!"".equals(detailtable) && detailtable.equals(tablename)){
                    return index;
                }
            }
        }else{
            rs.executeQuery("select groupid from workflow_formfield where isdetail = 1 and fieldid = ?",fieldid);
            if(rs.next()){
                return (rs.getInt("groupid")+1);
            }
        }
        return 0;
    }

    //获取明细行index
    public List<String> getEntityMapDetailDatas(Map<String, Object> valueParams,int hasDetail) {
        String rows =Util.null2String(valueParams.get("submitdtlid"+(hasDetail-1)));
        rows = rows.replaceAll("^,*|,*$", "");
        if(!"".equals(rows)){
            return Arrays.asList(rows.split(","));
        }else{
            return new ArrayList<String>();
        }
    }

    /*
    * 1、全部通过，可以提交：节点字段校验结果如下：
    * 2、不能提交AND：以下规则需全部满足：
    * 3、不能提交OR || 可提交但没有全通过：以下规则满足其中一个即可：
    * 4、提醒可提交：不合规仅提醒的规则，不影响提交流程：
    * */
    public String getTitle(String relation,List<List<Object>> ruleResultsList,int languageId){
        String type = getResultType(relation,ruleResultsList);
        return getTitle(type,languageId);
    }

    public String getTitle(String type,int languageId){
        switch (type){
            case "1":return SystemEnv.getHtmlLabelName(533494, languageId)+"：";
            case "2":return SystemEnv.getHtmlLabelName(533495, languageId)+"：";
            case "3":return SystemEnv.getHtmlLabelName(533496, languageId)+"：";
            case "4":return SystemEnv.getHtmlLabelName(533499, languageId)+"：";
            default:return "";
        }
    }

    public String getResultType(String relation,List<List<Object>> ruleResultsList){
        boolean needCheck = true;
        String type = "";
        int pass = 0;//通过
        int nopass = 0;//不通过
        int remind = 0;//提醒
        for(List<Object> ruleResultTmp : ruleResultsList){
            boolean ruleResult = (boolean)ruleResultTmp.get(0);
            String processType = Util.null2String(ruleResultTmp.get(1));
            if(needCheck){
                if("1".equals(relation) && (!ruleResult && "0".equals(processType))){//含不合规且为AND,后面都不用判断了,直接跳出循环
                    type = "2";
                    break;
                }else if(ruleResult){//合规
                    pass++;
                }else if(!ruleResult && "1".equals(processType)){//提醒
                    remind++;
                }else if("0".equals(relation) &&(!ruleResult && "0".equals(processType))){//不合规且为OR
                    nopass++;
                }
            }
        }
        if("".equals(type)){
            if((nopass == ruleResultsList.size()) || (pass>0 && pass != ruleResultsList.size() && "0".equals(relation))){//全为不合规且为OR 或 含合规不全为合规且为OR
                type = "3";
            }else if(remind>0 && ("1".equals(relation) || pass == 0)){//到这里只可能是 含不合规且为OR 和 不含合规 两种情况
                type = "4";
            }else{
                type = "1";
            }
        }
        return type;
    }
}
