package com.customization.cmd;

import com.alibaba.fastjson.JSON;
import com.cloudstore.dev.api.bean.MessageBean;
import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.workflow.cmd.requestForm.MsgPush_GetMsgBeansCmd;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@CommandDynamicProxy(target = MsgPush_GetMsgBeansCmd.class, desc = "流程数据推送消息cmd")
public class MsgPush_GetMsgBeansCmdProxyTitle extends AbstractCommandProxy<List<MessageBean>> {
    //匹配${text}的占位符
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}");
    private static final String getTitleAndFormsql = "select id,WFFORMNAME,TITLE from uf_gwtsth where WFID in( select id from workflow_base  where  activeversionid =( select activeversionid  from workflow_base where id = ?))";
    private static final String getdtFieldtype = "select FIELDNAME,TYPE from uf_gwtsth_dt1 where MAINID = ?";
    BaseBean bean = new BaseBean();

    @Override
    public List<MessageBean> execute(Command<List<MessageBean>> command) {
        BaseBean bb = new BaseBean();
        MsgPush_GetMsgBeansCmd cmd = (MsgPush_GetMsgBeansCmd) command;

        //获取MessageBeans
        List<MessageBean> list = cmd.getMessageBeans();
        if (!isOpen()) {
            return list;
        }
        //业务对象 流程id
        String targetId = "";
        RecordSet rs = new RecordSet();
        List<MessageBean> messageBeans = new ArrayList<>();

        try {
            for (int i = 0; i < list.size(); i++) {
                String requestname = "";
                String requestlevel = "";
                Integer wfid = 0;
                MessageBean messageBean = list.get(i);
                targetId = messageBean.getTargetId();
                if (targetId.indexOf("|") > 0) {
                    continue;
                }
                if (targetId.indexOf("_") > 0) {
                    // targetId = targetId.split("_")[0];
                    continue;
                }
                rs.execute("select requestlevel , workflowid ,requestname from workflow_requestbase where requestid = " + targetId);
                if (rs.next()) {
                    requestname = rs.getString("requestname");
                    wfid = Util.getIntValue(rs.getString("workflowid"));
                    requestlevel = rs.getString("requestlevel");
                }

                bean.writeLog("流程wfid==="+wfid);
                if (!isUpdateTitle(wfid)) {
                    //流程类型 3 是特急  2 是重要
                    if("3".equals(requestlevel)||"2".equals(requestlevel)){
                        messageBeans.add(messageBean);
                    }
                    continue;
                }
                rs.executeQuery(getTitleAndFormsql, wfid);
                String formTable = "";
                String title = "";
                String mainid = "";
                if (rs.next()) {
                    formTable = Util.null2String(rs.getString("WFFORMNAME"));
                    title = Util.null2String(rs.getString("TITLE"));
                    mainid = Util.null2String(rs.getString("id"));
                }
                Map<String, String> updateField = getUpdateField(mainid);
                String newTitle = "";
                if (updateField.size() > 0) {
                    Map<String, String> fieldValue = getFieldValue(formTable, targetId, updateField);
                    newTitle = replacePlaceholders(title, fieldValue);
                } else {
                    newTitle = title;
                }
                messageBean.setTitle(newTitle);
                //流程类型 3 是特急  2 是重要
                if("3".equals(requestlevel)||"2".equals(requestlevel)){
                    messageBeans.add(messageBean);
                }
            }
        } catch (Exception e) {
            bb.writeLog("异常信息" + e.getMessage());
            e.printStackTrace();
            return list;
        }

        bb.writeLog("新组建的messageBeans" + list);
        return list;
    }

    // 获取字段类型
    private Map<String, String> getUpdateField(String id) {
        HashMap<String, String> idTypeMap = new HashMap<>();
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(getdtFieldtype, id);
        while (recordSet.next()) {
            String field = Util.null2String(recordSet.getString("FIELDNAME"));
            String type = Util.null2String(recordSet.getString("TYPE"));
            idTypeMap.put(field, type);
        }
        return idTypeMap;
    }

    //根据建模表查询是否需要更新标题
    private boolean isUpdateTitle(int wfid) {

        String sql = "select count(1) cnt from uf_gwtsth where wfid in( select id from workflow_base  where  activeversionid =( select activeversionid  from workflow_base where id = ?))";

        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, wfid);
        int cnt = 0;
        if (rs.next()) {
            cnt = Util.getIntValue(rs.getString("cnt"), 0);
        }
        bean.writeLog("是否推送==="+cnt);
        return cnt > 0;
    }

    //配置文件是否开启
    private boolean isOpen() {
        String isopen = new BaseBean().getPropValue("updateMsgTitle", "isopen");
        return "1".equals(isopen);
        // return true;
    }


    //替换占位符
    public static String replacePlaceholders(String inputText, Map<String, String> placeholderValues) {
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(inputText);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String placeholder = matcher.group(1);
            String replacement = placeholderValues.get(placeholder);
            if (replacement != null) {
                matcher.appendReplacement(result, replacement);
            }
        }
        matcher.appendTail(result);

        return result.toString();
    }


    // 获取字段对应的值
    private Map<String, String> getFieldValue(String formName, String requestid, Map<String, String> fieldTypeMap) {
        HashMap<String, String> FieldValue = new HashMap<>();
        if (fieldTypeMap.size() == 0) {
            return FieldValue;
        }
        String sql = "select " + String.join(", ", fieldTypeMap.keySet()) + " from " + formName + " where REQUESTID = ?";
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        recordSet.executeQuery(sql, requestid);
        recordSet.next();
        fieldTypeMap.forEach((key, value) -> {
            //库里存的值
            String fieldValue = Util.null2String(recordSet.getString(key));
            //数据值  (防止在循环里创建recordSet对象,使用同一个recordSet对象)
            String FieldrealValue = getFieldRealValue(fieldValue, value, rs, formName, key);
            FieldValue.put(key, FieldrealValue);
        });
        return FieldValue;
    }

    private String getFieldRealValue(String fieldValue, String type, RecordSet rs, String formName, String fieldname) {
        //为空或者类型等于0(文本)直接返回字段值
        if (StringUtil.isEmpty(fieldValue) || StringUtil.isEmpty(type) || "0".equals(type)) {
            return fieldValue;
        }
        String sql = "";
        Boolean isMultiple = fieldValue.contains(",");
        if ("1".equals(type)) { //人力资源
            sql = "select lastName from HRMRESOURCE where id ";
            if (!isMultiple) {
                sql = sql + "= ?";
                rs.executeQuery(sql, fieldValue);
                if (rs.next()) {
                    return Util.null2String(rs.getString("lastName"));
                }
            } else {
                sql = sql + "in ( " + fieldValue + " )";
                ArrayList<String> fieldValues = new ArrayList<>();
                rs.executeQuery(sql);
                while (rs.next()) {
                    fieldValues.add(Util.null2String(rs.getString("lastName")));
                }
                return String.join(",", fieldValues);
            }
        } else if ("2".equals(type)) { //部门
            sql = "select DEPARTMENTNAME from HRMDEPARTMENT where id";
            if (!isMultiple) {
                sql = sql + "= ?";
                rs.executeQuery(sql, fieldValue);
                if (rs.next()) {
                    return Util.null2String(rs.getString("DEPARTMENTNAME"));
                }
            } else {
                sql = sql + "in ( " + fieldValue + " )";
                ArrayList<String> fieldValues = new ArrayList<>();
                rs.executeQuery(sql);
                while (rs.next()) {
                    fieldValues.add(Util.null2String(rs.getString("DEPARTMENTNAME")));
                }
                return String.join(",", fieldValues);
            }
        } else if ("3".equals(type)) { //分部
            sql = "select SUBCOMPANYNAME from HRMSUBCOMPANY where id";
            if (!isMultiple) {
                sql = sql + "= ?";
                rs.executeQuery(sql, fieldValue);
                if (rs.next()) {
                    return Util.null2String(rs.getString("SUBCOMPANYNAME"));
                }
            } else {
                sql = sql + "in ( " + fieldValue + " )";
                ArrayList<String> fieldValues = new ArrayList<>();
                rs.executeQuery(sql);
                while (rs.next()) {
                    fieldValues.add(Util.null2String(rs.getString("SUBCOMPANYNAME")));
                }
                return String.join(",", fieldValues);
            }
        } else if ("4".equals(type)) { //选择框
            String fid = "";
            sql = "select field.id fid from workflow_bill bill " +
                    "left join workflow_billfield field on bill.ID = field.BILLID  " +
                    "where TABLENAME = ? and FIELDNAME = ? ";
            rs.executeQuery(sql, formName, fieldname);
            bean.writeLog("选择框sql" + sql + formName + fieldname);
            if (rs.next()) {
                fid = Util.null2String(rs.getString("fid"));
            }
            bean.writeLog("fid===" + fid);
            sql = " select * from workflow_SelectItem where FIELDID = ? and SELECTVALUE ";
            if (!isMultiple) {
                sql = sql + "= ?";
                rs.executeQuery(sql, fid, fieldValue);
                bean.writeLog("选项sql===" + sql + fid + fieldValue);
                if (rs.next()) {
                    return Util.null2String(rs.getString("SELECTNAME"));
                }
            } else {
                sql = sql + "in ( " + fieldValue + " )";
                ArrayList<String> fieldValues = new ArrayList<>();
                rs.executeQuery(sql, fid);
                while (rs.next()) {
                    fieldValues.add(Util.null2String(rs.getString("SELECTNAME")));
                }
                return String.join(",", fieldValues);
            }
        } else if ("5".equals(type)) { //自定义
            String fid = "";
            String ftype = "";
            sql = "select field.id fid  , FIELDDBTYPE ftype from workflow_bill bill " +
                    "left join workflow_billfield field on bill.ID = field.BILLID  " +
                    "where TABLENAME = ? and FIELDNAME = ? ";
            rs.executeQuery(sql, formName, fieldname);
            bean.writeLog("选择框sql" + sql + formName + fieldname);
            if (rs.next()) {
                fid = Util.null2String(rs.getString("fid"));
                ftype = Util.null2String(rs.getString("ftype"));
            }
            String[] browArr =  ftype.split("\\.");
            if (browArr.length != 2){
                return "";
            }
            String brower = browArr[1];
            sql = "select a.SHOWNAME ,a.SQLTEXT ,c.FIELDNAME from  mode_browser a   " +
                    " left join mode_custombrowserdspfield b on a.CUSTOMID = b.CUSTOMID   " +
                    " left join workflow_billfield c on b.FIELDID = c.ID   " +
                    " where  b.ISTITLE > 0 and SHOWNAME = ? ";
            rs.executeQuery(sql, brower);
            bean.writeLog("选择框sql" + sql + "======"+brower);
            String showName = "";
            String sqltext = "";
            String linkName = "";
            if (rs.next()) {
                showName = Util.null2String(rs.getString("SHOWNAME"));
                sqltext = Util.null2String(rs.getString("SQLTEXT"));
                linkName = Util.null2String(rs.getString("FIELDNAME"));
            }
            if (!isMultiple) {
                sqltext = sqltext + "  where id = ?";
                rs.executeQuery(sqltext, fieldValue);
                bean.writeLog("选项sql===" + sqltext + fid + fieldValue);
                if (rs.next()) {
                    return Util.null2String(rs.getString(linkName));
                }
            } else {
                sqltext = sqltext + "  where id in ( " + fieldValue + " )";
                ArrayList<String> fieldValues = new ArrayList<>();
                rs.executeQuery(sql);
                while (rs.next()) {
                    fieldValues.add(Util.null2String(rs.getString(linkName)));
                }
                return String.join(",", fieldValues);
            }

        }
        return null;
    }



}