/*
 *
 * Copyright (c) 2001-2016 泛微软件.
 * 泛微协同商务系统,版权所有.
 *
 */
package weaver.ofs.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_DataCache;
import com.cloudstore.dev.api.util.Util_Message;
import com.engine.msgcenter.biz.ConfigManager;
import com.engine.msgcenter.biz.WeaMessageTypeConfig;
import com.engine.workflow.biz.requestSubmit.RequestOperationBiz;
import com.google.common.collect.Sets;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;

import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.cache.OfsSysInfoCacheNew;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.ofs.bean.*;
import weaver.ofs.dao.OfsSettingCacheDAO;
import weaver.ofs.dao.OfsSysInfoCacheDAO;
import weaver.ofs.dao.OfsWorkflowCacheDAO;
import weaver.ofs.manager.remind.*;
import weaver.ofs.manager.utils.OfsTodoDataUtils;
import weaver.ofs.mq.bean.AsyncListenerBean;
import weaver.ofs.mq.init.InitOfsMqMonitor;
import weaver.ofs.mq.publisher.OfsMqSendMessage;
import weaver.ofs.mq.selector.QueueSelector;
import weaver.ofs.mq.util.OfsCacheLockUtil;
import weaver.ofs.service.*;
import weaver.ofs.util.OfsUtils;
import weaver.ofs.utils.CheckIP;
import weaver.rtx.RTXConfig;
import weaver.security.util.SecurityMethodUtil;

import weaver.systeminfo.SystemEnv;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;


/**
 * 统一待办数据处理类
 *
 * @version 1.0
 */
public class OfsTodoDataManagerNew implements IOfsTodoDataManager {


    public void isAnalysis() {

//        OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//        ofsSettingCacheNew.next();

        OfsSettingCacheDAO ofsSettingCacheDAO = new OfsSettingCacheDAO();
        OfsSetting ofsSettingCache = ofsSettingCacheDAO.getOfsSettingCache();
        if ("1".equals(ofsSettingCache.getInvokewsLog()) || "1".equals(ofsSettingCache.getInvokerestLog())) {

            OfsTodoDataManagerNewProxy proxy = new OfsTodoDataManagerNewProxy(this);
            ofsTodoDataManager = proxy.getOfsManager();
        } else {
            ofsTodoDataManager = this;
        }

    }

    /**
     * 统一待办业务处理对象
     */
    private IOfsTodoDataManager ofsTodoDataManager = null;


    public Map<String, Object> jsonToMap(String json) {

        return (Map<String, Object>) JSON.parse(json);
    }


    public Map<String, Object> xmlToMap(String xml) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            xml = SecurityMethodUtil.clearEntity(xml);

            if (xml == null || "".equals(xml))
                return map;

            Document doc = parseText(xml);

            if (doc == null)
                return map;
            Element root = doc.getRootElement();
            for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
                Element e = (Element) iterator.next();
                if ("custom".equals(e.getName())) {
                    Map<String, String> map2 = new HashMap<String, String>();
                    List list = e.elements();
                    for (int i = 0; i < list.size(); i++) {
                        Element e2 = (Element) list.get(i);
                        map2.put(e2.getName(), e2.getText());
                    }
                    map.put(e.getName(), map2);
                } else {
                    map.put(e.getName(), e.getText());
                }
            }
        } catch (Exception e) {
            log.error("xml 转map 异常", e);
        }
        return map;
    }

    public Document parseText(String text) throws Exception {
        Document result = null;
        SAXReader reader = new SAXReader();
        reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        String encoding = getEncoding(text);
        InputSource source = new InputSource(new StringReader(text));
        source.setEncoding(encoding);
        result = reader.read(source);
        if (result.getXMLEncoding() == null) {
            result.setXMLEncoding(encoding);
        }

        return result;
    }

    private String getEncoding(String text) {
        String result = null;
        String xml = text.trim();
        if (xml.startsWith("<?xml")) {
            int end = xml.indexOf("?>");
            String sub = xml.substring(0, end);
            StringTokenizer tokens = new StringTokenizer(sub, " =\"'");

            while (tokens.hasMoreTokens()) {
                String token = tokens.nextToken();
                if ("encoding".equals(token)) {
                    if (tokens.hasMoreTokens()) {
                        result = tokens.nextToken();
                    }
                    break;
                }
            }
        }

        return result;
    }


    /**
     * 日志打印对象
     */
    public static Logger log = LoggerFactory.getLogger("ofs", OfsTodoDataManagerNew.class.getName());
    /**
     * 系统管理员ID
     */
    public static final String SYSADMIN_ID = "1";
    /**
     * 待办信息处理返回xml结果根元素
     */
    public static final String RESULT_XML_ROOT = "ResultInfo";
    /**
     * 缺省数据id
     */
    public static final int DEFAULT_DATA_ID = 0;//缺省数据id
    /**
     * 下划线分隔符
     */
    public static final String LINK_CHAR = "_";
    /**
     * 统一待办数据处理对象
     */
    public static OfsTodoDataServiceNew ofsTodoDataService = new OfsTodoDataServiceNew();
    /**
     * 统一待办系统信息对象
     */
    public static OfsSysInfoService ofsSysInfoService = new OfsSysInfoService();
    /**
     * 统一待办流程对象
     */
    public static OfsWorkflowService ofsWorkflowService = new OfsWorkflowService();
    /**
     * 统一待办设置业务对象
     */
    private OfsSettingService ofsSettingService = new OfsSettingService();
    /**
     * 统一待办处理日志记录对象
     */
    public static OfsLogServiceNew ofsLogService = new OfsLogServiceNew();
    public static OfsRequestBaseService ofsRequestBaseService = new OfsRequestBaseService();
    public static OfsDoneDataService ofsDoneDataService = new OfsDoneDataService();

    public static OfsMqSendMessage ofsMqSendMessage = new OfsMqSendMessage();
    /**
     * 访问Ip
     */
    public String clientIp;//访问Ip

    private boolean isCheckIP = true;//是否校验 IP
    private boolean isAuto = true;//是否自动
    private final boolean isSnowflake = InitOfsMqMonitor.isSnowflake;//是否开启雪花算法
    private final String queuePrefix = InitOfsMqMonitor.queuePrefix;//队列的前缀
    private final Integer queueCount = InitOfsMqMonitor.queueCount;//分的队列个数

    public void setIsCheckIP(boolean isCheckIP) {
        this.isCheckIP = isCheckIP;
    }

    public void setIsAuto(boolean isAuto) {
        this.isAuto = isAuto;
    }

    /**
     * 获取访问Ip
     */
    public String getClientIp() {
        return clientIp;
    }

    /**
     * 设置访问Ip
     */
    public void setClientIp(String clientIp) {
        this.clientIp = clientIp;
    }

    /**
     * 接收待办流程
     */
    public Map<String, String> receiveTodoRequestByMap(Map<String, Object> dataMap) {


        // 业务数据
        dataMap.put("isremark", OfsTodoData.IsRemark_Todo);
        dataMap.put("viewtype", OfsTodoData.ViewType_None);
        dataMap.put("iscomplete", OfsTodoData.IsComplete_No);
        //TODO 如果已经解析完成不用再次解析
        Object custom = dataMap.get("custom");
        if (custom instanceof Map) {

        } else {
            String str = (String) dataMap.get("custom");
            Map<String, Object> map = xmlToMap(str);
            dataMap.put("custom", map);
        }

        return this.receiveRequestInfo(dataMap, "todo");
    }

    /**
     * 接收待办流程(json格式)
     */
    public String receiveTodoRequestByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.receiveTodoRequestByMap(dataMap);

        return OfsUtils.mapToJson(resultMap);
    }

    /**
     * 接收待办流程(xml格式)
     */
    public String receiveTodoRequestByXml(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.receiveTodoRequestByMap(dataMap);
        return OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);
    }

    /**
     * 接收异构系统流程(map格式)
     */
    public Map<String, String> receiveRequestInfoByMap(Map<String, Object> dataMap) {

        //TODO 如果已经解析完成不用再次解析
        Object custom = dataMap.get("custom");
        if (custom instanceof Map) {

        } else {
            String str = (String) dataMap.get("custom");
            Map<String, Object> map = xmlToMap(str);
            dataMap.put("custom", map);
        }
        return this.receiveRequestInfo(dataMap, "info");
    }

    /**
     * 删除异构系统流程(map格式)
     */
    public Map<String, String> deleteRequestInfoByMap(Map<String, Object> dataMap) {

        String syscode = Util.null2String((String) dataMap.get("syscode"));
        String flowid = Util.null2String((String) dataMap.get("flowid"));

        return this.deleteRequestInfo(
                syscode,
                flowid
        );
    }

    /**
     * 删除异构系统流程(json格式)
     */
    public String deleteRequestInfoByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.deleteRequestInfoByMap(dataMap);

        return OfsUtils.mapToJson(resultMap);
    }

    /**
     * 删除异构系统流程(xml格式)
     */
    public String deleteRequestInfoByXML(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.deleteRequestInfoByMap(dataMap);
        return OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);
    }

    /**
     * 删除用户异构系统流程(map格式)
     */
    public Map<String, String> deleteUserRequestInfoByMap(Map<String, Object> dataMap) {


        String syscode = Util.null2String((String) dataMap.get("syscode"));
        String flowid = Util.null2String((String) dataMap.get("flowid"));
        String userid = Util.null2String((String) dataMap.get("userid"));
        if (StringUtils.isBlank(userid)) {
            userid = Util.null2String((String) dataMap.get("receiver"));
        }

        return this.deleteUserRequestInfo(
                syscode,
                flowid,
                userid
        );
    }

    /**
     * 根据用户id删除异构系统流程(json格式)
     */
    public String deleteUserRequestInfoByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.deleteUserRequestInfoByMap(dataMap);

        return OfsUtils.mapToJson(resultMap);
    }

    /**
     * 根据用户id删除异构系统流程(xml格式)
     */
    public String deleteUserRequestInfoByXML(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.deleteUserRequestInfoByMap(dataMap);
        return OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);
    }


    /**
     * 接收异构系统流程(json格式)
     */
    public String receiveRequestInfoByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.receiveRequestInfoByMap(dataMap);
        return OfsUtils.mapToJson(resultMap);
    }

    /**
     * 接收异构系统流程(xml格式)
     */
    public String receiveRequestInfoByXml(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.receiveRequestInfoByMap(dataMap);
        return OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);
    }

    public int buildRequestid(OfsTodoData data) {
        String requestid = ofsRequestBaseService.buildRequestid(data) + "";
        return Util.getIntValue(requestid);
    }

    public String buildRequestidForSnowflake(OfsTodoData data) {
        return ofsRequestBaseService.buildRequestidForSnowflake(data) + "";
    }

    public synchronized int getTodoDataId(OfsTodoData data) {
        int todoDataId = ofsTodoDataService.getTodoDataId(data.getSyscode(), data.getFlowid(), data.getUserid());
        return todoDataId;
    }

    @Override
    public synchronized int getDoneDataId(OfsTodoData data) {
        int doneDataId = ofsDoneDataService.getDoneDataId(data.getSyscode(), data.getFlowid(), data.getUserid());
        return doneDataId;
    }

    private Map<String, String> isAuto(OfsTodoData data) {
        Map<String, String> map = new HashMap<>();
        if (this.isAuto) {
            map.put("isauto", "" + SystemEnv.getHtmlLabelName(81855, weaver.general.ThreadVarLanguage.getLang()) + "");
            if ("0".equals(data.getId()) && "0".equals(data.getFlowguid())) {
                map.put("type", OfsLog.OperType_AutoNew);
            } else {
                map.put("type", OfsLog.OperType_AutoEdit);
            }
        } else {
            map.put("isauto", "" + SystemEnv.getHtmlLabelName(125582, weaver.general.ThreadVarLanguage.getLang()) + "");
            if ("0".equals(data.getId()) && "0".equals(data.getFlowguid())) {
                map.put("type", OfsLog.OperType_New);
            } else {
                map.put("type", OfsLog.OperType_Edit);
            }
        }
        return map;
    }

    private void copy(OfsTodoData source, OfsTodoData target) {


        try {
            Field[] fields = OfsTodoData.class.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String fieldName = field.getName();
                if (!fieldName.equals("custom") &&
                        !fieldName.equals("flowguid") &&
                        !fieldName.equals("id") &&
                        !fieldName.equals("isremark") &&
                        !fieldName.equals("viewtype") &&
                        !fieldName.equals("operatedate") &&
                        !fieldName.equals("operatetime") &&
                        !fieldName.equals("receivets") &&
                        !fieldName.equals("isauto")
                ) {
                    field.setAccessible(true);
                    Object o = field.get(target);
                    if (o == null) {
                        field.set(target, field.get(source));
                    }
                    if (o instanceof String) {
                        String str = (String) o;
                        if (StringUtils.isBlank(str)) {
                            field.set(target, field.get(source));
                        }
                    }
                }
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
            log.error("复制数据异常", e);
        }
    }

    public String saveData(OfsSysInfo ofsSysInfoCache, OfsTodoData data) {
        String isremark = data.getIsremark();
        String viewtype = data.getViewtype();
        String requestname = data.getRequestname();

        String pcurl = data.getPcurl();
        String appurl = data.getAppurl();

        String nodename = data.getNodename();
        String workflowname = data.getWorkflowname();

        String isremarkName = buildIsRemarkName(data);
        String OfsSysInfo_sysname = ofsTodoDataManager.buildSysName(data);//系统显示名称
        String OfsLog_OperType = OfsLog.OperType_AutoNew;
        String operresult = OfsLog.OperResult_Success;

        String returnMessage = "";
        int todoDataId = 0;


        // 从redis中获取数据是否存在
        String key = data.getSyscode() + "_" + data.getFlowid() + "_" + data.getUserid();
        Map<String, String> cache = null;//(Map<String,String>)Util_DataCache.getObjVal(key);
        String isremarkcache = "";
        /*if(cache != null){
            todoDataId = Util.getIntValue(cache.get("id"),0);
            isremarkcache = cache.get("isremark");
            data.setId(todoDataId+"");
        }*/
        // boolean issend = false;

        if ("0".equals(data.getIsremark()) || "8".equals(data.getIsremark())) {

            if ("0".equals(data.getId()) || !isremarkcache.equals(data.getIsremark())) {
                todoDataId = ofsTodoDataManager.getTodoDataId(data);
                data.setId(todoDataId + "");
            }


            int doneDataId = ofsTodoDataManager.getDoneDataId(data);
            data.setFlowguid(doneDataId + "");
            Map<String, String> auto = isAuto(data);
            OfsLog_OperType = auto.get("type");
            if ("0".equals(data.getId())) {//流程数据不存在

                boolean flag = isNeedUpdate(cache, data);

                if (flag) {

                    /**
                     * TODO 更改下逻辑
                     * 1 先删除数据
                     * 2 获取删除的结果，如果删除影响0行
                     * 3 就不添加新的数据
                     * 4 那待办和已办都没有，怎么办？
                     *
                     * */

                    //保存流程数据
                    boolean OfsTodoData_insert_flag = ofsTodoDataService.receiveRequestInfoInsert(data);
                    if (!(OfsTodoData_insert_flag)) {
                        boolean OfsTodoData_update_flag = ofsTodoDataService.receiveRequestInfoUpdate(data);
                        if (!(OfsTodoData_update_flag)) {
                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(83946, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(498, weaver.general.ThreadVarLanguage.getLang()) + "";
                            operresult = OfsLog.OperResult_Failure;
                        } else {
                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
                        }
                    } else {
                        returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(83946, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";

                        if (!"0".equals(data.getFlowguid())) {
                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
                        }
                    }
                    if (!OfsLog.OperResult_Failure.equals(operresult)) {
                        //获取主键
                        int id = ofsTodoDataService.getTodoDataId(data.getSyscode(), data.getFlowid(), data.getUserid());
                        data.setId(id + "");
                        Map<String, String> map = new HashMap<>();
                        map.put("requestid", data.getRequestid());
                        map.put("receivets", data.getReceivets());
                        map.put("isremark", data.getIsremark());
                        map.put("id", id + "");
                        Util_DataCache.setObjVal(key, map, 60 * 60 * 24);
                        //删除已办数据
                        boolean delete = ofsDoneDataService.delete(data.getSyscode(), data.getFlowid(), data.getUserid());
                        //ofsTodoDataManager.updatePcurlAndAppurl(ofsSysInfoCacheNew,data);

                        //待办才发送消息提醒
                        if ((isremark.equals(OfsTodoData.IsRemark_Todo) || isremark.equals("8") || isremark.equals("9")) && viewtype.equals(OfsTodoData.ViewType_None)) {
                            // TODO 注意 待办和已办 要处理一个是否按照时间戳更新的逻辑
                            ofsTodoDataManager.sendMessage(ofsSysInfoCache, OfsSysInfo_sysname, data);
                        }
                    }
                } else {
                    returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】"
                            + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(83946, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "，"
                            + SystemEnv.getHtmlLabelName(389993, weaver.general.ThreadVarLanguage.getLang()) + "，" +
                            SystemEnv.getHtmlLabelName(507856, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(567, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(23989, weaver.general.ThreadVarLanguage.getLang()) + "【receivets：" + data.getReceivets() + "】";
                }

            } else {
                boolean flag = isNeedUpdate(cache, data);

                if (flag) {

                    //数据存在，做更新操作 保存流程数据；
                    boolean OfsTodoData_update_flag = ofsTodoDataService.receiveRequestInfoUpdate(data);

                    if (!(OfsTodoData_update_flag)) {
                        returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(498, weaver.general.ThreadVarLanguage.getLang()) + "";
                        operresult = OfsLog.OperResult_Failure;
                    } else {
                        returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
                        //删除已办数据
                        boolean delete = ofsDoneDataService.delete(data.getSyscode(), data.getFlowid(), data.getUserid());
                        Map<String, String> map = new HashMap<>();
                        map.put("requestid", data.getRequestid());
                        map.put("receivets", data.getReceivets());
                        map.put("isremark", data.getIsremark());
                        map.put("id", data.getId());
                        Util_DataCache.setObjVal(key, map, 60 * 60 * 24);
                        //ofsTodoDataManager.updatePcurlAndAppurl(ofsSysInfoCacheNew,data);

                        //待办才发送消息提醒
                        if ((isremark.equals(OfsTodoData.IsRemark_Todo) || isremark.equals("8") || isremark.equals("9")) && viewtype.equals(OfsTodoData.ViewType_None)) {
                            // TODO 注意 待办和已办 要处理一个是否按照时间戳更新的逻辑
                            ofsTodoDataManager.sendMessage(ofsSysInfoCache, OfsSysInfo_sysname, data);
                        }
                    }
                } else {
                    returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" +
                            SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "，" +
                            SystemEnv.getHtmlLabelName(389993, weaver.general.ThreadVarLanguage.getLang()) + "，" +
                            SystemEnv.getHtmlLabelName(507856, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(567, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(23989, weaver.general.ThreadVarLanguage.getLang()) + "【receivets：" + data.getReceivets() + "】";
                }
            }


        } else if ("2".equals(data.getIsremark()) || "4".equals(data.getIsremark())) {
            // TODO  非待办从已办表查询todoDataId
            if ("0".equals(data.getId()) || !isremarkcache.equals(data.getIsremark())) {
                todoDataId = ofsTodoDataManager.getDoneDataId(data);
            }

            int id = ofsTodoDataManager.getTodoDataId(data);

            if (id == 0) {

            } else {
                OfsTodoData one = ofsTodoDataService.getOneBean(id);
                String isremarkbak = data.getIsremark();
                String receivets = data.getReceivets();
                //BeanUtils.copyProperties(one,data);
                copy(one, data);
                //单点登录地址
                String pcentranceurl = ofsSysInfoCache.getPcentranceurl();
                String appentranceurl = ofsSysInfoCache.getAppentranceurl();

                data.setIsremark(isremarkbak);
                data.setViewtype(viewtype);
                data.setReceivets(receivets);
                data.setRequestname(requestname);
                data.setPcurl(pcurl);
                data.setAppurl(appurl);
                data.setNodename(nodename);
                data.setWorkflowname(workflowname);

                if (StringUtils.isBlank(pcurl)) {
                    data.setPcurl(one.getPcurl());
                    if (StringUtils.isNotBlank(pcentranceurl)) {//兼容历史数据  历史数据 有中转页面 pcurl 和 pcurlsrc 不一致
                        data.setPcurl(one.getPcurlsrc());
                    }
                }
                if (StringUtils.isBlank(appurl)) {
                    data.setAppurl(one.getAppurl());
                    if (StringUtils.isNotBlank(appentranceurl)) {//兼容历史数据  历史数据 有中转页面 appurl 和 appurlsrc 不一致
                        data.setAppurl(one.getAppurlsrc());
                    }
                }
            }
            data.setFlowguid(id + "");

            data.setId(todoDataId + "");
            Map<String, String> auto = isAuto(data);
            OfsLog_OperType = auto.get("type");
            if ("0".equals(data.getId())) {

                boolean isNeedUpdate = isNeedUpdate(cache, data);
                if (isNeedUpdate) {

                    //保存流程数据
                    boolean flag = ofsDoneDataService.receiveRequestInfoInsert(data);
                    if (!(flag)) {
                        returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(83946, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(498, weaver.general.ThreadVarLanguage.getLang()) + "";
                        operresult = OfsLog.OperResult_Failure;
                    } else {
                        //删除待办数据
                        boolean delete = ofsTodoDataService.delete(data.getSyscode(), data.getFlowid(), data.getUserid());
                        returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(83946, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
                        int doneDataId = ofsDoneDataService.getDoneDataId(data.getSyscode(), data.getFlowid(), data.getUserid());
                        data.setId(doneDataId + "");

                        Map<String, String> map = new HashMap<>();
                        map.put("requestid", data.getRequestid());
                        map.put("receivets", data.getReceivets());
                        map.put("isremark", data.getIsremark());
                        map.put("id", doneDataId + "");
                        Util_DataCache.setObjVal(key, map, 60 * 60 * 24);
                        // 新建的已办数据，加一个已办的消息
                        /*if(id == 0){
                            issend = true;
                        }*/
                        if (!"0".equals(data.getFlowguid())) {
                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
                        }
                    }

                } else {
                    returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + ""
                            + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName +
                            "，" +
                            SystemEnv.getHtmlLabelName(389993, weaver.general.ThreadVarLanguage.getLang()) + "，" +
                            SystemEnv.getHtmlLabelName(507856, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(567, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(23989, weaver.general.ThreadVarLanguage.getLang()) + "【receivets：" + data.getReceivets() + "】";
                }

            } else {
                boolean isNeedUpdate = isNeedUpdate(cache, data);
                if (isNeedUpdate) {

                    //数据存在，做更新操作 保存流程数据；
                    boolean flag = ofsDoneDataService.receiveRequestInfoUpdate(data);

                    if (!(flag)) {
                        returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(498, weaver.general.ThreadVarLanguage.getLang()) + "";
                        operresult = OfsLog.OperResult_Failure;
                    } else {
                        //删除待办数据
                        boolean delete = ofsTodoDataService.delete(data.getSyscode(), data.getFlowid(), data.getUserid());
                        returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
                        Map<String, String> map = new HashMap<>();
                        map.put("requestid", data.getRequestid());
                        map.put("receivets", data.getReceivets());
                        map.put("isremark", data.getIsremark());
                        map.put("id", data.getId());
                        Util_DataCache.setObjVal(key, map, 60 * 60 * 24);
                    }
                } else {
                    returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName +
                            "，" +
                            SystemEnv.getHtmlLabelName(389993, weaver.general.ThreadVarLanguage.getLang()) + "，" +
                            SystemEnv.getHtmlLabelName(507856, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(567, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(23989, weaver.general.ThreadVarLanguage.getLang()) + "【receivets：" + data.getReceivets() + "】";
                }
            }


            //ofsTodoDataManager.updatePcurlAndAppurlInDone(ofsSysInfoCacheNew,data);
            /*if (issend){
                ofsTodoDataManager.sendMessage(ofsSysInfoCacheNew,OfsSysInfo_sysname,data);
            }*/
            User user = new User(Integer.parseInt(data.getUserid()));

            RequestOperationBiz.addWorkflowCount(Integer.parseInt(data.getWorkflowid()), user);
            //将所有已办且iscomplete=0变更为iscomplete=1；不处理待办情况
            boolean b = ofsDoneDataService.processOverRequestComplete(data.getSyscode(), data.getFlowid());
        } else if (StringUtils.isBlank(isremark)) {

            int idTodo = ofsTodoDataManager.getTodoDataId(data);
            int idDone = ofsTodoDataManager.getDoneDataId(data);
            Map<String, String> auto = isAuto(data);
            OfsLog_OperType = auto.get("type");

            if (idTodo == 0 && idDone == 0) {

                returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】"
                        + SystemEnv.getHtmlLabelName(23084, weaver.general.ThreadVarLanguage.getLang()) + "";

                ofsTodoDataManager.saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + data.getId(), OfsLog_OperType, operresult, returnMessage, data);
                return "-2";
            } else {

                boolean isNeedUpdate = isNeedUpdate(cache, data);
                if (isNeedUpdate) {

                    if (idTodo > 0) {
                        //数据存在，做更新操作 保存流程数据；
                        boolean OfsTodoData_update_flag = ofsTodoDataService.receiveRequestInfoUpdate(data);

                        if (!(OfsTodoData_update_flag)) {
                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】"
                                    + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + ""
                                    + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang()) + ""
                                    + SystemEnv.getHtmlLabelName(498, weaver.general.ThreadVarLanguage.getLang()) + "";
                            operresult = OfsLog.OperResult_Failure;
                        } else {
                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】"
                                    + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + ""
                                    + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang()) + ""
                                    + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
                        }
                    }
                    if (idDone > 0) {
                        boolean flag = ofsDoneDataService.receiveRequestInfoUpdate(data);

                        if (!(flag)) {
                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + ""
                                    + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang())
                                    + "" + SystemEnv.getHtmlLabelName(498, weaver.general.ThreadVarLanguage.getLang()) + "";
                            operresult = OfsLog.OperResult_Failure;
                        } else {

                            returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】" + auto.get("isauto") + ""
                                    + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + ""
                                    + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang()) + ""
                                    + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";

                        }
                    }
                } else {
                    returnMessage = "" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + requestname + "】"
                            + auto.get("isauto") + "" + SystemEnv.getHtmlLabelName(130625, weaver.general.ThreadVarLanguage.getLang()) + ""
                            + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang()) +
                            "，" +
                            SystemEnv.getHtmlLabelName(389993, weaver.general.ThreadVarLanguage.getLang()) + "，" +
                            SystemEnv.getHtmlLabelName(507856, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(567, weaver.general.ThreadVarLanguage.getLang()) +
                            SystemEnv.getHtmlLabelName(23989, weaver.general.ThreadVarLanguage.getLang()) + "【receivets：" + data.getReceivets() + "】";
                }
            }

        }
        //TODO 设置消息已处理
        //  if((isremark.equals("2") || isremark.equals("4")) && !issend ){
        Set<String> userids = new HashSet<String>();
        userids.add(data.getUserid());
        try {
            // Util_Message.updateBizState(userids,data.getSyscode()+"_"+data.getFlowid(),"1");
            Map<String, Object> urlMap = getURL(ofsSysInfoCache, data);
            if (isremark.equals("2") || isremark.equals("4")) {
                Util_Message.updateBizState(userids, data.getSyscode() + "_" + data.getFlowid(), "1");
            }
        } catch (Exception e) {
            log.error("消息已处理异常——userids：" + userids + "，syscode+_+flowid：" + data.getSyscode() + "_" + data.getFlowid() + ", state:1", e);
        }
        //  }
        ofsTodoDataManager.saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + data.getId(), OfsLog_OperType, operresult, returnMessage, data);

        return operresult;
    }

    private boolean isNeedUpdate(Map<String, String> cache, OfsTodoData data) {

        boolean flag = false;
        String receivetscache = "0";
       /* if(cache != null){
            receivetscache = cache.get("receivets");
            if("0".equals(data.getId()) && "0".equals(data.getFlowguid())){
                receivetscache = "0";
            }

        }else{*/
        OfsTodoData one = ofsTodoDataService.getOneNew(data.getSyscode(), data.getFlowid(), data.getUserid());
        if (!Objects.isNull(one)) {
            if (StringUtils.isNotBlank(one.getReceivets()) && Long.valueOf(receivetscache) < Long.valueOf(one.getReceivets())) {
                receivetscache = one.getReceivets();
            }
        }

        OfsTodoData oneBean = ofsDoneDataService.getOneNew(data.getSyscode(), data.getFlowid(), data.getUserid());
        if (!Objects.isNull(oneBean)) {
            if (StringUtils.isNotBlank(oneBean.getReceivets()) && Long.valueOf(receivetscache) < Long.valueOf(oneBean.getReceivets())) {
                receivetscache = oneBean.getReceivets();
            }
        }

        //}

        if (Long.valueOf(receivetscache) < Long.valueOf(data.getReceivets())) {
            flag = true;
        }

        return flag;
    }

    private Map<String, Object> getURL(OfsSysInfo ofsSysInfoCache, OfsTodoData data) {

        String OfsSysInfo_pcprefixurl = ofsSysInfoCache.getPcprefixurl();//PC地址前缀
        String OfsSysInfo_appprefixurl = ofsSysInfoCache.getAppprefixurl();//APP地址前缀

//        OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//        ofsSettingCacheNew.next();

        String pcurl = data.getPcurl();
        String appurl = data.getAppurl();


        //待办才发送消息提醒
        String remindPcUrl = (OfsSysInfo_pcprefixurl + "" + pcurl);
        String remindAppUrl = (OfsSysInfo_appprefixurl + "" + appurl);

        //TODO 如果有中转页面，推送给消息中心的是中转页面地址
        RecordSet rsrtx = new RecordSet();
        String sqlStr = "select * from SystemSet";
        rsrtx.executeSql(sqlStr);
        rsrtx.next();
        String oaaddress = rsrtx.getString("oaaddress");
        String appentranceurl = ofsSysInfoCache.getAppentranceurl();
        if (StringUtils.isNotBlank(appentranceurl)) {
            remindAppUrl = oaaddress + appurl;
        }

        String pcentranceurl = ofsSysInfoCache.getPcentranceurl();
        if (StringUtils.isNotBlank(pcentranceurl)) {
            remindPcUrl = oaaddress + pcurl;
        }

        if (pcurl.startsWith("http") || pcurl.startsWith("https")) {
            remindPcUrl = pcurl;
        }
        if (appurl.startsWith("http") || appurl.startsWith("https")) {
            remindAppUrl = appurl;
        }
        log.error("消息通知 app访问地址：" + remindAppUrl);
        log.error("消息通知 pc访问地址：" + remindPcUrl);

        Map<String, Object> map = new HashMap<>();
        map.put("linkUrl", remindPcUrl);
        map.put("linkMobileUrl", remindAppUrl);

        return map;
    }


    public OfsCustomDefinitionService ofsCustomDefinitionService = new OfsCustomDefinitionService();

    public Map<String, String> validateCustom(Map<String, String> custom, OfsTodoData data) {
        String str = "";
        List<CustomDefinition> list = ofsCustomDefinitionService.query();
        if (list.size() > 0) {
            if (custom == null) {
                custom = new HashMap<>();
            }
            for (CustomDefinition c : list) {
                if (c.getEnable() != 1) {
                    custom.remove(c.getDbname());
                }
                if (c.getEnable() == 1 && c.getRequired() == 1) {
                    String value = custom.get(c.getDbname());
                    if (StringUtils.isBlank(value)) {
                        str += "," + c.getDbname();
                    }
                }
            }
            if (StringUtils.isNotBlank(str)) {
                str = str.substring(1);
                return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "自定义字段必填项【" + str + "】数据不能为空", data);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    public OfsCustomDataService ofsCustomDataService = new OfsCustomDataService();

    /**
     * 接收异构系统流程
     */
    public Map<String, String> receiveRequestInfo(Map<String, Object> dataMap, String method) {
        isAnalysis();
        // 1 封装接口数据
        OfsTodoData data = ofsTodoDataManager.packageData(dataMap);
        String keyName = data.getSyscode() + "_" + data.getFlowid() + "_" + data.getReceiver();
        try {
            if (!OfsCacheLockUtil.getLock(keyName, 1)) {
                return ofsTodoDataManager.saveLog("0",
                        OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID,
                        OfsLog.OperType_Check,
                        OfsLog.OperResult_Failure,
                        "调用接口并发过高，1000ms内禁止syscode + flowid + receiver相同的流程调用接口 ",
                        data);
            }
            return this.receiveRequestInfo(data, method);
        } finally {
            OfsCacheLockUtil.unLock(keyName);
        }
    }


    public Map<String, String> receiveRequestInfo(OfsTodoData data, String method) {
        //   获取自定义字段的数据
        Map<String, String> custom2 = data.getCustom();
        Map<String, String> custom = new HashMap<>();
        if (custom2 != null && !custom2.isEmpty()) {
            Set<String> keySet = custom2.keySet();
            Object[] keys = keySet.toArray();
            for (Object key : keys) {
                String k = (String) key;
                String value = custom2.get(k);
                custom.put(k.toUpperCase(), value);
            }
        }
        String returnMessage = "";
        //   获取基本信息
		/*OfsSysInfoCacheNew ofsSysInfoCacheNew = ofsTodoDataManager.getOfsSysInfoCache(data);
		if(ofsSysInfoCacheNew == null){
			return saveLog(data.getSysid(),OfsLog.DataType_OtherSys + LINK_CHAR + DEFAULT_DATA_ID,OfsLog.OperType_Check,OfsLog.OperResult_Failure,"异构系统标识【"+data.getSyscode()+"】未注册", data);
		}*/
        // 2 校验数据
        Map<String, String> validate = ofsTodoDataManager.validate(data, method);
        if (validate != null && !validate.isEmpty()) {
            return validate;
        }
        // TODO 校验自定义字段
        if (this.isAuto) {
            Map<String, String> validateCustom = ofsTodoDataManager.validateCustom(custom, data);
            if (validateCustom != null && !validateCustom.isEmpty()) {
                return validateCustom;
            }
        }
//        OfsSysInfoCacheNew ofsSysInfoCacheNew = ofsTodoDataManager.getOfsSysInfoCache(data);
        OfsSysInfoCacheDAO ofsSysInfoCacheDAO = new OfsSysInfoCacheDAO();
        OfsSysInfo ofsSysInfoCache = ofsSysInfoCacheDAO.getOfsSysInfoCacheBySysCode(data.getSyscode());

        // 校验receiver
        Map map = ofsTodoDataManager.validateReceiver(ofsSysInfoCache, data);
        List<OfsTodoData> datas = (List<OfsTodoData>) map.get("datas");

        String noexist = (String) map.get("noexist");
        String exist = (String) map.get("exist");


        AsyncListenerBean asyncListenerBean = new AsyncListenerBean();
        asyncListenerBean.setTodoData(data);
        asyncListenerBean.setDataList(datas);
        asyncListenerBean.setCustom(custom);

        //region 判断是否发送消息到mq中
        if (InitOfsMqMonitor.isSendmessage) {
            return sendTodoDataToMq(data, method, noexist, exist, asyncListenerBean);
        }
        //endregion  判断是否发送消息到mq中


        if (Util.getIntValue(data.getRequestid(), 0) == 0) {
            log.info("是否开启雪花算法: " + isSnowflake);
            if (!isSnowflake) {
                //E9老逻辑，requestId没有使用雪花算法
                int requestId = ofsTodoDataManager.buildRequestid(data);
                data.setRequestid(Util.null2String(requestId));
            } else {
                //requestId使用雪花算法生成
                String requestId = ofsTodoDataManager.buildRequestidForSnowflake(data);
                data.setRequestid(requestId);
            }

        }

        // 保存数据
        for (OfsTodoData dataNew : datas) {
            dataNew.setRequestid(Util.null2String(data.getRequestid()));

            // 待办查待办表，做更新或者新增，同时删除已办数据（注：增加删除ofs_done_data）
            // 已办查已办表，做更新或者新增，同时删除待办数据（注意：ofs_log数据的关联需要修改——通过syscode、flowid、receiver关联数据）
            String saveResult = ofsTodoDataManager.saveData(ofsSysInfoCache, dataNew);
            // 保存自定义字段数据
            if (this.isAuto) {
                if (custom != null && !custom.isEmpty()) {
                    // TODO 将原来的数据dataid查出来，修改成新的dataid
                    ofsTodoDataManager.saveOfsCustom(dataNew, custom);
                }
            }
            if ("0".equals(saveResult)) {
                if (StringUtils.isBlank(noexist)) {
                    noexist = dataNew.getReceiver();
                } else {
                    noexist = noexist + "," + dataNew.getReceiver();
                }
            }
            if ("-2".equals(saveResult)) {
                if (exist.contains(",")) {

                    exist = exist.replace(dataNew.getReceiver() + ",", "");
                } else {
                    exist = exist.replace(dataNew.getReceiver(), "");

                }
                returnMessage += "，" + SystemEnv.getHtmlLabelName(10003831, weaver.general.ThreadVarLanguage.getLang()) + "" + data.getRequestname() + "】"
                        + SystemEnv.getHtmlLabelName(23084, weaver.general.ThreadVarLanguage.getLang()) + "";
            }
        }

        if (returnMessage.length() > 1) {
            returnMessage = returnMessage.substring(1);
        }
        String OfsLog_OperType = OfsLog.OperType_Check;
        String operresult = OfsLog.OperResult_Success;
        String isremarkName = ofsTodoDataManager.buildIsRemarkName2(data, method);
        // 有不存在的数据，返回提示失败的数据
        if (StringUtils.isNotBlank(noexist) && StringUtils.isNotBlank(exist)) {
            returnMessage += "" + SystemEnv.getHtmlLabelName(10003854, weaver.general.ThreadVarLanguage.getLang()) + "" + data.getRequestname() + "】" + SystemEnv.getHtmlLabelName(10003855, weaver.general.ThreadVarLanguage.getLang()) + "" + noexist + "】——" + SystemEnv.getHtmlLabelName(10003856, weaver.general.ThreadVarLanguage.getLang()) + "" + ";【" + exist + "】——" + SystemEnv.getHtmlLabelName(10003857, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
            OfsLog_OperType = OfsLog.OperType_Check;
            operresult = OfsLog.OperResult_Failure;
        } else if (StringUtils.isNotBlank(noexist) && StringUtils.isBlank(exist)) {
            returnMessage += "" + SystemEnv.getHtmlLabelName(10003854, weaver.general.ThreadVarLanguage.getLang()) + "" + data.getRequestname() + "】" + SystemEnv.getHtmlLabelName(10003855, weaver.general.ThreadVarLanguage.getLang()) + "" + noexist + "】——" + SystemEnv.getHtmlLabelName(10003858, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(563, weaver.general.ThreadVarLanguage.getLang()) + "";
            OfsLog_OperType = OfsLog.OperType_Check;
            operresult = OfsLog.OperResult_Failure;
        } else if (StringUtils.isBlank(noexist) && StringUtils.isBlank(exist)) {

        } else {
            returnMessage += "" + SystemEnv.getHtmlLabelName(10003854, weaver.general.ThreadVarLanguage.getLang()) + "" + data.getRequestname() + "】，" + "【" + exist + "】——" + SystemEnv.getHtmlLabelName(10003857, weaver.general.ThreadVarLanguage.getLang()) + "" + isremarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
        }
		/*if(OfsLog.OperResult_Failure.equals(operresult)){
			saveLog(data.getSysid(),OfsLog.DataType_WfData+ LINK_CHAR + DEFAULT_DATA_ID,OfsLog_OperType,operresult,returnMessage,data);
		}*/
        return ofsTodoDataManager.buildReceiveTodoRequest(
                data.getSyscode(),
                OfsLog.DataType_WfData,
                OfsLog_OperType,
                operresult,
                returnMessage
        );
    }

    private Map<String, String> sendTodoDataToMq(OfsTodoData data, String method, String noexist, String exist, AsyncListenerBean asyncListenerBean) {
        String returnMessage = "";
        String ofsLogOperType = OfsLog.OperType_Check;
        String operResult = OfsLog.OperResult_Success;

        String isRemarkName = ofsTodoDataManager.buildIsRemarkName2(data, method);
        if (StringUtils.isNotBlank(noexist) && StringUtils.isBlank(exist)) {
            returnMessage += "" + SystemEnv.getHtmlLabelName(10003854, weaver.general.ThreadVarLanguage.getLang()) + "" + data.getRequestname() + "】" + SystemEnv.getHtmlLabelName(10003855, weaver.general.ThreadVarLanguage.getLang()) + "" + noexist + "】——" + SystemEnv.getHtmlLabelName(10003858, weaver.general.ThreadVarLanguage.getLang()) + "" + isRemarkName + "" + SystemEnv.getHtmlLabelName(563, weaver.general.ThreadVarLanguage.getLang()) + "";
            ofsLogOperType = OfsLog.OperType_Check;
            operResult = OfsLog.OperResult_Failure;
            return ofsTodoDataManager.buildReceiveTodoRequest(
                    data.getSyscode(),
                    OfsLog.DataType_WfData,
                    ofsLogOperType,
                    operResult,
                    returnMessage
            );
        }

        // 将同一条流程发送到同一个队列中
        int shardingKey = QueueSelector.getShardingKey(data.getSyscode() + data.getFlowid(), queueCount);
        String routingkey = queuePrefix + "_" + shardingKey;
        log.info("使用的队列为：" + routingkey);

        boolean sendMessageFlag = ofsMqSendMessage.sendMessage(JSON.toJSONString(asyncListenerBean), routingkey);
        if (!sendMessageFlag) {
            return ofsTodoDataManager.buildReceiveTodoRequest(
                    data.getSyscode(),
                    OfsLog.DataType_WfData,
                    ofsLogOperType,
                    OfsLog.OperResult_Failure,
                    "流程数据发送到mq中失败！！"
            );
        }
        // 有不存在的数据，返回提示失败的数据
        if (StringUtils.isNotBlank(noexist) && StringUtils.isNotBlank(exist)) {
            returnMessage += "" + SystemEnv.getHtmlLabelName(10003854, weaver.general.ThreadVarLanguage.getLang()) + "" + data.getRequestname() + "】" + SystemEnv.getHtmlLabelName(10003855, weaver.general.ThreadVarLanguage.getLang()) + "" + noexist + "】——" + SystemEnv.getHtmlLabelName(10003856, weaver.general.ThreadVarLanguage.getLang()) + "" + ";【" + exist + "】——" + SystemEnv.getHtmlLabelName(10003857, weaver.general.ThreadVarLanguage.getLang()) + "" + isRemarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
            ofsLogOperType = OfsLog.OperType_Check;
            operResult = OfsLog.OperResult_Failure;
        } else if (StringUtils.isBlank(noexist) && StringUtils.isBlank(exist)) {

        } else {
            returnMessage += "" + SystemEnv.getHtmlLabelName(10003854, weaver.general.ThreadVarLanguage.getLang()) + "" + data.getRequestname() + "】，" + "【" + exist + "】——" + SystemEnv.getHtmlLabelName(10003857, weaver.general.ThreadVarLanguage.getLang()) + "" + isRemarkName + "" + SystemEnv.getHtmlLabelName(25008, weaver.general.ThreadVarLanguage.getLang()) + "";
        }
        returnMessage += "; 流程数据已发送到mq中。";
        return ofsTodoDataManager.buildReceiveTodoRequest(
                data.getSyscode(),
                OfsLog.DataType_WfData,
                ofsLogOperType,
                operResult,
                returnMessage
        );
    }


    public void saveDataByMq(List<OfsTodoData> datas, OfsTodoData data, Map<String, String> custom) {
        ofsTodoDataManager = this;
        OfsSysInfoCacheDAO ofsSysInfoCacheDAO = new OfsSysInfoCacheDAO();
        OfsSysInfo ofsSysInfoCache = ofsSysInfoCacheDAO.getOfsSysInfoCacheBySysCode(data.getSyscode());

        if (Util.getIntValue(data.getRequestid(), 0) == 0) {
            log.info("是否开启雪花算法: " + isSnowflake);
            if (!isSnowflake) {
                //E9老逻辑，requestId没有使用雪花算法
                int requestId = ofsTodoDataManager.buildRequestid(data);
                data.setRequestid(Util.null2String(requestId));
            } else {
                //requestId使用雪花算法生成
                String requestId = ofsTodoDataManager.buildRequestidForSnowflake(data);
                data.setRequestid(requestId);
            }
        }

        // 保存数据
        for (OfsTodoData dataNew : datas) {
            dataNew.setRequestid(Util.null2String(data.getRequestid()));

            // 待办查待办表，做更新或者新增，同时删除已办数据（注：增加删除ofs_done_data）
            // 已办查已办表，做更新或者新增，同时删除待办数据（注意：ofs_log数据的关联需要修改——通过syscode、flowid、receiver关联数据）
            String saveResult = this.saveData(ofsSysInfoCache, dataNew);
            // 保存自定义字段数据
            if (this.isAuto) {
                if (custom != null && !custom.isEmpty()) {
                    // TODO 将原来的数据dataid查出来，修改成新的dataid
                    this.saveOfsCustom(dataNew, custom);
                }
            }
        }
        log.error("流程数据保存成功！！");
    }


    public void saveOfsCustom(OfsTodoData dataNew, Map<String, String> custom) {
        boolean save = ofsCustomDataService.save(dataNew, custom);
		/*if(!save){
			throw new RuntimeException("保存自定义字段异常");
		}*/
    }

    /**
     * 删除异构系统流程
     */
    public Map<String, String> deleteRequestInfo(
            String syscode,
            String flowid
    ) {

        isAnalysis();

        OfsTodoData data = new OfsTodoData();
        data.setSyscode(syscode);
        data.setFlowid(flowid);

//        OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//        ofsSettingCacheNew.next();
//        String OfsSetting_isuse = ofsSettingCacheNew.getId();

        OfsSettingCacheDAO ofsSettingCacheDAO = new OfsSettingCacheDAO();
        OfsSetting ofsSettingCache = ofsSettingCacheDAO.getOfsSettingCache();
        String OfsSetting_isuse = ofsSettingCache.getIsuse();
        if (!OfsSetting.IsUse_Yes.equals(OfsSetting_isuse)) {//关闭统一待办中心状态

            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_IsUse,
                    OfsLog.OperType_Check,
                    OfsLog.OperResult_Failure,
                    "统一待办中心未启用"
            );
        }


        String msg = "";
        String result = OfsLog.OperResult_Failure;

        if (syscode == null || "".equals(syscode)) {
            msg = "" + SystemEnv.getHtmlLabelName(10003846, weaver.general.ThreadVarLanguage.getLang()) + ",syscode" + SystemEnv.getHtmlLabelName(385284, weaver.general.ThreadVarLanguage.getLang()) + "";
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_WfData,
                    OfsLog.OperType_Del,
                    result,
                    msg
            );
        }

//        OfsSysInfoCacheNew ofsSysInfoCacheNew = ofsTodoDataManager.getOfsSysInfoCache(data);
        OfsSysInfoCacheDAO ofsSysInfoCacheDAO = new OfsSysInfoCacheDAO();
        OfsSysInfo ofsSysInfoCache = ofsSysInfoCacheDAO.getOfsSysInfoCacheBySysCode(data.getSyscode());

        if (ofsSysInfoCache == null) {

            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_OtherSys,
                    OfsLog.OperType_Del,
                    result,
                    "异构系统标识【" + data.getSyscode() + "】未注册"
            );
        }

        //异构许可ip
        String OfsSysInfo_securityip = ofsSysInfoCache.getSecurityip();
//		Map<String,String> OfsSysInfoMap = ofsSysInfoService.getOneMap(syscode);
//        String OfsSysInfo_securityip = OfsUtils.getStringValueByMapKey(OfsSysInfoMap,"securityip");
        if (this.isCheckIP && !checkIp(OfsSysInfo_securityip, this.clientIp)) {
            //检测当前IP是否在许可IP范围内
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_OtherSys,
                    OfsLog.OperType_Check,
                    OfsLog.OperResult_Failure,
                    "异构系统标识【" + syscode + "】当前IP（" + this.clientIp + "）未授权"
            );
        }


        if (flowid == null || "".equals(flowid)) {
            msg = "" + SystemEnv.getHtmlLabelName(10003846, weaver.general.ThreadVarLanguage.getLang()) + ",flowid" + SystemEnv.getHtmlLabelName(385284, weaver.general.ThreadVarLanguage.getLang()) + "";
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_WfData,
                    OfsLog.OperType_Del,
                    result,
                    msg
            );
        }
		/*int tododataCnt = ofsTodoDataService.getTodoDataCnt(syscode,flowid);
		if(tododataCnt==0){
			msg = ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003846,weaver.general.ThreadVarLanguage.getLang())+","+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003847,weaver.general.ThreadVarLanguage.getLang())+"";

		}else{*/
        //TODO 删除消息
        Set<String> userids = new HashSet<String>();
        RecordSet rs1 = new RecordSet();
        rs1.executeQuery("select * from ofs_todo_data where syscode = ? and flowid = ?", syscode, flowid);
        while (rs1.next()) {
            String rs1String = rs1.getString("userid");
            if (StringUtils.isNotBlank(rs1String)) {
                userids.add(rs1String);
                String receiver = rs1.getString("receiver");
                Util_DataCache.clearVal(syscode + "_" + flowid + "_" + receiver);
            }
        }

        rs1.executeQuery("select * from ofs_done_data where syscode = ? and flowid = ?", syscode, flowid);
        while (rs1.next()) {
            String rs1String = rs1.getString("userid");
            if (StringUtils.isNotBlank(rs1String)) {
                userids.add(rs1String);
                String receiver = rs1.getString("receiver");
                Util_DataCache.clearVal(syscode + "_" + flowid + "_" + receiver);
            }
        }

        log.error("userids:" + userids);
        log.error("userids.size():" + userids.size());
        if (userids.size() > 0) {

            try {
                MessageBean messageBean = Util_Message.createMessage();
                messageBean.setUserList(userids);//接收人id
                messageBean.setTargetId(syscode + "_" + flowid);
                Util_Message.delMessageTargetid(messageBean);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除消息异常", e);
            }
        }


        ofsTodoDataService.receiveRequestInfoDelete(syscode, flowid);
        result = OfsLog.OperResult_Success;
        msg = "" + SystemEnv.getHtmlLabelName(10003848, weaver.general.ThreadVarLanguage.getLang()) + "";


        ofsDoneDataService.delete(syscode, flowid);

        ofsCustomDataService.delete(syscode, flowid);

        //}


	/*	// TODO 删除数据记录日志
		if(result.equals("1")){
			saveLog(data.getSysid(),OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID,OfsLog.OperType_Del,OfsLog.OperResult_Success,msg, data);
		}else{
			saveLog(data.getSysid(),OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID,OfsLog.OperType_Del,OfsLog.OperResult_Failure,msg, data);
		}*/
        return buildReceiveTodoRequest(
                syscode,
                OfsLog.DataType_WfData,
                OfsLog.OperType_Del,
                result,
                msg
        );

    }

    /**
     * 删除某个用户异构系统流程
     */
    public Map<String, String> deleteUserRequestInfo(
            String syscode,
            String flowid,
            String userid
    ) {
        isAnalysis();
        OfsTodoData data = new OfsTodoData();
        data.setSyscode(syscode);
        data.setFlowid(flowid);
        data.setReceiver(userid);

//        OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//        ofsSettingCacheNew.next();
//        String OfsSetting_isuse = ofsSettingCacheNew.getId();
        OfsSettingCacheDAO ofsSettingCacheDAO = new OfsSettingCacheDAO();
        OfsSetting ofsSettingCache = ofsSettingCacheDAO.getOfsSettingCache();
        String OfsSetting_isuse = ofsSettingCache.getIsuse();
        if (!OfsSetting.IsUse_Yes.equals(OfsSetting_isuse)) {//关闭统一待办中心状态

            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_IsUse,
                    OfsLog.OperType_Check,
                    OfsLog.OperResult_Failure,
                    "统一待办中心未启用"
            );
        }


        String msg = "";
        String result = OfsLog.OperResult_Failure;
        if (StringUtils.isBlank(syscode)) {
            msg = "" + SystemEnv.getHtmlLabelName(10003846, weaver.general.ThreadVarLanguage.getLang()) + ",syscode" + SystemEnv.getHtmlLabelName(385284, weaver.general.ThreadVarLanguage.getLang()) + "";
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_WfData,
                    OfsLog.OperType_Del,
                    result,
                    msg
            );
        }
//        OfsSysInfoCacheNew ofsSysInfoCacheNew = ofsTodoDataManager.getOfsSysInfoCache(data);
        OfsSysInfoCacheDAO ofsSysInfoCacheDAO = new OfsSysInfoCacheDAO();
        OfsSysInfo ofsSysInfoCache = ofsSysInfoCacheDAO.getOfsSysInfoCacheBySysCode(data.getSyscode());

        if (ofsSysInfoCache == null) {

            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_OtherSys,
                    OfsLog.OperType_Del,
                    result,
                    "异构系统标识【" + data.getSyscode() + "】未注册"
            );
        }

        //异构许可ip
        String OfsSysInfo_securityip = ofsSysInfoCache.getSecurityip();
//		Map<String,String> OfsSysInfoMap = ofsSysInfoService.getOneMap(syscode);
//        String OfsSysInfo_securityip = OfsUtils.getStringValueByMapKey(OfsSysInfoMap,"securityip");
        if (this.isCheckIP && !checkIp(OfsSysInfo_securityip, this.clientIp)) {
            //检测当前IP是否在许可IP范围内
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_OtherSys,
                    OfsLog.OperType_Check,
                    OfsLog.OperResult_Failure,
                    "异构系统标识【" + syscode + "】当前IP（" + this.clientIp + "）未授权"
            );
        }
        if (StringUtils.isBlank(flowid)) {
            msg = "" + SystemEnv.getHtmlLabelName(10003846, weaver.general.ThreadVarLanguage.getLang()) + ",flowid" + SystemEnv.getHtmlLabelName(385284, weaver.general.ThreadVarLanguage.getLang()) + "";
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_WfData,
                    OfsLog.OperType_Del,
                    result,
                    msg
            );
        }
        if (StringUtils.isBlank(userid)) {
            msg = "" + SystemEnv.getHtmlLabelName(10003846, weaver.general.ThreadVarLanguage.getLang()) + ",userid" + SystemEnv.getHtmlLabelName(385284, weaver.general.ThreadVarLanguage.getLang()) + "";
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_WfData,
                    OfsLog.OperType_Del,
                    result,
                    msg
            );
        }
		/*int tododataCnt = ofsTodoDataService.getTodoDataCnt(syscode,flowid,userid);
		if(tododataCnt==0){
			msg = ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003846,weaver.general.ThreadVarLanguage.getLang())+","+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003847,weaver.general.ThreadVarLanguage.getLang())+"";

		}else{*/
        //TODO 删除消息
        String useridReal = ofsSysInfoService.getHrmResourceIdByHrmTransRule(ofsSysInfoCache.getHrmtransrule(), userid);
        Set<String> userids = new HashSet<String>();
        if (StringUtils.isNotBlank(useridReal)) {
            userids.add(useridReal);
        } else {
            msg = "" + SystemEnv.getHtmlLabelName(10003846, weaver.general.ThreadVarLanguage.getLang()) + ",检测接收人【 " + userid + "】不存在";
            return buildReceiveTodoRequest(
                    syscode,
                    OfsLog.DataType_WfData,
                    OfsLog.OperType_Del,
                    result,
                    msg
            );
        }

//        data = ofsTodoDataService.getOne(syscode, flowid, userid);
//        Set<String> userids = new HashSet<String>();
//        if(data != null){
//            String dataUserid = data.getUserid();
//            if(StringUtils.isNotBlank(dataUserid)){
//                userids.add(dataUserid);
//            }
//        }
        // TODO 删除自定义字段数据
        ofsCustomDataService.delete(syscode, flowid, userid);
        log.info("userids:" + userids);
        log.info("userids.size():" + userids.size());
        if (userids.size() > 0) {

            try {
                MessageBean messageBean = Util_Message.createMessage();
                messageBean.setUserList(userids);//接收人id
                messageBean.setTargetId(syscode + "_" + flowid);
                Util_Message.delMessageTargetid(messageBean);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除消息异常", e);
            }
        }


        ofsTodoDataService.receiveRequestInfoUserDelete(syscode, flowid, useridReal);
        result = OfsLog.OperResult_Success;
        msg = "" + SystemEnv.getHtmlLabelName(10003848, weaver.general.ThreadVarLanguage.getLang()) + "";

        ofsDoneDataService.delete(syscode, flowid, useridReal);
        //}
        Util_DataCache.clearVal(syscode + "_" + flowid + "_" + useridReal);
        // TODO 删除数据记录日志
		/*if(result.equals("1")){
			saveLog(data.getSysid(),OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID,OfsLog.OperType_Del,OfsLog.OperResult_Success,msg, data);
		}else{
			saveLog(data.getSysid(),OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID,OfsLog.OperType_Del,OfsLog.OperResult_Failure,msg, data);
		}*/
        return buildReceiveTodoRequest(
                syscode,
                OfsLog.DataType_WfData,
                OfsLog.OperType_Del,
                result,
                msg
        );

    }

    /**
     * 处理待办流程(变为已办map格式)
     */
    public Map<String, String> processDoneRequestByMap(Map<String, Object> dataMap) {


        // 业务数据
        dataMap.put("isremark", OfsTodoData.IsRemark_Done);
        dataMap.put("viewtype", OfsTodoData.ViewType_Over);
        //TODO 如果已经解析完成不用再次解析
        Object custom = dataMap.get("custom");
        if (custom instanceof Map) {

        } else {
            String str = (String) dataMap.get("custom");
            Map<String, Object> map = xmlToMap(str);
            dataMap.put("custom", map);
        }
        return this.receiveRequestInfo(dataMap, "done");
    }

    /**
     * 处理待办流程（变为已办json格式）
     */
    public String processDoneRequestByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.processDoneRequestByMap(dataMap);
        return OfsUtils.mapToJson(resultMap);
    }

    /**
     * 处理待办流程（变为已办xml格式）
     */
    public String processDoneRequestByXml(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.processDoneRequestByMap(dataMap);
        return OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);
    }


    /**
     * 处理已办流程(变为办结map格式)
     */
    public Map<String, String> processOverRequestByMap(Map<String, Object> dataMap) {

        // 业务数据
        dataMap.put("isremark", OfsTodoData.IsRemark_Over);
        dataMap.put("viewtype", OfsTodoData.ViewType_Over);
        //TODO 如果已经解析完成不用再次解析
        Object custom = dataMap.get("custom");
        if (custom instanceof Map) {

        } else {
            String str = (String) dataMap.get("custom");
            Map<String, Object> map = xmlToMap(str);
            dataMap.put("custom", map);
        }
        return this.receiveRequestInfo(dataMap, "over");
    }

    /**
     * 处理办结流程（变为办结json格式）
     */
    public String processOverRequestByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.processOverRequestByMap(dataMap);
        return OfsUtils.mapToJson(resultMap);
    }

    /**
     * 处理办结流程(变为办结xml格式)
     */
    public String processOverRequestByXml(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.processOverRequestByMap(dataMap);
        return OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);
    }

    /**
     * ip检测
     * securityip为空，表示任何地址者可以访问；
     * securityip不为空，则检查clientIp是否在securityip中指定了；
     *
     * @param securityip 指定的ip范围
     *                   当前访问ip
     *                   是否在ip范围内
     */
    public boolean checkIp(String securityip, String clientIp) {
        //return ("," + securityip + ",").indexOf("," + clientIp + ",") > -1;
        log.info("securityip:" + securityip);
        log.info("clientIp:" + clientIp);
        String[] validIPs = securityip.split(",");
        Boolean checkIp = CheckIP.checkIPs(validIPs, clientIp);
        log.info("checkIp:" + checkIp);
        return checkIp;
    }

    public String getEntranceUrl(String entranceurl, String OfsTodoData_id) {

        String url = "";
        String param = "tododataid=" + OfsTodoData_id;

        if (!"".equals(entranceurl)) {
            if (entranceurl.contains("?")) {
                url = entranceurl + "&" + param;
            } else {
                url = entranceurl + "?" + param;
            }
        }
        return url;
    }

    private BatchReceiveRequestBean addOfsTodoDataList(BatchReceiveRequestBean bean, Map<String, Object> dataMap) {
        OfsTodoData ofsTodoData = ofsTodoDataManager.packageData(dataMap);
        bean.getOfsTodoDataList().add(ofsTodoData);
        // 如果没有requestId
		/*if (bean.getRequestId() == 0){
			//校验数据完整生成 requestId
			Map<String, String> validate = ofsTodoDataManager.validate(ofsTodoData,"info");
			if (validate == null){
				bean.setRequestId(ofsTodoDataManager.buildRequestid(ofsTodoData));
			}
		}*/
        return bean;
    }

    private BatchReceiveRequestBean getBatchReceiveRequestBean(Map<String, Object> dataMap) {

        BatchReceiveRequestBean bean = new BatchReceiveRequestBean();
        List<OfsTodoData> list = new ArrayList<>();
        OfsTodoData ofsTodoData = ofsTodoDataManager.packageData(dataMap);
        list.add(ofsTodoData);
        bean.setOfsTodoDataList(list);
        //校验数据完整生成 requestId
		/*Map<String, String> validate = ofsTodoDataManager.validate(ofsTodoData,"info");
		if (validate == null){
			bean.setRequestId(ofsTodoDataManager.buildRequestid(ofsTodoData));
		}*/
        return bean;
    }

    /**
     * 根据syscode和flowid区分出不同的json_arr批量处理数据
     * #599419
     * 概述：优化了【统一待办中心集成】批量提交接口的功能
     */
    public String batchReceiveRequestInfoByJson(String json) {
        isAnalysis();
        Map<String, BatchReceiveRequestBean> requestMap = new HashMap<String, BatchReceiveRequestBean>();
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        JSONArray arr = JSONArray.fromObject(json);
        if (arr != null) {
            for (int i = 0; i < arr.size(); i++) {
                Map<String, Object> dataMap = jsonToMap(arr.getJSONObject(i).toString());
				/*String syscode = Util.null2String((String)dataMap.get("syscode"));
				String flowId = Util.null2String((String)dataMap.get("flowid"));

				StringBuffer mapKey = new StringBuffer() ;
				mapKey.append(syscode).append("_").append(flowId) ;
				BatchReceiveRequestBean batchReceiveRequestBean = requestMap.get(mapKey.toString()) ;
				if (batchReceiveRequestBean != null && batchReceiveRequestBean.validate() ){
					this.addOfsTodoDataList(batchReceiveRequestBean , dataMap) ;
				}else {
					requestMap.put(mapKey.toString() , this.getBatchReceiveRequestBean(dataMap)) ;
				}*/
				/*Map<String,Object> dataMap = jsonToMap(arr.getJSONObject(i).toString());
				Map<String, String> result = this.receiveRequestInfo(dataMap,"info");//获取要存储数据库的数据
				list.add(result);
				String syscode = Util.null2String((String)dataMap.get("syscode"));
				String flowid = Util.null2String((String)dataMap.get("flowid"));
				String isremark = Util.null2String((String)dataMap.get("isremark"));
				ofsTodoDataManager.batchProcessOverRequstComplet(syscode, flowid, isremark);//批量处理办结情况*/

                Map<String, String> result = this.receiveRequestInfo(dataMap, "info");//获取要存储数据库的数据
                list.add(result);
            }
        }
		/*for (String key : requestMap.keySet()){
			BatchReceiveRequestBean bean = requestMap.get(key) ;
			if (bean != null){
				for (int i = 0 ; i< bean.getOfsTodoDataList().size() ; i++){
					Map<String, String> result = this.receiveRequestInfo(bean.getOfsTodoData(i),"info");//获取要存储数据库的数据
					list.add(result);
				}
			}
		}*/

        return JSON.toJSONString(list);
    }


    public void batchProcessOverRequstComplet(String syscode, String flowid, String isremark) {
        //将所有已办且iscomplete=0变更为iscomplete=1；不处理待办情况
        if (isremark.equals(OfsTodoData.IsRemark_Done)) {//已办的处理
            ofsTodoDataService.processOverRequestComplete(syscode, flowid);
        } else if (isremark.equals(OfsTodoData.IsRemark_Over)) {//办结的处理
            ofsTodoDataService.processOverRequestComplete(syscode, flowid);
        }
    }

    /**
     * 批量删除流程
     */
    public String batchDeleteUserRequestInfoByJson(String json) {

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        JSONArray json_arr = JSONArray.fromObject(json);
        if (json_arr != null) {
            for (int i = 0; i < json_arr.size(); i++) {
                Map<String, Object> dataMap = jsonToMap(json_arr.getJSONObject(i).toString());
                //批量删除，返回每一个删除结果
                Map<String, String> map = this.deleteUserRequestInfoByMap(dataMap);
                list.add(map);
            }
        }
        return JSON.toJSONString(list);
    }


    //TODO 抄送

    /**
     * 接收抄送流程(json格式)
     */
    public String receiveCCRequestByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.receiveCCRequestByMap(dataMap);
        String resultJson = OfsUtils.mapToJson(resultMap);

        return resultJson;
    }

    /**
     * 接收抄送流程(xml格式)
     */
    public String receiveCCRequestByXml(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.receiveCCRequestByMap(dataMap);

        String toXml = OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);

        return toXml;

    }

    /**
     * 接收抄送流程
     */
    public Map<String, String> receiveCCRequestByMap(Map<String, Object> dataMap) {

        // 业务数据
        dataMap.put("isremark", "8");
        dataMap.put("viewtype", OfsTodoData.ViewType_None);
        //TODO 如果已经解析完成不用再次解析
        Object custom = dataMap.get("custom");
        if (custom instanceof Map) {

        } else {
            String str = (String) dataMap.get("custom");
            Map<String, Object> map = xmlToMap(str);
            dataMap.put("custom", map);
        }
        return this.receiveRequestInfo(dataMap, "cc");
    }


    //TODO 已读

    /**
     * 接收抄送流程(json格式)
     */
    public String receiveReadRequestByJson(String json) {

        Map<String, Object> dataMap = this.jsonToMap(json);
        Map<String, String> resultMap = this.receiveReadRequestByMap(dataMap);
        String resultJson = OfsUtils.mapToJson(resultMap);

        return resultJson;
    }

    /**
     * 接收抄送流程(xml格式)
     */
    public String receiveReadRequestByXml(String xml) {

        Map<String, Object> dataMap = this.xmlToMap(xml);
        Map<String, String> resultMap = this.receiveReadRequestByMap(dataMap);

        String toXml = OfsUtils.mapToXml(resultMap, RESULT_XML_ROOT);

        return toXml;

    }

    /**
     * 接收抄送流程
     */
    public Map<String, String> receiveReadRequestByMap(Map<String, Object> dataMap) {

        // 业务数据
        String isremark = Util.null2String((String) dataMap.get("isremark"));
		/*if(StringUtils.isBlank(isremark)){
			dataMap.put("isremark","8");
		}*/
        dataMap.put("viewtype", "1");
        //TODO 如果已经解析完成不用再次解析
        Object custom = dataMap.get("custom");
        if (custom instanceof Map) {

        } else {
            String str = (String) dataMap.get("custom");
            Map<String, Object> map = xmlToMap(str);
            dataMap.put("custom", map);
        }
        return this.receiveRequestInfo(dataMap, "read");
    }

    public OfsTodoData packageData(Map<String, Object> dataMap) {
        String syscode = Util.null2String((String) dataMap.get("syscode"));
        String flowid = Util.null2String((String) dataMap.get("flowid"));
        String requestname = Util.null2String((String) dataMap.get("requestname"));
        String workflowname = Util.null2String((String) dataMap.get("workflowname"));
        String nodename = Util.null2String((String) dataMap.get("nodename"));
        String pcurl = Util.null2String((String) dataMap.get("pcurl"));
        String appurl = Util.null2String((String) dataMap.get("appurl"));
        String isremark = Util.null2String((String) dataMap.get("isremark"));
        String viewtype = Util.null2String((String) dataMap.get("viewtype"));
        String createdatetime = Util.null2String((String) dataMap.get("createdatetime"));
        String creator = Util.null2String((String) dataMap.get("creator"));
        String receiver = Util.null2String((String) dataMap.get("receiver"));
        String receivedatetime = Util.null2String((String) dataMap.get("receivedatetime"));
        String receivets = Util.null2String((String) dataMap.get("receivets"));
        String requestlevel = Util.null2String((String) dataMap.get("requestlevel"));
        //String isauto = Util.null2String((String)dataMap.get("isauto"));
        if (StringUtils.isBlank(receivets)) {
            receivets = String.valueOf(System.currentTimeMillis());
        }
        String createtime = "";
        String receivetime = "";
        String createdate = "";
        String receivedate = "";
        if (StringUtils.isNotBlank(createdatetime) && createdatetime.length() == 19) {
            createdate = createdatetime.substring(0, 10);
            createtime = createdatetime.length() > 11 ? createdatetime.substring(11) : createtime;
        } else {
            createdate = createdatetime;
        }

        if (StringUtils.isNotBlank(receivedatetime) && receivedatetime.length() == 19) {
            receivedate = receivedatetime.substring(0, 10);
            receivetime = receivedatetime.length() > 11 ? receivedatetime.substring(11) : receivetime;
        } else {
            receivedate = receivedatetime;
        }

		/*if(StringUtils.isBlank(requestname)){
			requestname = ofsRequestBaseService.getRequestname(syscode,flowid);
		}*/

        //   获取自定义字段的数据
        Map<String, String> custom = (Map<String, String>) dataMap.get("custom");

        OfsTodoData data = new OfsTodoData();
        data.setSyscode(syscode);
        data.setFlowid(flowid);
        data.setRequestname(requestname);
        data.setWorkflowname(workflowname);
        data.setNodename(nodename);
        data.setPcurl(pcurl);
        data.setAppurl(appurl);
        data.setIsremark(isremark);
        data.setViewtype(viewtype);
        data.setCreator(creator);
        data.setReceiver(receiver);
        data.setCreatedate(createdate);
        data.setCreatetime(createtime);
        data.setReceivedate(receivedate);
        data.setReceivetime(receivetime);
        data.setReceivets(receivets);
        data.setRequestlevel(requestlevel);
        //data.setIsauto(isauto);
        data.setCustom(custom);
        return data;
    }

    // TODO receiver 接收多个人，返回那些人不存在
    public Map validateReceiver(OfsSysInfo ofsSysInfoCache, OfsTodoData data) {
        List<OfsTodoData> list = new ArrayList<>();
        String requestname = data.getRequestname();
        String receiver = data.getReceiver();
        String[] split = receiver.split(",");
        //人员转换规则
        String OfsSysInfo_HrmTransRule = ofsSysInfoCache.getHrmtransrule();

        // 存在的接收人
        String exist = "";
        // 不存在的接收人
        String noexist = "";

        for (String rece : split) {

            String userid = ofsSysInfoService.getHrmResourceIdByHrmTransRule(OfsSysInfo_HrmTransRule, rece);

            if (Util.null2String(userid).equals("0") || StringUtils.isEmpty(userid)) {
                //保存失败，记录系统日志：流程数据-检测-失败-流程数据【"+requestname+"】检测接收人不存在
                noexist += "," + rece;
                data.setReceiver(rece);
                data.setUserid("0");
                ofsTodoDataManager.saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + data.getId(), OfsLog.OperType_Check, OfsLog.OperResult_Failure, "流程数据【" + requestname + "】检测接收人【" + rece + "】不存在", data);
            } else {
                exist += "," + rece;
                // 克隆一个对象，修改接收人userid和receiver
                OfsTodoData obj = JSON.parseObject(JSON.toJSONString(data), OfsTodoData.class);

                obj.setUserid(userid);
                obj.setReceiver(rece);
                list.add(obj);
            }
        }
        if (exist.length() > 0) {

            exist = exist.substring(1);
        }
        if (noexist.length() > 0) {

            noexist = noexist.substring(1);
        }

        Map map = new HashMap();
        map.put("datas", list);
        map.put("exist", exist);
        map.put("noexist", noexist);
        return map;
    }

    @Override
    public Map<String, String> validate(OfsSysInfoCacheNew ofsSysInfoCacheNew, OfsTodoData data, String method) {
        return null;
    }

    public Map<String, String> validate(OfsTodoData data, String method) {
        String receivets = data.getReceivets();
        String receiver = data.getReceiver();
        String requestname = data.getRequestname();
        String creator = data.getCreator();
        String syscode = data.getSyscode();
        String flowid = data.getFlowid();
        String isremark = data.getIsremark();
        String viewtype = data.getViewtype();
        String workflowname = data.getWorkflowname();
        String requestlevel = data.getRequestlevel();


//        OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//        ofsSettingCacheNew.next();
//        String OfsSetting_isuse = ofsSettingCacheNew.getId();
        OfsSettingCacheDAO ofsSettingCacheDAO = new OfsSettingCacheDAO();
        OfsSetting ofsSettingCache = ofsSettingCacheDAO.getOfsSettingCache();
        String OfsSetting_isuse = ofsSettingCache.getIsuse();
        if (!OfsSetting.IsUse_Yes.equals(OfsSetting_isuse)) {//关闭统一待办中心状态
            Map<String, String> OfsSettingMap = ofsSettingService.getOneMap();
            OfsSetting_isuse = OfsUtils.getStringValueByMapKey(OfsSettingMap, "isuse", OfsSetting.IsUse_No);//是否启用统一待办中心状态
            if (!OfsSetting.IsUse_Yes.equals(OfsSetting_isuse))
                return saveLog("0", OfsLog.DataType_IsUse + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "统一待办中心未启用", data);
        }

		/*int syscodeCnt = this.ofsSysInfoService.getCnt(syscode);//获取指定异构系统标识的数量
		if(syscodeCnt == 0){//记录系统日志：异构系统-检测-失败-异构系统标识【XXXX】未注册
			return saveLog(data.getSysid(),OfsLog.DataType_OtherSys + LINK_CHAR + DEFAULT_DATA_ID,OfsLog.OperType_Check,OfsLog.OperResult_Failure,"异构系统标识【"+syscode+"】未注册", data);
		}*/
//        OfsSysInfoCacheNew ofsSysInfoCacheNew = ofsTodoDataManager.getOfsSysInfoCache(data);
        OfsSysInfoCacheDAO ofsSysInfoCacheDAO = new OfsSysInfoCacheDAO();
        OfsSysInfo ofsSysInfoCache = ofsSysInfoCacheDAO.getOfsSysInfoCacheBySysCode(syscode);
        String OfsSysInfo_HrmTransRule;
        String OfsSysInfo_securityip;
        int OfsSysInfo_receivewfdata;
        int OfsSysInfo_autocreatewftype;
        int OfsSysInfo_sysid;
        if (ofsSysInfoCache == null) {
            int syscodeCnt = ofsSysInfoService.getCnt(syscode);//获取指定异构系统标识的数量
            if (syscodeCnt == 0) {//记录系统日志：异构系统-检测-失败-异构系统标识【XXXX】未注册
                return saveLog("0", OfsLog.DataType_OtherSys + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "异构系统标识【" + data.getSyscode() + "】未注册", data);
            } else {
                Map<String, String> OfsSysInfoMap = ofsSysInfoService.getOneMap(syscode);
                OfsSysInfo_sysid = OfsUtils.getIntValueByMapKey(OfsSysInfoMap, "sysid", OfsSysInfo.Default_SysId);//异构系统id
                data.setSysid(OfsSysInfo_sysid + "");
                OfsSysInfo_HrmTransRule = OfsUtils.getStringValueByMapKey(OfsSysInfoMap, "hrmtransrule");//人员转换规则
                OfsSysInfo_securityip = OfsUtils.getStringValueByMapKey(OfsSysInfoMap, "securityip");//异构许可ip
                OfsSysInfo_receivewfdata = OfsUtils.getIntValueByMapKey(OfsSysInfoMap, "receivewfdata", OfsSysInfo.ReceiveWfData_No);//异构系统允许接收流程数据
                OfsSysInfo_autocreatewftype = OfsUtils.getIntValueByMapKey(OfsSysInfoMap, "autocreatewftype", OfsSysInfo.AutoCreateWfType_No);//异构系统自动创建流程类型
            }

        } else {
            //异构系统id
            OfsSysInfo_sysid = Util.getIntValue(ofsSysInfoCache.getSysid(), 0);
            if (OfsSysInfo_sysid == 0) {
                OfsSysInfo_sysid = Util.getIntValue(ofsSysInfoService.getOneBean(data.getSyscode()).getSysid());
            }
            data.setSysid(OfsSysInfo_sysid + "");
            //人员转换规则
            OfsSysInfo_HrmTransRule = ofsSysInfoCache.getHrmtransrule();
            //异构许可ip
            OfsSysInfo_securityip = ofsSysInfoCache.getSecurityip();
            //异构系统允许接收流程数据
            OfsSysInfo_receivewfdata = Util.getIntValue(ofsSysInfoCache.getReceivewfdata(), OfsSysInfo.ReceiveWfData_No);
            OfsSysInfo_autocreatewftype = Util.getIntValue(ofsSysInfoCache.getAutocreatewftype(), OfsSysInfo.AutoCreateWfType_No);
        }


        //校验时间戳
        Pattern pattern = Pattern.compile("[0-9]*");
        boolean matchesReceivets = pattern.matcher(receivets).matches();
        if (matchesReceivets) {

        } else {
            return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "时间戳不合法，当前时间戳为：" + receivets, data);
        }
        //校验紧急程度字段
        boolean matchesRequestlevel = pattern.matcher(requestlevel).matches();
        if (matchesRequestlevel) {

        } else {
            return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "紧急程度数据不合法，当前值为：" + requestlevel, data);
        }

        //保存失败，记录系统日志：流程数据-检测-失败-流程数据【"+requestname+"】检测接收人为空
        if (StringUtils.isBlank(receiver)) {
            return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "流程数据【" + requestname + "】检测接收人为空", data);
        }
        if ("read".equals(method)) {

        } else {
            if (("0".equals(isremark) || "8".equals(isremark) || StringUtils.isNotBlank(data.getCreatedate() + " " + data.getCreatetime())) && !checkDateTime(data.getCreatedate() + " " + data.getCreatetime())) {
                return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "创建日期不合法，合法格式：yyyy-mm-dd hh:MM:ss", data);
            }
            if (("0".equals(isremark) || "8".equals(isremark) || StringUtils.isNotBlank(data.getReceivedate() + " " + data.getReceivetime())) && !checkDateTime(data.getReceivedate() + " " + data.getReceivetime())) {//校验接收日期格式
                return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "接收日期不合法，合法格式：yyyy-mm-dd hh:MM:ss", data);
            }
        }
        if (StringUtils.isBlank(flowid)) {//流程id不能为空
            return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "flowid不能为空", data);
        }
        if (method.equals("read") || method.equals("todo") || method.equals("done") || method.equals("over") || method.equals("cc")) {

        } else {
            //检测isremark不合法
            if (!isremark.equals(OfsTodoData.IsRemark_Todo) &&
                    !isremark.equals(OfsTodoData.IsRemark_Done) &&
                    !isremark.equals(OfsTodoData.IsRemark_Over) &&
                    !isremark.equals("8")) {
                return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "流程数据【" + requestname + "】检测isremark不合法（0：待办|2：已办|4：办结|8：抄送）", data);
            }
            //检查viewtype值是否合法
            if (!viewtype.equals(OfsTodoData.ViewType_None) && !viewtype.equals(OfsTodoData.ViewType_Over)) {
                return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "流程数据【" + requestname + "】检测viewtype不合法（0：未读|1：已读）", data);
            }
        }
        if (StringUtils.isBlank(workflowname)) {//记录系统日志：流程类型-检测-失败-流程类型未填写
            return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "流程类型未填写", data);
        }
        if (StringUtils.isBlank(requestname)) {//保存失败，记录系统日志：流程数据-检测-失败-流程标题未填写
            return saveLog(data.getSysid(), OfsLog.DataType_WfData + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "流程标题未填写", data);
        }


        //创建人不校验给默认值
        String creatorid = ofsSysInfoService.getHrmResourceIdByHrmTransRule(OfsSysInfo_HrmTransRule, creator);
        if (StringUtils.isNotBlank(creator)) {
            data.setCreatorid(creatorid);
        }

//        Map<String,String> OfsSysInfoMap = ofsSysInfoService.getOneMap(syscode);
//        OfsSysInfo_securityip = OfsUtils.getStringValueByMapKey(OfsSysInfoMap,"securityip");
        if (this.isCheckIP && !checkIp(OfsSysInfo_securityip, this.clientIp)) {
            //检测当前IP是否在许可IP范围内
            return saveLog(data.getSysid(), OfsLog.DataType_OtherSys + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "异构系统标识【" + syscode + "】当前IP（" + this.clientIp + "）未授权", data);
        }

        if (OfsSysInfo_receivewfdata == 0) {
            return saveLog(data.getSysid(), OfsLog.DataType_OtherSys + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "异构系统标识【" + syscode + "】不允许接收流程数据", data);
        }

        //是否新流程类型：1旧，0新
        int workflownameCnt = ofsWorkflowService.getCnt(OfsSysInfo_sysid, workflowname);
        //异构系统自动创建流程类型
        //int OfsSysInfo_autocreatewftype = Util.getIntValue(ofsSysInfoCacheNew.getAutocreatewftype(),OfsSysInfo.AutoCreateWfType_No);
        if (OfsSysInfo_autocreatewftype == 0 && workflownameCnt == 0) {//异构系统的【自动创建流程类型】关闭  并且  流程类型不存在
            return saveLog(data.getSysid(), OfsLog.DataType_OtherSys + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "异构系统标识【" + syscode + "】不允许创建流程类型", data);
        }

        //TODO 异构系统的【自动创建流程类型】开启  并且  流程类型不存在，自动新增流程类型
        //TODO 根据异构系统id和流程类型名称获取异构系统流程类型信息
        Map<String, String> result = saveWorkflowtype(OfsSysInfo_autocreatewftype,
                workflownameCnt,
                OfsSysInfo_sysid,
                OfsSysInfo_receivewfdata, workflowname, flowid);
        if (StringUtils.isNotBlank(result.get("msg"))) {
            data.setUserid("1");
            if ("false".equals(result.get("flag"))) {
                saveLog(data.getSysid(), OfsLog.DataType_WfType + LINK_CHAR + data.getId(), result.get("type"), OfsLog.OperResult_Failure, result.get("msg"), data);
            } else {
                saveLog(data.getSysid(), OfsLog.DataType_WfType + LINK_CHAR + data.getId(), result.get("type"), OfsLog.OperResult_Success, result.get("msg"), data);
            }
            data.setUserid("");
        }

        //根据异构系统id和流程类型名称获取异构系统流程类型信息
//        Map<String,String>  OfsWorkflowMap = ofsWorkflowService.getOneMap(OfsSysInfo_sysid, workflowname);
//        int OfsWorkflow_workflowid = OfsUtils.getIntValueByMapKey(OfsWorkflowMap,"workflowid",OfsWorkflow.Default_WorkflowId);//获取异构系统流程类型id
//        int OfsWorkflow_receivewfdata = OfsUtils.getIntValueByMapKey(OfsWorkflowMap,"receivewfdata",OfsWorkflow.ReceiveWfData_No);//接收流程数据

        int OfsWorkflow_workflowid = OfsWorkflow.Default_WorkflowId;//获取异构系统流程类型id
        int OfsWorkflow_receivewfdata = OfsWorkflow.ReceiveWfData_No;//接收流程数据
        //根据异构系统id和流程类型名称获取异构系统流程类型信息
        OfsWorkflowCacheDAO ofsWorkflowCacheDAO = new OfsWorkflowCacheDAO();
        OfsWorkflow ofsWorkflowCache = ofsWorkflowCacheDAO.getOfsWorkflowCache(String.valueOf(OfsSysInfo_sysid), workflowname);
        if (!Objects.isNull(ofsWorkflowCache)) {
            if (StringUtils.isNotBlank(ofsWorkflowCache.getWorkflowid())) {
                OfsWorkflow_workflowid = Integer.parseInt(ofsWorkflowCache.getWorkflowid());
            }
            if (StringUtils.isNotBlank(ofsWorkflowCache.getReceivewfdata())) {
                OfsWorkflow_receivewfdata = Integer.parseInt(ofsWorkflowCache.getReceivewfdata());
            }
        }

        if ("true".equals(result.get("flag"))) {
            defaultSelect(syscode, OfsWorkflow_workflowid + "");
        }

        if (OfsWorkflow_receivewfdata == 0) {
            return saveLog(data.getSysid(), OfsLog.DataType_OtherSys + LINK_CHAR + DEFAULT_DATA_ID, OfsLog.OperType_Check, OfsLog.OperResult_Failure, "流程类型【" + workflowname + "】不允许接收流程数据", data);
        }

        // 校验通过
        data.setWorkflowid(OfsWorkflow_workflowid + "");
        //data.setFlowguid(data.getSyscode() + LINK_CHAR + OfsWorkflow_workflowid + LINK_CHAR + data.getFlowid() + LINK_CHAR + data.getReceiver());

        //data.setId(ofsTodoDataService.getTodoDataId(syscode,flowid,receiver)+"");

        //1 校验自定义字段
        //2 先校验ofs_todo_data表数据，再校验自定义字段的数据（是否启用，是否必填）
        //3 先保存ofs_todo_data表数据，保存成功之后保存自定义字段的数据
        return null;

    }

    public Map<String, String> saveWorkflowtype(int OfsSysInfo_autocreatewftype,
                                                int workflownameCnt,
                                                int OfsSysInfo_sysid,
                                                int OfsSysInfo_receivewfdata,
                                                String workflowname, String flowid) {
        String msg = "";
        String flag = "false";
        String type = "";
        if (OfsSysInfo_autocreatewftype == 1 && workflownameCnt == 0) {//异构系统的【自动创建流程类型】开启  并且  流程类型不存在
            //流程类型不存在
            //相同flowid历史数据中的流程类型是否存在
            //List<HashMap<String, String>> historyOfsWfTypeExistList = ofsTodoDataService.getHistoryOfsWfTypeExistList(OfsSysInfo_sysid+"",workflowname,flowid);
            //历史数据中的流程类型不存在
            //if(historyOfsWfTypeExistList.size()==0){//不存在，自动新增
            //创建流程类型；
            boolean ofswftypeInsertFlag = ofsWorkflowService.insert(
                    OfsSysInfo_sysid + "", workflowname, OfsSysInfo_receivewfdata + "", OfsWorkflow.Cancel_No + "", SYSADMIN_ID);

            if (ofswftypeInsertFlag) {//记录系统日志：流程类型-自动创建-成功
                //自动创建流程成功后要重新获取流程类型数据
                msg = "" + SystemEnv.getHtmlLabelName(10003859, weaver.general.ThreadVarLanguage.getLang()) + "" + workflowname + "】" + SystemEnv.getHtmlLabelName(10003860, weaver.general.ThreadVarLanguage.getLang()) + "";
                flag = "true";
                type = OfsLog.OperType_AutoNew;
            } else {//记录系统日志：流程类型-自动创建-失败-流程类型【XXXX】保存失败
                msg = "" + SystemEnv.getHtmlLabelName(10003859, weaver.general.ThreadVarLanguage.getLang()) + "" + workflowname + "】" + SystemEnv.getHtmlLabelName(10003861, weaver.general.ThreadVarLanguage.getLang()) + "";
                flag = "false";
                type = OfsLog.OperType_AutoNew;
            }
            //}else{//存在，自动更新
            //更新流程类型；
            //    boolean ofswftypeUpdateFlag = ofsWorkflowService.updateWorkflowName(OfsSysInfo_sysid+"",workflowname,SYSADMIN_ID,historyOfsWfTypeExistList);

            //    if(ofswftypeUpdateFlag){//记录系统日志：流程类型-自动创建-成功
            //自动创建流程成功后要重新获取流程类型数据
            //        msg = ""+ SystemEnv.getHtmlLabelName(10003859,weaver.general.ThreadVarLanguage.getLang())+""+workflowname+"】"+ SystemEnv.getHtmlLabelName(10003862,weaver.general.ThreadVarLanguage.getLang())+"";
            //        flag = "true";
            //        type = OfsLog.OperType_AutoEdit;
            //    }else{//记录系统日志：流程类型-自动创建-失败-流程类型【XXXX】保存失败
            //        msg = ""+ SystemEnv.getHtmlLabelName(10003859,weaver.general.ThreadVarLanguage.getLang())+""+workflowname+"】"+ SystemEnv.getHtmlLabelName(10003863,weaver.general.ThreadVarLanguage.getLang())+"";
            //        flag = "false";
            //        type = OfsLog.OperType_AutoEdit;
            //    }
            //}
//            Map<String, String> map = ofsWorkflowService.getOneMap(OfsSysInfo_sysid, workflowname);
//            OfsWorkflowCacheNew ofsWorkflowCacheNew = new OfsWorkflowCacheNew();
//            ofsWorkflowCacheNew.addCacheByKey(map.get("workflowid"));

            OfsWorkflowCacheDAO ofsWorkflowCacheDAO = new OfsWorkflowCacheDAO();
            ofsWorkflowCacheDAO.addOfsWorkflowCache(String.valueOf(OfsSysInfo_sysid), workflowname);
        }

        Map<String, String> result = new HashMap<String, String>();
        result.put("msg", msg);
        result.put("flag", flag);
        result.put("type", type);

        return result;
    }

    private OfsTodoDataUtils ofsTodoDataUtils = new OfsTodoDataUtils();

    public void sendMessage(OfsSysInfo ofsSysInfoCache, String sysname, OfsTodoData data) {
        //String OfsSysInfo_pcprefixurl = ofsSysInfoCacheNew.getPcprefixurl();//PC地址前缀
        //String OfsSysInfo_appprefixurl = ofsSysInfoCacheNew.getAppprefixurl();//APP地址前缀

//        OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//        ofsSettingCacheNew.next();

        OfsSettingCacheDAO ofsSettingCacheDAO = new OfsSettingCacheDAO();
        OfsSetting ofsSettingCache = ofsSettingCacheDAO.getOfsSettingCache();

        String pcurl = data.getPcurl();
        String appurl = data.getAppurl();


        //待办才发送消息提醒
        /*
        String remindPcUrl = (OfsSysInfo_pcprefixurl+""+pcurl);
        String remindAppUrl = (OfsSysInfo_appprefixurl+""+appurl);

        //TODO 如果有中转页面，推送给消息中心的是中转页面地址

		//String sqlStr = "select * from SystemSet";
		//rsrtx.executeSql(sqlStr);
		//rsrtx.next();
		//String oaaddress = rsrtx.getString("oaaddress");
        String appentranceurl = ofsSysInfoCacheNew.getAppentranceurl();
        if(StringUtils.isNotBlank(appentranceurl)){
			remindAppUrl = appurl;
        }

        String pcentranceurl = ofsSysInfoCacheNew.getPcentranceurl();
        if(StringUtils.isNotBlank(pcentranceurl)){
			remindPcUrl = pcurl;
        }

        if(pcurl.startsWith("http") || pcurl.startsWith("https")){
            remindPcUrl = pcurl;
        }
        if(appurl.startsWith("http") || appurl.startsWith("https")){
            remindAppUrl = appurl;
        }*/


        String remindPcUrl = this.ofsTodoDataUtils.getTodoURL(data, "pc") + "&_weaverofsmsg=1&_ec_ismobile=true";
        String remindAppUrl = this.ofsTodoDataUtils.getTodoURL(data, "app") + "&_weaverofsmsg=1&_ec_ismobile=true";
        log.error("消息通知 app访问地址：" + remindAppUrl);
        log.error("消息通知 pc访问地址：" + remindPcUrl);
        RTXConfig config = new RTXConfig();
        String RtxOrElinkType = config.getPorp(RTXConfig.RtxOrElinkType);//IM提醒类型
        String isusedtx = config.getPorp("isusedtx");//开启IM集成

        log.error("=======================sendMessage start....====================");


        RemindMessage msg = new RemindMessage();
        data.setPcurl(remindPcUrl);
        data.setAppurl(remindAppUrl);
//        msg.setOfsSettingCacheNew(ofsSettingCacheNew);
//        msg.setOfsSysInfoCacheNew(ofsSysInfoCacheNew);
        msg.setOfsSetting(ofsSettingCache);
        msg.setOfsSysInfo(ofsSysInfoCache);
        msg.setData(data);
        msg.setSysname(ofsSysInfoCache.getSysshortname());

        String syscode = ofsSysInfoCache.getSyscode();
        RecordSet rsrtx = new RecordSet();
        rsrtx.executeQuery("select * from Ofs_sysinfo_remind where syscode = ?", syscode);
        int isuse = 0;
        int ismsgcenter = 0;
        int isim = 0;
        int isshortmsg = 0;
        int iscustom = 0;
        String customclass = "";
        String channel = "";
        if (rsrtx.next()) {
            isuse = rsrtx.getInt("isuse");

            ismsgcenter = rsrtx.getInt("ismsgcenter");
            isim = rsrtx.getInt("isim");
            isshortmsg = rsrtx.getInt("isshortmsg");
            iscustom = rsrtx.getInt("iscustom");
            customclass = rsrtx.getString("customclass");
            channel = rsrtx.getString("channel");

            if (isuse == 1) {
                msg.setIsuse(isuse);
                if (ismsgcenter == 1) {
                    msg.setChannel(channel);
                    ofsTodoDataManager.sendMsgCenter(msg, ismsgcenter);
                }
                if (isim == 1) {
                    OfsRemindOtherManagerNew ofsRemindOtherManagerNew = new OfsRemindOtherManagerNew();
                    ofsRemindOtherManagerNew.sendMsg(msg);

                    OfsRemindRTXManagerNew ofsRemindRTXManagerNew = new OfsRemindRTXManagerNew();
                    ofsRemindRTXManagerNew.sendMsg(msg);

                    OfsRemindElinkManagerNew ofsRemindElinkManagerNew = new OfsRemindElinkManagerNew();
                    ofsRemindElinkManagerNew.sendMsg(msg);
                }

                if (isshortmsg == 1) {
                    OfsRemindShortMessage ofsRemindShortMessag = new OfsRemindShortMessage();
                    ofsRemindShortMessag.sendMsg(msg);
                }
                if (iscustom == 1) {
                    String className = customclass;
                    try {
                        Class<?> clazz = Class.forName(className);
                        OfsRemind o = (OfsRemind) clazz.newInstance();
                        o.sendMsg(msg);
                    } catch (Exception e) {
                        log.info("调用自定义接口异常", e);
                    }
                }
            } else {
                //todo 用消息中心了
                ofsTodoDataManager.sendMsgCenter(msg, 0);

                //提醒到IM
                String OfsParam_remindim = Util.null2String(ofsSettingCache.getRemindim(), OfsSetting.RemindIM_No);
                if (isusedtx.equals("1") && OfsSetting.RemindIM_Yes.equals(OfsParam_remindim)) {//开启提醒到IM

                    OfsRemindOtherManagerNew ofsRemindOtherManagerNew = new OfsRemindOtherManagerNew();
                    ofsRemindOtherManagerNew.sendMsg(msg);

                    OfsRemindRTXManagerNew ofsRemindRTXManagerNew = new OfsRemindRTXManagerNew();
                    ofsRemindRTXManagerNew.sendMsg(msg);

                    OfsRemindElinkManagerNew ofsRemindElinkManagerNew = new OfsRemindElinkManagerNew();
                    ofsRemindElinkManagerNew.sendMsg(msg);
                }
                // 推送到自定义消息接口
                String customreminders = ofsSettingCache.getCustomreminders();
                if ("1".equals(customreminders)) {
                    String className = ofsSettingCache.getCustomreminderclass();
                    try {
                        Class<?> clazz = Class.forName(className);
                        OfsRemind o = (OfsRemind) clazz.newInstance();
                        o.sendMsg(msg);
                    } catch (Exception e) {
                        log.info("调用自定义接口异常", e);
                    }
                }

                // 推送短信
                String remindshortmessage = ofsSettingCache.getRemindshortmessage();
                if ("1".equals(remindshortmessage)) {
                    OfsRemindShortMessage ofsRemindShortMessag = new OfsRemindShortMessage();
                    ofsRemindShortMessag.sendMsg(msg);
                }
            }

        } else {
            //todo 用消息中心了
            ofsTodoDataManager.sendMsgCenter(msg, 0);

            //提醒到IM
            String OfsParam_remindim = Util.null2String(ofsSettingCache.getRemindim(), OfsSetting.RemindIM_No);
            if (isusedtx.equals("1") && OfsSetting.RemindIM_Yes.equals(OfsParam_remindim)) {//开启提醒到IM

                OfsRemindOtherManagerNew ofsRemindOtherManagerNew = new OfsRemindOtherManagerNew();
                ofsRemindOtherManagerNew.sendMsg(msg);

                OfsRemindRTXManagerNew ofsRemindRTXManagerNew = new OfsRemindRTXManagerNew();
                ofsRemindRTXManagerNew.sendMsg(msg);

                OfsRemindElinkManagerNew ofsRemindElinkManagerNew = new OfsRemindElinkManagerNew();
                ofsRemindElinkManagerNew.sendMsg(msg);
            }
            // 推送到自定义消息接口
            String customreminders = ofsSettingCache.getCustomreminders();
            if ("1".equals(customreminders)) {
                String className = ofsSettingCache.getCustomreminderclass();
                try {
                    Class<?> clazz = Class.forName(className);
                    OfsRemind o = (OfsRemind) clazz.newInstance();
                    o.sendMsg(msg);
                } catch (Exception e) {
                    log.info("调用自定义接口异常", e);
                }
            }

            // 推送短信
            String remindshortmessage = ofsSettingCache.getRemindshortmessage();
            if ("1".equals(remindshortmessage)) {
                OfsRemindShortMessage ofsRemindShortMessag = new OfsRemindShortMessage();
                ofsRemindShortMessag.sendMsg(msg);
            }
        }

        data.setPcurl(pcurl);
        data.setAppurl(appurl);
    }

    public String buildIsRemarkName(OfsTodoData data) {
        String isremark = data.getIsremark();
        String viewtype = data.getViewtype();
        String isRemarkName = "";
        if (StringUtils.isBlank(isremark) && viewtype.equals("1")) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals(OfsTodoData.IsRemark_Todo)) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(16658, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals(OfsTodoData.IsRemark_Done)) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(24627, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals(OfsTodoData.IsRemark_Over)) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(22487, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals("8")) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(10003849, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals("9")) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(10003849, weaver.general.ThreadVarLanguage.getLang()) + "";
        }
        return isRemarkName;
    }

    public String buildIsRemarkName2(OfsTodoData data, String method) {
        String isremark = data.getIsremark();
        String viewtype = data.getViewtype();
        String isRemarkName = "";
        if ("read".equals(method)) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (StringUtils.isBlank(isremark) && viewtype.equals("1")) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(25425, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals(OfsTodoData.IsRemark_Todo)) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(16658, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals(OfsTodoData.IsRemark_Done)) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(24627, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals(OfsTodoData.IsRemark_Over)) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(22487, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals("8")) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(10003849, weaver.general.ThreadVarLanguage.getLang()) + "";
        } else if (isremark.equals("9")) {
            isRemarkName = "" + SystemEnv.getHtmlLabelName(10003849, weaver.general.ThreadVarLanguage.getLang()) + "";
        }
        return isRemarkName;
    }

    public boolean checkDateTime(String datetime) {
        return Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}(:\\d{2})?$").matcher(datetime).matches();
    }

    public String buildPcUrl(String pcentranceurl, String OfsTodoDataId, String pcurl) {

        if (!"".equals(pcentranceurl)) {
            return getEntranceUrl(pcentranceurl, OfsTodoDataId);
        }
        return pcurl;
    }

    public String buildAppUrl(String pcentranceurl, String OfsTodoDataId, String appurl) {
        if (!"".equals(pcentranceurl)) {
            return getEntranceUrl(pcentranceurl, OfsTodoDataId);
        }
        return appurl;
    }

    public void updatePcurlAndAppurl(OfsSysInfoCacheNew ofsSysInfoCacheNew, OfsTodoData data) {
        //单点登录地址
        String pcentranceurl = ofsSysInfoCacheNew.getPcentranceurl();
        String appentranceurl = ofsSysInfoCacheNew.getAppentranceurl();

        String pcurl = data.getPcurl();
        String pcurlsrc = "";

        if (StringUtils.isNotBlank(pcentranceurl)) {
            pcurlsrc = data.getPcurl();
            pcurl = buildPcUrl(pcentranceurl, data.getId(), data.getPcurl()) + "&isremark=" + data.getIsremark();
        }

        String appurl = data.getAppurl();
        String appurlsrc = "";

        if (StringUtils.isNotBlank(appentranceurl)) {
            appurlsrc = data.getAppurl();
            appurl = buildAppUrl(appentranceurl, data.getId(), data.getAppurl()) + "&isremark=" + data.getIsremark();
        }

        //更新地址

        ofsTodoDataService.updateUrl(Integer.parseInt(data.getId()), data.getFlowid(), pcurlsrc, pcurl, appurlsrc, appurl);

        data.setPcurl(pcurl);
        data.setAppurl(appurl);

    }


    public void updatePcurlAndAppurlInDone(OfsSysInfoCacheNew ofsSysInfoCacheNew, OfsTodoData data) {
        //单点登录地址
        String pcentranceurl = ofsSysInfoCacheNew.getPcentranceurl();
        String appentranceurl = ofsSysInfoCacheNew.getAppentranceurl();

        String pcurl = data.getPcurl();
        String pcurlsrc = "";

        if (StringUtils.isNotBlank(pcentranceurl)) {
            pcurlsrc = data.getPcurl();
            pcurl = buildPcUrl(pcentranceurl, data.getId(), data.getPcurl()) + "&isremark=" + data.getIsremark();
        }

        String appurl = data.getAppurl();
        String appurlsrc = "";

        if (StringUtils.isNotBlank(appentranceurl)) {
            appurlsrc = data.getAppurl();
            appurl = buildAppUrl(appentranceurl, data.getId(), data.getAppurl()) + "&isremark=" + data.getIsremark();
        }


        //更新地址
        ofsDoneDataService.updateUrlInDone(Integer.parseInt(data.getId()), data.getFlowid(), pcurlsrc, pcurl, appurlsrc, appurl);

        data.setPcurl(pcurl);
        data.setAppurl(appurl);

    }

    public String buildSysName(OfsTodoData data) {
        //显示异构系统名称
//        OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//        ofsSettingCacheNew.next();
//        String OfsSetting_showsysname = ofsSettingCacheNew.getShowsysname();

//        OfsSysInfoCacheNew ofsSysInfoCacheNew = new OfsSysInfoCacheNew();
//        String OfsSysInfo_sysshortname = "";
//        String OfsSysInfo_sysfullname = "";
//        while(ofsSysInfoCacheNew.next()){
//            if(data.getSyscode().equals(ofsSysInfoCacheNew.getSyscode())){
//                OfsSysInfo_sysshortname = ofsSysInfoCacheNew.getSysshortname();//异构系统简称
//                OfsSysInfo_sysfullname = ofsSysInfoCacheNew.getSysfullname();//异构系统全称
//                break;
//            }
//        }

        OfsSettingCacheDAO ofsSettingCacheDAO = new OfsSettingCacheDAO();
        OfsSetting ofsSettingCache = ofsSettingCacheDAO.getOfsSettingCache();
        String OfsSetting_showsysname = ofsSettingCache.getShowsysname();

        OfsSysInfoCacheDAO ofsSysInfoCacheDAO = new OfsSysInfoCacheDAO();
        OfsSysInfo ofsSysInfoCache = ofsSysInfoCacheDAO.getOfsSysInfoCacheBySysCode(data.getSyscode());
        String OfsSysInfo_sysshortname = ofsSysInfoCache.getSysshortname();
        String OfsSysInfo_sysfullname = ofsSysInfoCache.getSysfullname();

        String OfsSysInfo_sysname = "";
        if (OfsSetting_showsysname.equalsIgnoreCase(OfsSetting.ShowSysName_None)) {
            OfsSysInfo_sysname = "";
        } else if (OfsSetting_showsysname.equalsIgnoreCase(OfsSetting.ShowSysName_Short)) {
            OfsSysInfo_sysname = OfsSysInfo_sysshortname;
        } else if (OfsSetting_showsysname.equalsIgnoreCase(OfsSetting.ShowSysName_Full)) {
            OfsSysInfo_sysname = OfsSysInfo_sysfullname;
        }

        return OfsSysInfo_sysname;
    }

    public void sendMsgCenter(RemindMessage msg, int ismsgcenter) {

        String channels = msg.getChannel();
        List<String> channelList = new ArrayList<>();
        log.info("前端传入的消息类型ID：" + channels);
        if (StringUtils.isNotBlank(channels)) {
            channelList = Arrays.asList(channels.split(","));
        }
        Map<WeaMessageTypeConfig, List<String>> accessConfig = null;
        ConfigManager configManager = new ConfigManager();
        if ("8".equals(msg.getData().getIsremark())) {
            accessConfig = configManager.defaultRuleCheckConfig(MessageType.OTHER_MAILWAIT_READ, Util.getIntValue(msg.getData().getUserid()), null);
        } else {
            accessConfig = configManager.defaultRuleCheckConfig(MessageType.OTHER_MAILWAIT_REMIND, Util.getIntValue(msg.getData().getUserid()), null);
        }

        if (accessConfig != null && accessConfig.size() > 0) {
            //判断是否推送到消息中心
//            OfsSettingCacheNew ofsSettingCacheNew = new OfsSettingCacheNew();
//            ofsSettingCacheNew.next();
//            String messagecenter = ofsSettingCacheNew.getMessagecenter();
            OfsSettingCacheDAO ofsSettingCacheDAO = new OfsSettingCacheDAO();
            OfsSetting ofsSettingCache = ofsSettingCacheDAO.getOfsSettingCache();
            String messagecenter = ofsSettingCache.getMessagecenter();
            if ("1".equals(messagecenter) || ismsgcenter == 1) {
                for (Map.Entry<WeaMessageTypeConfig, List<String>> entry : accessConfig.entrySet()) {
                    //TodoCenterTodoMessageSender todoCenterTodoMessageSender = new TodoCenterTodoMessageSender(OfsSettingMap, OfsSysInfoMap, sysname, workflowname, requestname, remindPcUrl, remindAppUrl, creatorid, createdate, createtime, receiverid, receivedate, receivetime, OfsTodoDataId, requestid);
                    //new Thread(todoCenterTodoMessageSender).start();
                    // 4、构造消息实体
                    MessageBean message = null;
                    try {
                        User user = User.getUser(Util.getIntValue(msg.getData().getCreatorid()), 0);
                        int langId = 7;
                        String userName = "";
                        if (user != null) {
                            langId = user.getLanguage();
                            userName = user.getLastname();
                        }
                        String detailContent = SystemEnv.getHtmlLabelName(882, langId) + ":" + userName;
                        detailContent += "<br/>";
                        detailContent += SystemEnv.getHtmlLabelName(1339, langId) + ":" + msg.getData().getCreatedate() + " " + msg.getData().getCreatetime();

                        if ("8".equals(msg.getData().getIsremark())) {
                            message = Util_Message.createMessage(MessageType.OTHER_MAILWAIT_READ, Integer.parseInt(msg.getData().getUserid()), msg.getData().getRequestname(), "" + "${}" + msg.getSysname() + "", detailContent, msg.getData().getPcurl(), msg.getData().getAppurl(), Util.getIntValue(msg.getData().getCreatorid(), 0));
                        } else {
                            message = Util_Message.createMessage(MessageType.OTHER_MAILWAIT_REMIND, Integer.parseInt(msg.getData().getUserid()), msg.getData().getRequestname(), "" + "${}" + msg.getSysname() + "", detailContent, msg.getData().getPcurl(), msg.getData().getAppurl(), Util.getIntValue(msg.getData().getCreatorid(), 0));
                        }

                        message.setBizState("0");
                        if ("2".equals(msg.getData().getIsremark()) || "4".equals(msg.getData().getIsremark())) {
                            message.setBizState("1");
                        }
                        //TODO 获取syscode和flowid作为TargetId
//                        RecordSet rs = new RecordSet();
//                        rs.executeQuery("select * from ofs_todo_data where id = ?" ,msg.getData().getId());
//                        rs.next();
//                        String syscode = rs.getString("syscode");
//                        String flowid = rs.getString("flowid");

                        String syscode = msg.getData().getSyscode();
                        String flowid = msg.getData().getFlowid();
                        message.setTargetId(syscode + "_" + flowid);
                        Map<String, Object> detailTitleParams = message.getDetailTitleParams();
                        detailTitleParams.put("workflow_name", msg.getData().getWorkflowname());
                        detailTitleParams.put("system_name", msg.getSysname());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                    // 5、获取新的自定义消息类型
                    WeaMessageTypeConfig config1 = entry.getKey();

                    /*
                     * 1. 当不配置消息类型id时，默认走所有的消息类型。
                     * 2. 当配置消息类型id时，只走配置的消息类型。
                     * 3. 当只开启外部的开关，所有的消息类型都发送。
                     */
                    log.info("1从WeaMessageTypeConfig类中匹配到的消息类型ID：" + config1.getId());
                    boolean flag = false;
                    if (StringUtils.isBlank(channels)) {
                        message.setMessageConfig(config1);
                    } else {
                        for (String channel : channelList) {
                            if (config1.getId().equals(channel)) {
                                flag = true;
                                break;
                            }
                        }
                        if (flag) {
                            message.setMessageConfig(config1);
                        } else {
                            continue;
                        }
                    }

                    // 7、设置检查配置通过需要发送消息的用户
                    message.setUserList(Sets.newHashSet(entry.getValue()));
//                    String showPC = msg.getOfsSysInfoCacheNew().getShowpc() ; //PC显示
                    String showPC = msg.getOfsSysInfo().getShowpc(); //PC显示
                    if (!"1".equals(showPC)) {
                        message.setEnablePC("n");
                    }
//                    String showAPP = msg.getOfsSysInfoCacheNew().getShowapp() ; //APP显示
                    String showAPP = msg.getOfsSysInfo().getShowapp(); //APP显示
                    log.info("showPC and showAPP is : " + showPC + " || " + showAPP);
                    if (!"1".equals(showAPP)) {
                        message.setEnableEM("n");
                        message.setSendMobile("n");
                    }
                    MessageType messageType = MessageType.newInstance(130);
                    message.setMessageType(messageType);
                    String s = JSONObject.toJSONString(message);
                    try {
                        if (isOpen()) {

                            new BaseBean().writeLog("推送消息===" + s);
                            new BaseBean().writeLog("推送消息类===" + this.getClass().getName());
                            String linkMobileUrl = message.getLinkMobileUrl();
                            new BaseBean().writeLog("linkMobileUrl===" + linkMobileUrl);
                            Map<String, String> parameters = parseUrlParameters(linkMobileUrl);
                            new BaseBean().writeLog("linkMobileUrl===" + parameters);
                            String workflowId = parameters.get("workflowId");
                            new BaseBean().writeLog("workflowId===" + workflowId);
                            String title = getTitlebyOfswfid(workflowId);
                            new BaseBean().writeLog("title===" + title);

                            if (!StringUtils.isEmpty(title)) {
                                message.setTitle(title);
                            }
                            // message.setMessageGroupType();
                            // message.setAgentId("86");
                            // message.setMessageGroupTypeName("[dfefgr]");
                            // message.setDetailTitle("");
                            // message.setDetailTitleParams(null);
                        }
                        new BaseBean().writeLog("推送消息===" + JSONObject.toJSONString(message));
                    } catch (Exception e) {
                        new BaseBean().writeLog("推送消息异常===" + e.getMessage());
                        e.printStackTrace();
                    }

                    // 8、发送消息
                    try {
                        Util_Message.sendAndpublishMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    public void defaultSelect(String syscode, String OfsWorkflow_workflowid) {
        //TODO 创建成功，添加默认选中
        try {
            Class clazz = Class.forName("weaver.page.element.WfCenterInterface");
            //type typeid==sysid flowid===workflowid
            //content 具体值
            Method method = clazz.getDeclaredMethod("setWfCenterDefaultData", String.class, String.class);

            RecordSet rs = new RecordSet();
            rs.executeQuery("select * from ofs_sysinfo where syscode = ?", syscode);
            rs.next();
            String sysid = rs.getString("sysid");

            Object instance = clazz.newInstance();
            method.invoke(instance, "typeid", sysid);
            method.invoke(instance, "flowid", OfsWorkflow_workflowid);

            log.error("flowid:" + OfsWorkflow_workflowid);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("添加门户的默认选中失败", e);
        }
    }


    public OfsSysInfoCacheNew getOfsSysInfoCache(OfsTodoData data) {
        OfsSysInfoCacheNew ofsSysInfoCacheNew = new OfsSysInfoCacheNew();
        while (ofsSysInfoCacheNew.next()) {
            String syscode1 = data.getSyscode();
            String syscode2 = ofsSysInfoCacheNew.getSyscode();
            if (syscode1.equals(syscode2)) {
                return ofsSysInfoCacheNew;
            }
        }
        return null;
    }

    /**
     * 保存日志
     */
    public Map<String, String> saveLog(
            String sysid,
            String datatype,
            String opertype,
            String operresult,
            String failremark,
            OfsTodoData todoData
    ) {
        String[] data = datatype.split("_");
        datatype = data[0];
        String dataid = data[1];

        ofsLogService.insert(
                sysid,
                datatype,
                dataid,
                opertype,
                operresult,
                failremark,
                todoData.getSyscode(),
                todoData.getFlowid(),
                todoData.getRequestname(),
                todoData.getWorkflowname(),
                todoData.getNodename(),
                todoData.getIsremark(),
                todoData.getPcurl(),
                todoData.getAppurl(),
                todoData.getCreator(),
                todoData.getCreatorid(),
                todoData.getCreatedate(),
                todoData.getCreatetime(),
                todoData.getReceiver(),
                todoData.getUserid(),
                todoData.getReceivedate(),
                todoData.getReceivetime(),
                todoData.getReceivets()
        );
        return buildReceiveTodoRequest(
                todoData.getSyscode(),
                datatype,
                opertype,
                operresult,
                failremark
        );
    }

    /**
     * 构造处理接收待办信息的结果到map中
     */
    public Map<String, String> buildReceiveTodoRequest(
            String syscode,
            String dataType,
            String operType,
            String operResult,
            String message
    ) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("syscode", syscode);
        map.put("dataType", dataType);
        map.put("operType", operType);
        map.put("operResult", operResult);
        map.put("message", message);

        return map;
    }


    public static Map<String, String> parseUrlParameters(String url) {
        Map<String, String> parameters = new HashMap<>();

        try {
            // URL parsedUrl = new URL(url);
            // String query = parsedUrl.getQuery();
            url = url.substring(url.indexOf("?") + 1);
            if (url != null) {
                String[] pairs = url.split("&");
                for (String pair : pairs) {
                    String[] keyValue = pair.split("=");
                    if (keyValue.length == 2) {
                        String key = keyValue[0];
                        String value = keyValue[1];
                        parameters.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return parameters;
    }


    public static String getTitlebyOfswfid(String ofswfid) {

        String sql = "select title from uf_ofsMsgtitle where wfid = ?";
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(sql, ofswfid);
        String title = "";
        if (recordSet.next()) {
            title = Util.null2String(recordSet.getString("title"));
        }
        return title;
    }

    public static void main(String[] args) {

        String s = "/interface/transfer/ofsTrance.jsp?type=app&sysId=-2&workflowId=-111&flowId=794193549238206464&_weaverofsmsg=1&_ec_ismobile=true";

        System.out.println(parseUrlParameters(s));
    }

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