package com.engine.msgcenter.util;

import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.message.constant.ConstantMapping;
import com.cloudstore.dev.api.util.APPManager;
import com.cloudstore.dev.api.util.EMManager;
import com.cloudstore.eccom.common.WeaIndexManager;
import com.engine.msgcenter.constant.MsgToEMConstant;
import com.engine.msgcenter.entity.MsgDataItem;
import com.engine.systeminfo.util.AppSyncUtil;
import com.icbc.api.internal.apache.http.E;
import com.weaver.file.Prop;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.file.FileNamingManager;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MsgECToEM {
    private static final Log log = LogFactory.getLog(MsgECToEM.class);

    /**
     * 设置在EM创建消息型应用的参数
     *
     * @param img_url     应用在EM显示的图标的地址
     * @param agent_type  2：消息型应用
     * @param name        应用名称
     * @param description 描述
     * @param dialog_url  描述
     * @param sendmobile  是否发送到emobile
     * @return
     */
    public static MsgDataItem createMsgDataItem(String img_url, int agent_type, String name, String description, String dialog_url, String dialog_url_pc, String sendmobile) {
        MsgDataItem item = new MsgDataItem();
        item.setImg_url(img_url);
        item.setAgent_type(agent_type);
        item.setDescription(description);
        item.setDialog_url(dialog_url);
        item.setDialog_url_pc(dialog_url_pc);//EM根据这个是否为空来决定显示原生的还是H5页面,传和dialog_url一样的值
        sendmobile = MsgToEMConstant.SEND_MOBILE.equals(sendmobile) ? "1" : "0";
        item.setSend_to_em(sendmobile);
        String zh_name = name;
        if (name.contains("~"))
            zh_name = Util.formatMultiLang(name, 7 + "");
        item.setName(zh_name);
        Set<Map> set = new HashSet<>();
        for (int i = 7; i <= 9; i++) {
            Map<String, Object> map = new HashMap<>();
            if (i == 7)
                map.put("lang_tag", "zh");
            if (i == 8)
                map.put("lang_tag", "en");
            if (i == 9)
                map.put("lang_tag", "zh_TW");
            map.put("set_value", Util.formatMultiLang(name, i + ""));
            set.add(map);
        }

        item.setLang_data(set);
        return item;
    }


    /**
     * @param agentid     EM消息型应用唯一id
     * @param img_url     应用在EM显示的图标的地址
     * @param agent_type  2：消息型应用
     * @param name        应用名称
     * @param description 描述
     * @param dialog_url  是否发送到emobile
     * @return
     */
    public static MsgDataItem updateMsgDataItem(String agentid, String img_url, int agent_type, String name, String description, String dialog_url, String dialog_url_pc, String sendmobile) {
        MsgDataItem item = new MsgDataItem();
        item.setAgentid(agentid);
        item.setImg_url(img_url);
        item.setAgent_type(agent_type);
        item.setDescription(description);
        item.setDialog_url(dialog_url);
        item.setDialog_url_pc(dialog_url_pc);
        sendmobile = MsgToEMConstant.SEND_MOBILE.equals(sendmobile) ? "1" : "0";
        item.setSend_to_em(sendmobile);
        String zh_name = name;
        if (name.contains("~"))
            zh_name = Util.formatMultiLang(name, 7 + "");
        item.setName(zh_name);
        Set<Map> set = new HashSet<>();
        for (int i = 7; i <= 9; i++) {
            Map<String, Object> map = new HashMap<>();
            if (i == 7)
                map.put("lang_tag", "zh");
            if (i == 8)
                map.put("lang_tag", "en");
            if (i == 9)
                map.put("lang_tag", "zh_TW");
            map.put("set_value", Util.formatMultiLang(name, i + ""));
            set.add(map);
        }
        item.setLang_data(set);
        return item;
    }

    /**
     * 设置在EM创建消息型应用的参数
     *
     * @param msgtype     "share"
     * @param agentid     移动端agentid
     * @param send_type   1
     * @param opentype    1
     * @param opentype_pc 2
     * @param canforward  0:不允许转发  1:可以转发
     * @param callbackurl 消息转发回调地址
     * @return
     */
    public static MsgDataItem sendMsgDataItem(String senderid, String userids, String msgtype, String agentid, String send_type, String content, String desc,
                                              String linkurl, String linkurl_pc, String opentype, String opentype_pc,
                                              String canforward, String callbackurl, String sharetype, String shareid, String sharetypename, Map<String, Object> sendParams) {
        MsgDataItem item = new MsgDataItem();
        item.setSenderid(senderid);
        item.setUserids(userids);
        item.setMsgtype(msgtype);
        item.setAgentid(agentid);
        item.setSend_type(send_type);
        item.setContent(content);
        item.setDesc(desc);
        item.setLinkurl(linkurl);
        item.setLinkurl_pc(linkurl_pc);
        item.setOpentype(opentype);
        item.setOpentype_pc(opentype_pc);
        item.setCanforward(canforward);
        item.setCallbackurl(callbackurl);
        item.setSharetypename(sharetypename);
        item.setSharetype(sharetype);
        item.setShareid(shareid);
        item.setSendParams(sendParams);
        new BaseBean().writeLog("qwe====>"+JSONObject.toJSONString(item));

        return item;
    }


    /**
     * 设置在EM创建消息型应用的参数，封装成一个Map
     */
    public static Map<String, Object> createAppParams(MsgDataItem item) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotBlank(item.getAgentid()))
            params.put("agentid", item.getAgentid());
        if (StringUtils.isNotBlank(item.getName()))
            params.put("name", item.getName());
        if (!item.getLang_data().isEmpty())
            params.put("lang_data", item.getLang_data());
        if (StringUtils.isNotBlank(item.getEnglish_name()))
            params.put("english_name", item.getEnglish_name());
        if (StringUtils.isNotBlank(item.getDescription()))
            params.put("description", item.getDescription());
        if (StringUtils.isNotBlank(String.valueOf(item.getAgent_type())))
            params.put("agent_type", String.valueOf(item.getAgent_type()));
        if (StringUtils.isNotBlank(item.getLogo()))
            params.put("logo", item.getLogo());
        if (StringUtils.isNotBlank(item.getLogo_pc()))
            params.put("logo_pc", item.getLogo_pc());
        if (StringUtils.isNotBlank(item.getClienttypes()))
            params.put("clienttypes", item.getClienttypes());
        if (StringUtils.isNotBlank(item.getDialog_url()))
            params.put("dialog_url", item.getDialog_url());
        if (StringUtils.isNotBlank(item.getDialog_url_pc()))
            params.put("dialog_url_pc", item.getDialog_url_pc());
        if (StringUtils.isNotBlank(item.getStatus_url()))
            params.put("status_url", item.getStatus_url());
        if (StringUtils.isNotBlank(item.getAttention_url()))
            params.put("attention_url", item.getAttention_url());
        if (StringUtils.isNotBlank(item.getMsg_url()))
            params.put("msg_url", item.getMsg_url());
        if (StringUtils.isNotBlank(item.getShare_url()))
            params.put("share_url", item.getShare_url());
        if (StringUtils.isNotBlank(item.getEnable_auth()))
            params.put("enable_auth", item.getEnable_auth());
        if (StringUtils.isNotBlank(item.getSend_to_em()))
            params.put("send_to_em", item.getSend_to_em());

        return params;
    }


    /**
     * 设置消息发给EM的参数,封装成一个Map
     */
    public static Map<String, Object> sendMsgParams(MsgDataItem item) {
        Map<String, Object> params = new HashMap<>(item.getSendParams());
        if (StringUtils.isNotBlank(item.getSenderid()))
            params.put("senderid", item.getSenderid());
        if (StringUtils.isNotBlank(item.getUserids()))
            params.put("userids", item.getUserids());
        if (StringUtils.isNotBlank(item.getMsgtype()))
            params.put("msgtype", item.getMsgtype());
        if (StringUtils.isNotBlank(item.getAgentid()))
            params.put("agentid", item.getAgentid());
        if (StringUtils.isNotBlank(item.getSend_type()))
            params.put("send_type", item.getSend_type());
        Map<String, Object> shareParams = new HashMap<>();
        if (params.get("share") != null) {
            shareParams = (Map) JSONObject.toJSON(params.get("share"));
        }
        if (StringUtils.isNotBlank(item.getContent()))
            shareParams.put("content", item.getContent());
        Map<String, Object> extraParams = new HashMap<>();
        if (shareParams.get("extra") != null) {
            extraParams = (Map) JSONObject.toJSON(shareParams.get("extra"));
        }
        if (StringUtils.isNotBlank(item.getDesc()))
            extraParams.put("desc", item.getDesc());
        if (StringUtils.isNotBlank(item.getLinkurl()))
            extraParams.put("linkurl", item.getLinkurl());
        if (StringUtils.isNotBlank(item.getLinkurl_pc()))
            extraParams.put("linkurl_pc", item.getLinkurl_pc());
        if (StringUtils.isNotBlank(item.getOpentype()))
            extraParams.put("opentype", item.getOpentype());
        if (StringUtils.isNotBlank(item.getOpentype_pc()))
            extraParams.put("opentype_pc", item.getOpentype_pc());
        if (StringUtils.isNotBlank(item.getCanforward()))
            extraParams.put("canforward", item.getCanforward());
        if (StringUtils.isNotBlank(item.getSharetypename()))
            extraParams.put("sharetypename", item.getSharetypename());
        if (StringUtils.isNotBlank(item.getSharetype()))
            extraParams.put("sharetype", item.getSharetype());
        if (StringUtils.isNotBlank(item.getShareid()))
            extraParams.put("shareid", item.getShareid());
        shareParams.put("extra", extraParams);
        params.put("share", shareParams);

        return params;
    }

    public static String delHTMLTag(String htmlStr) {
        if (htmlStr != null) {
            htmlStr = htmlStr.replaceAll("\\</p>|<br>|</br>|<br/>", "\n");

            htmlStr = htmlStr.replaceAll("&nbsp;", " ");

            String regEx_html = "(<img )(.[^>]*)(>)";
            Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(htmlStr);

            htmlStr = m_html.replaceAll("[" + SystemEnv.getHtmlLabelName(74, 7) + "]"); //过滤html标签
            regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); //过滤html标签
            return htmlStr.trim();
        }
        return null;

    }

    /**
     * 创建EC在EM的消息型应用
     */
    public static String CreateMsgTypeApp(String img_url, String name, String description, String dialog_url, String sendmobile) {
        MsgDataItem item = createMsgDataItem(img_url, 2, name, description, checkDialogUrl_New(dialog_url), checkDialogUrl_Old(dialog_url), sendmobile);
        return getAgentId(item);
    }

    /**
     * 创建EC在EM的消息型应用
     */
    public static String CreateMsgTypeApp(String img_url, String name, String description, String app_Dialog_url, String pc_Dialogurl, String sendmobile) {
        MsgDataItem item = createMsgDataItem(img_url, 2, name, description, checkDialogUrl_New(app_Dialog_url), checkDialogUrl_Old(pc_Dialogurl), sendmobile);
        return getAgentId(item);
    }

    public static String getDialog_Url(String belongId, String isTab) {
        String dialog_url = MsgToEMConstant.DIALOG_URL + belongId;
        //新到达流程
        if (MsgToEMConstant.IS_TAB.equals(isTab))
            dialog_url += MsgToEMConstant.DIALOG_URL_Flag;
        return dialog_url;
    }


    /**
     * 用于创建消息型应用的时候，获取默认的EM PC端地址
     *
     * @param id ecology_biz_mobile_config 表中的id
     * @return
     */
    public static String getEM_PC_DialogUrl(String id) {
        String dialog_url = MsgToEMConstant.DIALOG_URL + id;
        return dialog_url;
    }


    /**
     * 用于创建消息型应用的时候，获取默认的EM 移动端地址
     *
     * @param id ecology_biz_mobile_config 表中的id
     * @return
     */
    public static String getEM_APP_DialogUrl(String id) {
        String dialog_url = MsgToEMConstant.DIALOG_URL_NEW + id;
        return dialog_url;
    }


    //上传图片,setlogo
    public static MsgDataItem mediaUpload(MsgDataItem item) {
        if (StringUtils.isNotBlank(item.getImg_url())) {
            FileNamingManager manager = FileNamingManager.getInstance();
            String fileUrl = manager.unTransform(item.getImg_url());
            String fileid = fileUrl.replaceAll("/weaver/weaver.file.FileDownload\\?fileid=", "");
            ImageFileManager imageFileManager = new ImageFileManager();
            InputStream input;
            String responseData = null;
            try {
                if (StringUtils.isNumeric(fileid)) {
                    imageFileManager.getImageFileInfoById(Util.getIntValue(fileid));
                    responseData = APPManager.mediaUpload("image", imageFileManager.getImageFileType(), imageFileManager.getInputStream(), "media", imageFileManager.getImageFileName());

                } else if ((input = AppSyncUtil.getFileInputSteam(null, item.getImg_url())) != null) {
                    responseData = APPManager.mediaUpload("image", AppSyncUtil.getFileType(item.getImg_url()), input, "media", AppSyncUtil.getFileName(item.getImg_url()));
                } else {
                    return null;
                }
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            JSONObject objectData = JSONObject.parseObject(responseData);
            if (objectData != null && objectData.getIntValue("errcode") != 0) {
                log.error(objectData.getString("errmsg"));
                return null;
            }
            if (objectData != null)
                item.setLogo(objectData.getString("media_id"));
            else
                log.info("==========" + item.getName() + " 图片为空 ========");
            return item;
        }
        return null;
    }

    public static String getAgentId(MsgDataItem item) {
        if (StringUtils.isBlank(item.getAgentid()) && StringUtils.isNotBlank(item.getImg_url())) {
            String responseData = null;
            item = mediaUpload(item);
            if (item != null) {
                Map<String, Object> params = createAppParams(item);//将参数基类转化为map
                try {
                    responseData = APPManager.createApp(params);//创建应用
                } catch (KeyManagementException e) {
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                JSONObject objectData = JSONObject.parseObject(responseData);
                if (objectData != null && objectData.getIntValue("errcode") != 0) {
                    log.error(objectData.getString("errmsg"));
                    return null;
                }
                return objectData.getString("agentid");
            }
            return null;
        }
        return null;
    }


    public static boolean getApp(String agentid) {
        if (StringUtils.isNotBlank(agentid)) {
            Map param = new HashMap();
            String responseData = null;
            param.put("agentid", agentid);
            try {
                responseData = APPManager.getApp(param);//获取单个应用
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            JSONObject objectData = JSONObject.parseObject(responseData);
            if (objectData != null && objectData.getIntValue("errcode") != 0) {
                log.error(objectData.getString("errmsg"));
                return false;
            }
            return true;
        }
        return false;
    }


    public static String send(MsgDataItem item) {
        String responseData = null;
        try {
            responseData = APPManager.send(sendMsgParams(item));
        } catch (KeyManagementException e) {
            log.error("消息推送到EM平台失败:" + e);
        } catch (NoSuchAlgorithmException e) {
            log.error("消息推送到EM平台失败:" + e);
        }

        JSONObject objectData = JSONObject.parseObject(responseData);
        if (objectData != null && objectData.getIntValue("errcode") != 0)
            log.error("消息推送到EM错误信息:" + objectData.getString("errmsg"));
        return responseData;
    }


    /**
     * 设置在EM创建消息型应用的参数
     *
     * @param message 发送的消息体
     */

    public static void sendMsg(MessageBean message) {
        for (MessageBean messageBean : getLangMsgList(message)) {
            send(sendMsgDataItem(messageBean));
        }
    }


    /**
     * 设置消息发给EM的参数
     *
     * @return
     */
    public static MsgDataItem sendMsgDataItem(MessageBean messageBean) {

        StringBuilder str = new StringBuilder();
        String senderid = messageBean.getEmParams().get("senderid") == null ? Util.null2String(messageBean.getCreater()) : Util.null2String(messageBean.getEmParams().get("senderid"));
//        String userids = messageBean.getEmParams().get("userids") == null ? null : Util.null2String(messageBean.getEmParams().get("userids"));
        String userids;
        String msgtype = messageBean.getEmParams().get("msgtype") == null ? "share" : Util.null2String(messageBean.getEmParams().get("msgtype"));
        String agentid = messageBean.getEmParams().get("agentid") == null ? messageBean.getAgentId() : Util.null2String(messageBean.getEmParams().get("agentid"));
        String send_type = messageBean.getEmParams().get("send_type") == null ? "1" : Util.null2String(messageBean.getEmParams().get("send_type"));
        Map shareMap = messageBean.getEmParams().get("share") == null ? new HashMap() : (Map) JSONObject.toJSON(messageBean.getEmParams().get("share"));
        String title;
        if (StringUtils.isNotBlank(messageBean.getDetailTitle()) && !messageBean.getMessageGroupTypeName().equals(messageBean.getDetailTitle()))
            title = shareMap.get("content") == null ? messageBean.getDetailTitle() + "： " + delHTMLTag(messageBean.getTitle()) : Util.null2String(shareMap.get("content"));
        else
            title = shareMap.get("content") == null ? delHTMLTag(messageBean.getTitle()) : Util.null2String(shareMap.get("content"));


        Map extraMap = shareMap.get("extra") == null ? new HashMap() : (Map) JSONObject.toJSON(shareMap.get("extra"));
        String content = extraMap.get("desc") == null ? delHTMLTag(messageBean.getContext()) : Util.null2String(extraMap.get("desc"));
        String linkurl = extraMap.get("linkurl") == null ? messageBean.getLinkMobileUrl() : Util.null2String(extraMap.get("linkurl"));
        String linkurl_pc = extraMap.get("linkurl_pc") == null ? messageBean.getLinkUrl() : Util.null2String(extraMap.get("linkurl_pc"));
//        String linkurl = extraMap.get("linkurl") == null ? "/message.jsp?linkurl=" + codeBase64(messageBean.getLinkUrl()) + "&linkmobileurl="+codeBase64(messageBean.getLinkMobileUrl()) : Util.null2String(extraMap.get("linkurl"));
//        String linkurl_pc = extraMap.get("linkurl_pc") == null ? "/message.jsp?linkurl="+ codeBase64(messageBean.getLinkUrl()) + "&linkmobileurl="+codeBase64(messageBean.getLinkMobileUrl())   : Util.null2String(extraMap.get("linkurl_pc"));
        String opentype = extraMap.get("opentype") == null ? "1" : Util.null2String(extraMap.get("opentype"));
        String opentype_pc = extraMap.get("opentype_pc") == null ? "2" : Util.null2String(extraMap.get("opentype_pc"));
        String canforward = extraMap.get("canforward") == null ? "0" : Util.null2String(extraMap.get("canforward"));
        String callbackurl = extraMap.get("callbackurl") == null ? "" : Util.null2String(extraMap.get("callbackurl"));
        String sharetypename = extraMap.get("sharetypename") == null ? messageBean.getDetailTitle() : Util.null2String(extraMap.get("sharetypename"));
        String sharetype = extraMap.get("sharetype") == null ? null : Util.null2String(extraMap.get("sharetype"));
        String shareid = extraMap.get("shareid") == null ? null : Util.null2String(extraMap.get("shareid"));

        if (messageBean.getUserList().size() == 0) {
            userids = Util.null2String(messageBean.getUserId());
        } else {
            for (String userid : messageBean.getUserList())
                str.append(userid).append("|");
            userids = str.toString().substring(0, str.length() - 1);//去掉最后一个“|”
        }

        if (StringUtils.isNotBlank(Util.null2String(messageBean.getEmParams().get("userids"))))
            userids = userids + "|" + Util.null2String(messageBean.getEmParams().get("userids"));

        if (StringUtils.isBlank(sharetype) && StringUtils.isNotBlank(messageBean.getTargetId())) {
            sharetype = "workflow";
            shareid = messageBean.getTargetId();
        }


        if ("share".equals(msgtype) && StringUtils.isBlank(linkurl)) {
            msgtype = "text";
            Map<String, Object> textMap = new HashMap<>();
            if (StringUtils.isNotBlank(messageBean.getDetailTitle()) && !messageBean.getMessageGroupTypeName().equals(messageBean.getDetailTitle()))
                textMap.put("content", messageBean.getDetailTitle() + "： " + delHTMLTag(messageBean.getTitle()) + "\n" + delHTMLTag(messageBean.getContext()));
            else
                textMap.put("content", delHTMLTag(messageBean.getTitle()) + "\n" + delHTMLTag(messageBean.getContext()));
            Map<String, Object> map = new HashMap<>();
            map.put("text", textMap);
            map.put("safe", 0);
            messageBean.getEmParams().putAll(map);
        }
        //如果是此消息id是需要修改的消息则替换为空
        String msgTypeId = (Util.null2String(Prop.getPropValue("QC2586804", "msgtype")));
        String msgTypeId2 = (Util.null2String(Prop.getPropValue("QC2586804", "msgtype2")));
        new BaseBean().writeLog("msgTypeId===>"+msgTypeId);
        new BaseBean().writeLog("messageBean===>"+JSONObject.toJSONString(messageBean));
        try {
            if(msgTypeId.length()>0){
                String[] msgTypeIdArr = msgTypeId.split(",");
                List<String> msgTypeIdList = Arrays.asList(msgTypeIdArr);
                if (msgTypeIdList.contains(messageBean.getMessageGroupType())){
                    title=title.replace("：","\u0020");
                }
            }

            if(msgTypeId2.length()>0){
                String[] msgTypeIdArr = msgTypeId2.split(",");
                List<String> msgTypeIdList = Arrays.asList(msgTypeIdArr);
                if (msgTypeIdList.contains(messageBean.getMessageGroupType())){
                    title=title.replace("：","-");
                }
            }

        }catch (Exception e){
            new BaseBean().writeLog("Exception===>"+e.getMessage());
            e.printStackTrace();
        }

        new BaseBean().writeLog("messageBean===>"+JSONObject.toJSONString(messageBean));
        return sendMsgDataItem(senderid, userids, msgtype, agentid, send_type, title, content, linkurl,
                linkurl_pc, opentype, opentype_pc, canforward, callbackurl, sharetype, shareid, sharetypename, messageBean.getEmParams());
    }


    public static List<MessageBean> getLangMsgList(MessageBean message) {
        List<MessageBean> messageBeanList = new ArrayList<>();
        Map<Integer, Set> lang_map = new HashMap<>();
        int userLang;
        if (message.getUserList().isEmpty())
            message.getUserList().add(Util.null2String(message.getUserId()));
        for (String userid : message.getUserList()) {
            userLang = User.getUserLang(Util.getIntValue(userid, 0));
            if (!lang_map.containsKey(userLang)) {
                Set<String> userSet = new HashSet<>();
                userSet.add(userid);
                lang_map.put(userLang, userSet);
            } else {
                lang_map.get(userLang).add(userid);
            }
        }
        for (Map.Entry<Integer, Set> entry : lang_map.entrySet()) {
            MessageBean messageBean = message.shallowClone();
            messageBean.setUserList(entry.getValue());
            messageBean.setMessageGroupTypeName(Util.formatMultiLang(messageBean.getMessageGroupTypeName(), entry.getKey() + ""));
            messageBean.setDetailTitle(MsgTypeUtil.spilt(messageBean.getDetailTitle(), entry.getKey()));
            messageBean.setTitle(Util.formatMultiLang(messageBean.getTitle(), entry.getKey() + ""));
            messageBean.setContext(Util.formatMultiLang(messageBean.getContext(), entry.getKey() + ""));
            messageBeanList.add(messageBean);
        }
        return messageBeanList;

    }


    public static boolean updateMsgTypeApp(String agentid, String img_url, String name, String description, String sendmobile) {
        String responseData = null;

        MsgDataItem item = updateMsgDataItem(agentid, img_url, 2, name, description, null, null, sendmobile);
        item = mediaUpload(item);

        try {
            responseData = APPManager.updateApp(createAppParams(item));
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        JSONObject objectData = JSONObject.parseObject(responseData);
        if (objectData != null && objectData.getIntValue("errcode") != 0) {
            log.error(objectData.getString("errmsg"));
            return false;
        }
        return true;

    }

    public static boolean updateMsgTypeApp(String agentid, String img_url, String name, String description, String dialogurl, String sendmobile) {
        String responseData = null;

        MsgDataItem item = updateMsgDataItem(agentid, img_url, 2, name, description, checkDialogUrl_New(dialogurl), checkDialogUrl_Old(dialogurl), sendmobile);
        item = mediaUpload(item);
        if (StringUtils.isBlank(item.getLogo()))
            return false;

        try {
            responseData = APPManager.updateApp(createAppParams(item));
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        JSONObject objectData = JSONObject.parseObject(responseData);
        if (objectData != null && objectData.getIntValue("errcode") != 0) {
            log.error(objectData.getString("errmsg"));
            return false;
        }
        return true;

    }


    public static boolean updateMsgTypeApp(String agentid, String img_url, String name, String description, String dialogurl, String dialogurl_pc, String sendmobile) {
        String responseData = null;

        MsgDataItem item = updateMsgDataItem(agentid, img_url, 2, name, description, checkDialogUrl_New(dialogurl), checkDialogUrl_Old(dialogurl_pc), sendmobile);
        item = mediaUpload(item);
        if (StringUtils.isBlank(item.getLogo()))
            return false;

        try {
            responseData = APPManager.updateApp(createAppParams(item));
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        JSONObject objectData = JSONObject.parseObject(responseData);
        if (objectData != null && objectData.getIntValue("errcode") != 0) {
            log.error(objectData.getString("errmsg"));
            return false;
        }
        return true;

    }

    public static boolean updateMsgBizType(String id, String imgurl, String group, String enable, String enablepc, String enableem, String sendmobile) {
        RecordSet rs = new RecordSet();
        boolean flag;
        rs.executeUpdate("update ecology_biz_mobile_config set groupid = ? , enable = ? ,enablepc = ?,enableem = ? ,imgurl=?, sendmobile = ? where belongid = ? and biztypeid is not null ", group, enable, enablepc, enableem, imgurl, sendmobile, id);
        rs.executeQuery("select * from ecology_biz_mobile_config where  belongid = ? and biztypeid is not null ", id);
        while (rs.next()) {
            if (StringUtils.isNotBlank(rs.getString("agentid"))) {
                flag = updateMsgTypeApp(rs.getString("agentid"), rs.getString("imgurl"), rs.getString("name"), rs.getString("description"), rs.getString("em_app_url"), rs.getString("dialogurl"), rs.getString("sendmobile"));
            }
        }
        return true;
    }

    public static void deleteMsgTypeApp(String agentids) {
        try {
            String[] agentid = agentids.split(",");
            for (String id : agentid) {
                String data = APPManager.delete(id);
                log.info(data);
            }
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static void deleteMsgBizType(String ids) {
        String[] idStr = Util.splitString(ids, ",");
        RecordSet rs = new RecordSet();
        for (String id : idStr) {
            rs.executeQuery("select * from ecology_biz_mobile_config where  belongid = ? and biztypeid is not null ", id);
            while (rs.next() && StringUtils.isNotBlank(rs.getString("agentid"))) {
                deleteMsgTypeApp(rs.getString("agentid"));
            }
            rs.executeUpdate("delete from ecology_biz_mobile_config where belongid = ? and biztypeid is not null ", id);
        }
    }

    /**
     * 初始化更新保存在EC的EM消息型应用地址 dialogurl
     *
     * @return
     */
    public static void initDialogUrlOld() {
        //EM移动端地址在EC数据库中初始化
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id,dialogurl,is_em_app_url from ECOLOGY_BIZ_MOBILE_CONFIG where is_em_app_url = ?", "n");
        List<List> params = new ArrayList<>();
        while (rs.next()) {
            if (("n").equals(rs.getString("is_em_app_url"))) {
                if (rs.getString("dialogurl")!= null && rs.getString("dialogurl").startsWith(MsgToEMConstant.DIALOG_URL)){
                    List list = new ArrayList<>();
                    list.add(checkDialogUrl_New(rs.getString("dialogurl")));
                    list.add("y");
                    list.add(rs.getString("id"));
                    params.add(list);
                }
            }
        }

        rs.executeBatchSql("update ECOLOGY_BIZ_MOBILE_CONFIG set em_app_url = ? ,is_em_app_url = ? where id = ?  ", params);

        // EM移动端地址在EM初始化
        if (EMManager.getJoinStatus(true)) {
            RecordSet recordSet = new RecordSet();
            int random = (int) (Math.random() * 1000);
            rs.executeQuery("select id,agentid,imgurl,name,dialogurl,em_app_url,sendmobile,belongid,is_dialogurl,is_em_app_url from ECOLOGY_BIZ_MOBILE_CONFIG where agentid is not null");
            while (rs.next()) {
                if (StringUtils.isNotBlank(rs.getString("agentid"))) {
                    // 修复客户交流提醒数据
                    if("28".equals(rs.getString("id")) && "y".equals(rs.getString("is_em_app_url"))){
                        try {
                            boolean flag = MsgECToEM.updateMsgTypeApp(rs.getString("agentid"), rs.getString("imgurl"), rs.getString("name"), "", randomDialogUrl(checkDialogUrl_New("/spa/crm/static4mobile/index.html#/remind"), random), randomDialogUrl(checkDialogUrl_Old(rs.getString("dialogurl")), random), rs.getString("sendmobile"));
                            if (flag)
                                recordSet.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set is_em_app_url =? where id = ? ",  "n", rs.getString("id"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (("n").equals(rs.getString("is_dialogurl"))) {
                        try {
                            boolean flag = MsgECToEM.updateMsgTypeApp(rs.getString("agentid"), rs.getString("imgurl"), rs.getString("name"), "", randomDialogUrl(checkDialogUrl_New(rs.getString("em_app_url")), random), randomDialogUrl(checkDialogUrl_Old(rs.getString("dialogurl")), random), rs.getString("sendmobile"));
                            if (flag)
                                recordSet.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set dialogurl = ?,is_dialogurl=? where id = ? ", checkDialogUrl_Old(rs.getString("dialogurl")), "y", rs.getString("id"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

    }

    /**
     * 检测保存在EC的EM消息型应用地址，并添加一个随机数用于EM手机端刷新地址缓存
     *
     * @param dialogurl EM消息型应用地址
     * @param random    随机数
     * @return
     */
    public static String randomDialogUrl(String dialogurl, int random) {
        if (dialogurl.startsWith(MsgToEMConstant.DIALOG_URL) || dialogurl.startsWith(MsgToEMConstant.DIALOG_URL_NEW)) {
            //        dialogurl = checkDialogUrl(dialogurl); //检测dialogUrl
            String[] dialogurls = dialogurl.split("\\?");
            if (dialogurls.length > 1)
                dialogurl = dialogurl.replaceAll("#", "?" + dialogurls[1] + "&v=test" + random + "#");
            else
                return null;
        }
        return dialogurl;
    }

    /**
     * 检测保存在EC的EM消息型应用地址
     *
     * @param dialogurl EM消息型应用地址
     * @return 新的dialogurl
     */
    public static String checkDialogUrl_New(String dialogurl) {
        if (StringUtils.isNotBlank(dialogurl) && dialogurl.startsWith(MsgToEMConstant.DIALOG_URL))
            dialogurl = dialogurl.replace(MsgToEMConstant.DIALOG_URL, MsgToEMConstant.DIALOG_URL_NEW);
        return dialogurl;
    }


    /**
     * 检测保存在EC的EM消息型应用地址
     *
     * @param dialogurl_Old EM消息型应用地址
     * @return 旧的dialogurl
     */
    public static String checkDialogUrl_Old(String dialogurl_Old) {
        if (StringUtils.isNotBlank(dialogurl_Old) && dialogurl_Old.startsWith(MsgToEMConstant.DIALOG_URL_NEW))
            dialogurl_Old = dialogurl_Old.replace(MsgToEMConstant.DIALOG_URL_NEW, MsgToEMConstant.DIALOG_URL);
        return dialogurl_Old;
    }


    /**
     * 确保消息类型对应的agentid参数更新为真正需要推向EM的agentid
     */
    public static void insureMessageType(MessageBean bean) {
        if (bean != null) {
            String agentName = bean.getMessageGroupTypeName();
//            String dialogUrl = MsgToEMConstant.DIALOG_URL + bean.getMessageGroupType();
            String app_Dialogurl = getEM_APP_DialogUrl(bean.getMessageGroupType());
            String pc_Dialogurl = getEM_PC_DialogUrl(bean.getMessageGroupType());

            String biztypeid = bean.getMessageGroupType() + "," + bean.getBizType();
            boolean isAssistant = false;

            RecordSet rs = new RecordSet();
            String agentid = null;
            rs.executeQuery("select * from ECOLOGY_BIZ_MOBILE_CONFIG where id = ? ", bean.getMessageGroupType());
            if (rs.next()) {
                agentid = rs.getString("agentid");
                app_Dialogurl = rs.getString("em_app_url");
                pc_Dialogurl = rs.getString("dialogurl");
            }
            //1、对业务类型的处理
            if (StringUtils.isNotBlank(bean.getBizType()) && ConstantMapping.booleanOfString(bean.getIsDefault())) {
                agentName = bean.getBizTitle();
                app_Dialogurl = MsgToEMConstant.DIALOG_URL_NEW + bean.getMessageGroupType() + "," + bean.getBizType();
                pc_Dialogurl = MsgToEMConstant.DIALOG_URL + bean.getMessageGroupType() + "," + bean.getBizType();
                isAssistant = true;
            }


            if (!isAssistant) {
                //3、如果不是业务类型,当agentid为空时调用EM接口创建应用并更新
                if (StringUtils.isBlank(agentid)) {
                    //消息类型
                    String agentId = CreateMsgTypeApp(bean.getImgUrl(), agentName, agentName, app_Dialogurl, pc_Dialogurl, bean.getSendMobile());
                    rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set agentid=? where id=?", agentId, bean.getMessageGroupType());
                    bean.setAgentId(agentId);
                } else
                    bean.setAgentId(agentid);
            } else {
                //4、如果是业务类型,查询业务类型对应的agentid
                rs.executeQuery("select  * from ECOLOGY_BIZ_MOBILE_CONFIG where biztypeid = ? ", "2,-1," + bean.getBizType());//查询老的业务类型
                if (rs.next()) {
                    String eid = rs.getString("id");
                    String img_url = rs.getString("imgurl");
                    rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set NAME = ? , DIALOGURL = ? , em_app_url = ?,BIZTYPEID = ? where id = ?", bean.getBizTitle(), pc_Dialogurl, app_Dialogurl, biztypeid, eid);
                    updateMsgTypeApp(rs.getString("agentid"), img_url, bean.getBizTitle(), "", app_Dialogurl, pc_Dialogurl, bean.getSendMobile());
                }


                rs.executeQuery("select name,agentid,em_app_url,dialogurl from ecology_biz_mobile_config where biztypeid=?", biztypeid);
                if (rs.next()) {
                    //5、当前业务类型已经创建EM应用时则更新消息实体中agentid参数即可
                    if (StringUtils.isNotBlank(rs.getString("agentid"))) {
                        bean.setAgentId(rs.getString("agentid"));
                        app_Dialogurl = rs.getString("em_app_url");
                        pc_Dialogurl = rs.getString("dialogurl");
                        if (!rs.getString("name").equals(bean.getBizTitle())) {
                            log.info("================update biztitle to EM ====================");
                            updateMsgTypeApp(bean.getAgentId(), bean.getImgUrl(), bean.getBizTitle(), "", app_Dialogurl, pc_Dialogurl, bean.getSendMobile());
                            rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set name=?  where biztypeid=?", bean.getBizTitle(), biztypeid);
                            rs.executeUpdate("update ECOLOGY_MESSAGE_BIZ_TYPE set biztitle = ? where  messagegrouptype  = ? and biztype = ?", bean.getBizTitle(), bean.getMessageGroupType(), bean.getBizType());
                        }
                    } else {
                        //6、当前业务类型没有创建EM应用时则调用EM接口创建应用并更新
                        String agentId = CreateMsgTypeApp(bean.getImgUrl(), agentName, agentName, app_Dialogurl, pc_Dialogurl, bean.getSendMobile());
                        rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set agentid=? ,dialogurl = ?,em_app_url = ? where biztypeid=?", agentId, pc_Dialogurl, app_Dialogurl, biztypeid);
                        bean.setAgentId(agentId);
                    }
                } else {
                    //7、如果当前业务类型是第一次接收,调用EM接口创建并更新即可
                    String agentId = CreateMsgTypeApp(bean.getImgUrl(), agentName, agentName, app_Dialogurl, pc_Dialogurl, bean.getSendMobile());
                    rs.executeUpdate("insert into ECOLOGY_BIZ_MOBILE_CONFIG (id,name,messagetypeid,belongid,biztypeid,moduleid,groupid,agentid,dialogurl,em_app_url,imgurl,enable,enablepc,enableem,sendmobile,isshow,isdefault) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                            WeaIndexManager.getGuid(8),
                            bean.getBizTitle(),
                            bean.getMessageGroupType(),
                            bean.getBelongId(),
                            biztypeid,
                            bean.getModuleId(),
                            null,
                            agentId,
                            pc_Dialogurl,
                            app_Dialogurl,
                            bean.getImgUrl(),
                            bean.getEnable(),
                            bean.getEnablePC(),
                            bean.getEnableEM(),
                            bean.getSendMobile(),
                            ConstantMapping.CONST_N,
                            ConstantMapping.CONST_N);
                    bean.setAgentId(agentId);
                }
            }
        }
    }

}
