package com.engine.payroll.biz;

import com.api.doc.detail.util.DocDownloadCheckUtil;
import com.api.doc.mobile.systemDoc.util.SystemDocUtil;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.engine.msgcenter.biz.ConfigManager;
import com.engine.msgcenter.biz.WeaMessageTypeConfig;
import com.google.common.collect.Sets;
import weaver.conn.RecordSet;
import weaver.file.FileUploadToPath;
import weaver.file.ImageFileManager;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class SendMsg extends BaseBean {
    private static SendMsg _sendMsg;

    public static SendMsg getInstance() {
        if (_sendMsg == null)
            _sendMsg = new SendMsg();
        return _sendMsg;
    }

    private static final String LINKURL = "/spa/hrm/index_mobx.html#/main/hrm/payrollDetail/";
    private static final String LINKMOBILEURL = "/spa/hrm/static4mobile/index.html#/payrollDetail/";

    /**
     * 推送消息
     * @param request
     * @param user
     * @param targetId
     */
    public void dispatch(HttpServletRequest request, User user, String targetId, Set<String> userList, Map<String, String> keys, FileUploadToPath fu) {
        try{
            String payrollTitle = fu.getParameter("title");
            String templateId = fu.getParameter("templateId");
            String imgId = "";
            boolean dispatchImg = false;
            RecordSet rs = new RecordSet();
            rs.executeQuery("select dispatchImg, imgId from hrm_payroll_template where id = ?", templateId);
            while(rs.next()){
                imgId = Util.null2String(rs.getString("imgId"));
                dispatchImg = "1".equals(Util.null2String(rs.getString("dispatchImg")));
            }

            //构建消息内容
            String detailTitle = "";
            String title = payrollTitle;//SystemEnv.getHtmlLabelName(503, user.getLanguage());
            String context = payrollTitle;

            Map<String, Object> shareMap = new HashMap<>();
            Map<String, Object> extraMap = new HashMap<>();
            String host_url = Util.null2String(Prop.getInstance().getPropValue("doc_project_url", "host_url"));
            if(!"".equals(imgId)) {
                imgId = DocDownloadCheckUtil.getDownloadfileidstr(imgId);
                String ddcode = "";
                try{
                    Map<String,String> params = new HashMap<>();
                    params.put(SystemDocUtil.TIMEOUT, "5");
                    params.put(SystemDocUtil.TIMELIMIT, "0");
                    params.put(SystemDocUtil.ADMINRIGHT, "1");
                    ddcode = SystemDocUtil.takeddcode(user, imgId, params);
                }catch(Exception e){}
                String fid = DocDownloadCheckUtil.getDownloadfileidstr(imgId);
                ImageFileManager imageFileManager = new ImageFileManager();
                imageFileManager.getImageFileInfoById(Util.getIntValue(fid, 0));
                String filename = imageFileManager.getImageFileName();
                String suffic = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
                extraMap.put("showimage", host_url + "/weaver/weaver.file.FileDownload?fileid=" + imgId + "&ddcode=" + ddcode + "&pictype=" + suffic);//图片地址
            }else
                extraMap.put("showimage", host_url + "/hrm/hrm_e9/images/payroll.jpg?pictype=jpg");//图片地址
            if(dispatchImg)
                shareMap.put("extra", extraMap);

            //实例化配置工具类
            ConfigManager manager = new ConfigManager();

            Iterator iterator = userList.iterator();
            while (iterator.hasNext()){
                //封装图片资源
                Map<String, Object> map = new HashMap<>();
                map.put("share", shareMap);

                String resourceId = String.valueOf(iterator.next());
                writeLog("sendMsg:" + resourceId);
                String key = Util.null2String(keys.get(resourceId));
                boolean isWechatUser = false;
                boolean isNotSetLoginid = false;
                if(resourceId.indexOf(":wechatid") > -1) {
                    resourceId = resourceId.replace(":wechatid", "");
                    isWechatUser = true;
                }else if(resourceId.indexOf(":userId") > -1){
                    resourceId = resourceId.replace(":userId", "");
                    isNotSetLoginid = true;
                }else{}

                //构建消息类型，消息接受人员列表
                Map<WeaMessageTypeConfig, List<String>> accessConfig = manager.defaultRuleCheckConfig(MessageType.HRM_PAYROLL, resourceId + ",0", null);

                //构建消息内容
                String linkUrl = LINKURL + targetId + "?dataEncryptId=" + key;
                String linkMobileUrl = LINKMOBILEURL + targetId + "?dataEncryptId=" + key;
                if(isWechatUser || isNotSetLoginid){
                    linkUrl += "&wechatid=" + resourceId + "&em_no_login=1" + (isNotSetLoginid ? "&notLoginid=1" : "");
                    linkMobileUrl += "&wechatid=" + resourceId + "&em_no_login=1" + (isNotSetLoginid ? "&notLoginid=1" : "");
                }

                int create = user.getUID();

                //遍历自定义消息类型集合
                for (Map.Entry<WeaMessageTypeConfig, List<String>> entry : accessConfig.entrySet()) {
                    //构建消息内容
                    MessageBean bean = Util_Message.createMessage(MessageType.HRM_PAYROLL, 0, title, detailTitle, context, linkUrl, linkMobileUrl, create, request);
                    bean.setTargetId(targetId);//消息来源code +“|”+业务id  需要修改消息状态时传入

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

                    //新的自定义消息类型相关信息通知到消息实体bean上
                    bean.setMessageConfig(config);

                    //ec中不存在的无帐号人员
                    if(isWechatUser){
                        map.put("touser", resourceId);
                    }else{
                        //设置检查配置通过需要发送消息的用户
                        bean.setUserList(Sets.newHashSet(entry.getValue()));
                    }
                    bean.setEmParams(map);

                    //发送消息
                    Util_Message.sendAndpublishMessage(bean);
                }
            }
        }catch (Exception ex){
            writeLog(ex);
        }
    }

    /**
     * 删除消息
     * @param targetId
     * @param resourceId
     */
    public void deleteMsg(String targetId, String resourceId){
        try{
            MessageBean messageBean = Util_Message.createMessage();
            Set<String> userList = new HashSet<>();
            userList.add(resourceId);
            messageBean.setUserList(userList);
            messageBean.setTargetId(targetId);
            Util_Message.delMessageTargetid(messageBean);
        }catch (Exception ex){
            writeLog(ex);
        }
    }
}
