package com.engine.workflow.biz.newRule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 规则导入标准类
 */
public class RuleImportBiz {

    User user;

    public RuleImportBiz(User user) {
        this.user = user;
    }

    public Map<String, String> idMap = new HashMap<>();

    public String doImport(String jsonStr) {
//        InputStream is = ImageFileManager.getInputStreamById(fileId);

//        String jsonStr = new BufferedReader(new InputStreamReader(is))
//                .lines().collect(Collectors.joining(System.lineSeparator()));

//        String jsonStr = "{\"newrule_valuebase\":{\"valuetype\":\"98\",\"detailtype\":\"1\",\"valueid\":\"1353352332988907521\",\"paramtype\":\"0\",\"expressionbaseid\":\"1353352461724680192\",\"valuetext\":\"1111\",\"fieldhtmltype\":\"1\",\"ruleid\":\"1344133919628328960\",\"value\":\"1111\",\"fielddbtype\":\"-1\"},\"newrule_expressions\":{\"expressionid\":\"1353352461766623232\",\"expids\":\"\",\"expbaseid\":\"1353352461724680192\",\"isroot\":\"\",\"ruleid\":\"1344133919628328960\",\"relation\":\"-1\"},\"newrule_expressionbase\":{\"elementvalue1id\":\"1353352332988907522\",\"expressionbaseid\":\"1353352461724680192\",\"compareoption1\":\"5\",\"compareoption2\":\"-1\",\"ruleid\":\"1344133919628328960\",\"elementvalue2id\":\"1353352332988907523\",\"datavalueid\":\"1353352332988907521\"},\"newrule_base\":{\"sourceid\":\"\",\"condit\":\"(1111 等于 '22222' )\",\"ruledesc\":\"\",\"orderid\":\"\",\"rulepassedtip\":\"\",\"nopassprocesstype\":\"0\",\"rulename\":\"cxbtest\",\"source\":\"0\",\"ruleid\":\"1344133919628328960\",\"rulenopasstip\":\"$_variableName1353352332988907521_$$_variable1353352332988907521_$\",\"drl\":\"package rules_1344133919628328960 import com.engine.workflow.biz.newRule.RuleValueManager; \\r\\nrule \\\"1344133919628328960\\\" \\r\\nwhen $obj : RuleValueManager\\r\\n(((\\r\\n$obj.getValue(\\\"1344133999647260672\\\") >= $obj.getValue(\\\"1344133999647260673\\\")\\r\\n && \\r\\n$obj.getValue(\\\"1344133999647260672\\\") >= $obj.getValue(\\\"1344133999647260674\\\")\\r\\n)\\r\\n))\\r\\nthen $obj.setRulePass(true); end\"}}";

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);

        JSONArray ruleBase = jsonObject.getJSONArray("newrule_base");
        //生成新的ruleid
        String ruleId = Util.null2String(ruleBase.getJSONObject(0).get("ruleid"));
        String newRuleId = RuleSetBiz.generateNewId();
        idMap.put(ruleId, newRuleId);

        //导入变量基本信息
        JSONArray valueBases = jsonObject.getJSONArray("newrule_valuebase");
        for (int i = 0; i < valueBases.size(); i++) {
            insertDatas("newrule_valuebase", valueBases.getJSONObject(i));
        }

        //导入规则基础信息
        insertDatas("newrule_base", ruleBase.getJSONObject(0));

        //导入表达式基本信息
        JSONArray expressionBases = jsonObject.getJSONArray("newrule_expressionbase");
        for (int i = 0; i < expressionBases.size(); i++) {
            insertDatas("newrule_expressionbase", expressionBases.getJSONObject(i));
        }

        //导入表达式关系数据
        JSONArray expressions = jsonObject.getJSONArray("newrule_expressions");
        JSONArray expressions_expJson = new JSONArray();
        List<String> expressions_expid = new ArrayList<>();
        List<String> expressions_id = new ArrayList<>();
        for (int i = 0; i < expressions.size(); i++) {
            JSONObject dataInfo = expressions.getJSONObject(i);
            if(!"".equals(Util.null2String(dataInfo.get("expbaseid")))){
                expressions_expid.add(Util.null2String(dataInfo.get("expressionid")));
                insertDatas("newrule_expressions", dataInfo);
            }else{
                expressions_expJson.add(dataInfo);
            }
            expressions_id.add(Util.null2String(dataInfo.get("expressionid")));
        }
        insertExpressionsDatas(expressions_expJson,expressions_expid,expressions_id);


        //重新生成drl表达式
        new DroolsGenerator().generateDroolsExpression(newRuleId);

        return newRuleId;
    }

    private void insertExpressionsDatas(JSONArray expressionsArry,List<String> expressions_expid) {
        insertExpressionsDatas(expressionsArry,expressions_expid,new ArrayList<>());
    }
    private void insertExpressionsDatas(JSONArray expressionsArry,List<String> expressions_expid,List<String> expressions_id) {
        JSONArray expressionsArryTmp = new JSONArray();
        for (int i = 0; i < expressionsArry.size(); i++) {
            JSONObject dataInfo = expressionsArry.getJSONObject(i);
            boolean canInsert = true;
            boolean valid = true;
            List<String> expids = Util.TokenizerString(Util.null2String(dataInfo.get("expids")),",");
            for(String expid : expids){
                if(!expressions_expid.contains(expid)){
                    canInsert = false;
                }
                if(expressions_id.size() > 0 && !expressions_id.contains(expid)){
                    valid = false;
                }
            }
            if(canInsert){
                insertDatas("newrule_expressions", dataInfo);
                expressions_expid.add(Util.null2String(dataInfo.get("expressionid")));
            }else if(valid){
                expressionsArryTmp.add(dataInfo);
            }
        }
        if(expressionsArryTmp.size() > 0){
            insertExpressionsDatas(expressionsArryTmp,expressions_expid,expressions_id);
        }
    }

    /**
     * 将jsonObject数据，插入到对应数据表
     * @param tableName
     * @param dataInfo
     */
    public void insertDatas(String tableName, JSONObject dataInfo) {
        String sqlColumn = "insert into " + tableName + " ( ";
        String sqlValue = " values ( ";
        List<Object> valueList = new ArrayList<>();
        Set<String> colNames = dataInfo.keySet();

        for (String colName : colNames) {
            //uuid需要自动生成
            if(colName.equalsIgnoreCase("uuid")){
                continue;
            }
            sqlColumn += colName + ",";
            sqlValue += "?,";
            String value = valueTrans(tableName, colName, Util.null2String(dataInfo.get(colName)));
            valueList.add("".equals(value) ? null : value);
        }

        //去除末尾的逗号
        sqlColumn = sqlColumn.substring(0, sqlColumn.length() - 1);
        sqlValue = sqlValue.substring(0, sqlValue.length() - 1);

        RecordSet rs = new RecordSet();
        rs.executeUpdate(sqlColumn + ") " + sqlValue + " )", valueList);
    }

    /**
     * 数据转换，主要是针对主键重新生成
     * @param tableName
     * @param colName
     * @param value
     * @return
     */
    public String valueTrans(String tableName, String colName, String value) {
        //为主键，需要替换
        if(colName.equals("ruleid") || colName.equals("expressionid") || colName.equals("datavalueid") ||
                colName.equals("elementvalue1id") || colName.equals("elementvalue2id") || colName.equals("valueid") ||
                colName.equals("expbaseid") || colName.equals("expressionbaseid")) {
            if(idMap.containsKey(value)) {
                value = idMap.get(value);
            } else if(!"".equals(value)){
                String newValue = RuleSetBiz.generateNewId();
                idMap.put(value, newValue);
                value = newValue;
            }
        } else if(tableName.equals("newrule_expressions") && colName.equals("expids")) {
            //expids做特殊处理
            String newExpbaseIds = "";
            String[] expbaseIds = value.split(",");
            for (String expbaseId : expbaseIds) {
                newExpbaseIds += idMap.get(expbaseId) + ",";
            }
            value = newExpbaseIds.substring(0, newExpbaseIds.length() - 1);
        } else if(tableName.equals("newrule_base") && (colName.equals("rulenopasstip") || colName.equals("rulepassedtip"))) {
            //替换提示语的变量id
            for (String key : idMap.keySet()) {
                value = value.replace(key, idMap.get(key));
            }
        } else if(tableName.equals("newrule_base") && colName.equals("rulename")) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String curtime = formatter.format(new Date());
            value = value+"("+curtime+ SystemEnv.getHtmlLabelName(18596, user.getLanguage())+")";
        }
        return value;
    }

    public Map<String, String> getIdMap(){
        return idMap;
    }
}
