package com.gic.haoban.manage.service.service.notify.out;

import static org.slf4j.LoggerFactory.getLogger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.gic.clerk.api.dto.ClerkListDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.*;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.notify.dto.NotifyMessageMQDTO;
import com.gic.haoban.manage.api.dto.notify.qdto.NotifyMessageBatchQDTO;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseRelatedApiService;
import com.gic.haoban.manage.api.util.notify.NoticeMessageUtil;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterprise;
import com.gic.haoban.manage.service.service.WxEnterpriseRelatedService;
import com.gic.haoban.manage.service.service.message.NoticeMessageHandler;
import com.gic.haoban.manage.service.util.ApolloUtils;
import com.gic.message.center.api.subscribe.model.NoticeMessageForm;
import com.gic.mq.sdk.GicMQClient;
import com.gic.wechat.api.dto.qywx.QywxTemplateCardSendMessageDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Constant;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.notify.dto.NoticeMessageInfoDTO;
import com.gic.haoban.manage.api.dto.notify.qdto.NoticeMessageQDTO;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.haoban.manage.api.service.notify.NoticeMessageApiService;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.TabHaobanStaff;
import com.gic.haoban.manage.service.errorcode.HaoBanErrCode;
import com.gic.haoban.manage.service.pojo.bo.NoticeMessageBO;
import com.gic.haoban.manage.service.pojo.bo.TemplateContentBO;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.service.StaffService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.notify.NoticeMessageService;
import com.gic.haoban.manage.service.service.notify.NoticeMessageTemplateService;
import com.gic.wechat.api.dto.qywx.ItemDTO;
import com.gic.wechat.api.dto.qywx.QywxXcxSendMessageDTO;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;

/**
 * Created 2021/12/17.
 *
 * @author hua
 */
@Service
public class NoticeMessageApiServiceImpl implements NoticeMessageApiService {

    private static final Logger logger = getLogger(NoticeMessageApiServiceImpl.class);

    @Autowired
    private NoticeMessageTemplateService noticeMessageTemplateService;

    @Autowired
    private Config config;

    @Autowired
    private StaffClerkRelationService staffClerkRelationService;

    @Autowired
    private NoticeMessageService noticeMessageService;

    @Autowired
    private QywxSuiteApiService qywxSuiteApiService;

    @Autowired
    private WxEnterpriseService wxEnterpriseService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private WxEnterpriseRelatedService wxEnterpriseRelatedService;

    @Autowired
    private ClerkService clerkService;

    @Autowired
    private NoticeMessageHandler noticeMessageHandler;

    /*消息中心修改此处
    @Override*/
    public void noticeMessageMq_old(String json) {
        logger.info("通知消息：{}", json);
        NoticeMessageQDTO messageQDTO = JSONObject.parseObject(json, NoticeMessageQDTO.class);
        NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(messageQDTO.getMessageType());
        if (messageTypeEnum == null) {
            logger.error("无消息模板：{}", json);
            return;
        }
        messageQDTO.setTemplateCode(messageTypeEnum.getTemplateCode());
        //企业微信模板
        List<TemplateContentBO> contentList = getDescriotion(messageQDTO);
        //好办模板
        String haobanNotice = getHaobanNotice(messageQDTO);
        //模板不存在
        if (CollectionUtils.isEmpty(contentList) || StringUtils.isBlank(haobanNotice)) {
            logger.info("没有模板，无法发送消息：{}", messageQDTO.getTemplateCode());
            return;
        }
        String staffId = null;
        String wxEnterpriseId = null;
        StaffClerkRelationDTO clerkRelationDTO = null;
        if (StringUtils.isNotBlank(messageQDTO.getStaffId())) {
            TabHaobanStaff haobanStaff = staffService.selectById(messageQDTO.getStaffId());
            staffId = haobanStaff != null ? haobanStaff.getStaffId() : null;
            wxEnterpriseId = haobanStaff != null ? haobanStaff.getWxEnterpriseId() : null;
        }
        if (StringUtils.isNotEmpty(messageQDTO.getClerkId())) {
            clerkRelationDTO = staffClerkRelationService.getByClerkId(messageQDTO.getClerkId());
        }
        if (staffId == null && clerkRelationDTO == null) {
            logger.info("没有导购：{}", messageQDTO.getClerkId());
            return;
        }
        staffId = (staffId == null ? clerkRelationDTO.getStaffId() : staffId);
        wxEnterpriseId = (wxEnterpriseId == null ? clerkRelationDTO.getWxEnterpriseId() : wxEnterpriseId);

        //消息组装 新增消息
        NoticeMessageBO noticeMessageBO = new NoticeMessageBO();
        noticeMessageBO.setCategoryType(messageTypeEnum.getCategory());
        noticeMessageBO.setMessageType(messageQDTO.getMessageType());
        noticeMessageBO.setClerkId(messageQDTO.getClerkId() != null ? messageQDTO.getClerkId() : "-1");
        noticeMessageBO.setStoreId(clerkRelationDTO != null ? clerkRelationDTO.getStoreId() : "-1");
        noticeMessageBO.setTitle(StringUtils.isNotBlank(messageQDTO.getTitle()) ? messageQDTO.getTitle() : messageTypeEnum.getName());
        noticeMessageBO.setTemplateCode(messageTypeEnum.getTemplateCode());
        noticeMessageBO.setDescription(haobanNotice);
        noticeMessageBO.setEnterpriseId(messageQDTO.getEnterpriseId());
        noticeMessageBO.setRelationId(messageQDTO.getOptTargetId());
        noticeMessageBO.setMessageContent(messageQDTO.getExtendContent() != null ? JSONObject.toJSONString(messageQDTO.getExtendContent()) : null);
        noticeMessageService.addOrCreateNoticeMessage(noticeMessageBO);
        //发送企业微信
        sendMessage(contentList, wxEnterpriseId, staffId, messageTypeEnum, noticeMessageBO.getMessageContent(), messageQDTO.getTitle());
    }

    @Override
    public void noticeMessageMq(String json) {

        if (!ApolloUtils.useMessageCenter()) {
            logger.info("消息中心-走老版消息通知");
            this.noticeMessageMq_old(json);
            return;
        }
        NoticeMessageQDTO messageQDTO = JSONObject.parseObject(json, NoticeMessageQDTO.class);
        logger.info("messageType:{},消息中心测试通知消息：{}", messageQDTO.getMessageType(), json);
        String staffId = null;
        StaffClerkRelationDTO clerkRelationDTO = null;
        if (StringUtils.isNotBlank(messageQDTO.getStaffId())) {

            TabHaobanStaff haobanStaff = staffService.selectById(messageQDTO.getStaffId());
            staffId = haobanStaff != null ? haobanStaff.getStaffId() : null;
        }
        if (StringUtils.isNotEmpty(messageQDTO.getClerkId())) {
            clerkRelationDTO = staffClerkRelationService.getByClerkId(messageQDTO.getClerkId());
        }
        if (staffId == null && clerkRelationDTO == null) {
            logger.info("没有导购：{}", messageQDTO.getClerkId());
            return;
        }

        try {

            Map<String, String> variableMap = ObjectUtil.isNotNull(messageQDTO.getContentMap()) ? messageQDTO.getContentMap() : new HashMap<>();

            if (ObjectUtil.isNotEmpty(messageQDTO.getExtendContent())) {
                variableMap.put("pageParams", JSONObject.toJSONString(messageQDTO.getExtendContent()));
            }

            if (ObjectUtil.isNotEmpty(messageQDTO.getTitle())) {
                variableMap.put("templateTitle", messageQDTO.getTitle());
            }


            NoticeMessageTypeEnum noticeMessageTypeEnum = NoticeMessageTypeEnum.getByType(messageQDTO.getMessageType());
            if (ObjectUtil.isNull(noticeMessageTypeEnum)) {
                return;
            }
            NoticeMessageForm build = NoticeMessageForm.builder()
                    .messageCode(noticeMessageTypeEnum.getMessageCode())
                    .mqRouterCode(noticeMessageTypeEnum.getRouterCode())
                    .businessId(messageQDTO.getOptTargetId())
                    .createTime(new Date())
                    .enterpriseId(messageQDTO.getEnterpriseId())
                    .uniqueKey(UniqueIdUtils.uniqueLongHex())
                    .variableMap(variableMap).build();
            if (clerkRelationDTO != null) {
                build.setUserIdList(Collections.singletonList(clerkRelationDTO.getClerkId()));
            } else {
                build.setStaffIdList(Collections.singletonList(staffId));
            }
            noticeMessageHandler.sendMessage(build);
        } catch (Exception e) {
            logger.error("发送消息通知失败", e);
        }

    }

    @Override
    public void run(String json) {
        this.noticeMessageMq(json);
    }

    @Override
    public void noticeMessageBatchMq(String json) {
        NotifyMessageBatchQDTO notifyMessageBatchQDTO = JSONObject.parseObject(json, NotifyMessageBatchQDTO.class);
        if (!ApolloUtils.useMessageCenter()) {
            logger.info("消息中心-走老版消息通知");
            this.batchSendMessage_old(notifyMessageBatchQDTO);
            return;
        }
        batchSendMessage(notifyMessageBatchQDTO);
    }

    /*消息中心修改此处
    @Override*/
    public ServiceResponse<Void> batchSendMessage_old(NotifyMessageBatchQDTO notifyMessageBatchQDTO) {
        String enterpriseId = notifyMessageBatchQDTO.getEnterpriseId();
        List<String> storeIdList = notifyMessageBatchQDTO.getStoreIdList();
        if (CollectionUtils.isEmpty(storeIdList)) {
            logger.info("门店列表为空");
            return ServiceResponse.success();
        }
        int count = wxEnterpriseRelatedService.getRelationCount(enterpriseId);
        if (count == 0) {
            logger.info("商户未关联好办或都已停用enterpriseId={}", enterpriseId);
            return ServiceResponse.success();
        }
        List<TabHaobanWxEnterprise> wxEnterpriseList = wxEnterpriseRelatedService.listByEnterpriseId(enterpriseId);
        List<String> wxEnterpriseIdList = wxEnterpriseList.stream().map(TabHaobanWxEnterprise::getWxEnterpriseId).collect(Collectors.toList());
        List<String> clerkIdList = clerkService.getclerkListByStoreIds(storeIdList);
        if (CollectionUtils.isEmpty(clerkIdList)) {
            logger.info("门店导购列表为空");
            return ServiceResponse.success();
        }
        List<StaffClerkRelationDTO> relationList = staffClerkRelationService.listByClerkIds(clerkIdList);
        if (CollectionUtils.isEmpty(relationList)) {
            logger.info("成员关联列表为空");
            return ServiceResponse.success();
        }
        NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(notifyMessageBatchQDTO.getMessageType());
        if (messageTypeEnum == null) {
            logger.error("无消息模板：{}", JSON.toJSONString(notifyMessageBatchQDTO));
            return ServiceResponse.success();
        }
        notifyMessageBatchQDTO.setTemplateCode(messageTypeEnum.getTemplateCode());
        Map<String, List<StaffClerkRelationDTO>> map = relationList.stream().filter(x -> wxEnterpriseIdList.contains(x.getWxEnterpriseId())).collect(Collectors.groupingBy(StaffClerkRelationDTO::getWxEnterpriseId));
        map.forEach((wxEnterpriseId, v) -> {
            WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
            if (qwDTO == null) {
                logger.info("企业为空:{}", wxEnterpriseId);
                return;
            }
            // 用于成员去重
            Set<String> userIdSet = new HashSet<>();
            List<List<StaffClerkRelationDTO>> listList = ListUtil.split(v, 1000);
            for (List<StaffClerkRelationDTO> list : listList) {
                try {
                    sendMessage(notifyMessageBatchQDTO, list, userIdSet, qwDTO);
                } catch (Exception e) {
                    logger.error("发送消息通知失败", e);
                }
            }
        });
        return ServiceResponse.success();
    }


    @Override
    public ServiceResponse<Void> batchSendMessage(NotifyMessageBatchQDTO notifyMessageBatchQDTO) {
        logger.info("消息中心测试通知消息：{}", JSONObject.toJSONString(notifyMessageBatchQDTO));
        String enterpriseId = notifyMessageBatchQDTO.getEnterpriseId();
        List<String> storeIdList = notifyMessageBatchQDTO.getStoreIdList();
        List<String> clerkIdList = notifyMessageBatchQDTO.getClerkIdList();
        int count = wxEnterpriseRelatedService.getRelationCount(enterpriseId);
        if (count == 0) {
            logger.info("商户未关联好办或都已停用enterpriseId={}", enterpriseId);
            return ServiceResponse.success();
        }
        if (CollectionUtils.isEmpty(clerkIdList)) {
            if (CollectionUtils.isEmpty(storeIdList)) {
                logger.info("门店列表为空");
                return ServiceResponse.success();
            }

            clerkIdList = clerkService.getclerkListByStoreIds(storeIdList);
        }
        if (CollectionUtils.isEmpty(clerkIdList)) {
            logger.info("门店导购列表为空");
            return ServiceResponse.success();
        }

        List<StaffClerkRelationDTO> relationList = staffClerkRelationService.listByClerkIds(clerkIdList);
        if (CollectionUtils.isEmpty(relationList)) {
            logger.info("成员关联列表为空");
            return ServiceResponse.success();
        }

        try {

            //TODO 这里有个回调未处理

            Map<String, String> variableMap = notifyMessageBatchQDTO.getContentMap();

            variableMap.put("pageParams", JSONObject.toJSONString(notifyMessageBatchQDTO.getExtendContent()));
            variableMap.put("extendContent", JSONObject.toJSONString(notifyMessageBatchQDTO.getExtendContent()));
            variableMap.put("templateTitle", notifyMessageBatchQDTO.getTitle());
            NoticeMessageTypeEnum noticeMessageTypeEnum = NoticeMessageTypeEnum.getByType(notifyMessageBatchQDTO.getMessageType());
            if (ObjectUtil.isNull(noticeMessageTypeEnum)) {
                return ServiceResponse.failure("-1", "模版枚举不存在");
            }
            List<String> userIdList = relationList.stream().map(StaffClerkRelationDTO::getClerkId).distinct().collect(Collectors.toList());
            List<List<String>> listList = ListUtil.split(userIdList, 1000);
            for (List<String> list : listList) {
                noticeMessageHandler.sendMessage(NoticeMessageForm.builder()
                        .messageCode(noticeMessageTypeEnum.getMessageCode())
                        .mqRouterCode(noticeMessageTypeEnum.getRouterCode())
                        .businessId(notifyMessageBatchQDTO.getOptTargetId())
                        .createTime(new Date())
                        .enterpriseId(notifyMessageBatchQDTO.getEnterpriseId())
                        .uniqueKey(UniqueIdUtils.uniqueLongHex())
                        .userIdList(list)
                        .variableMap(variableMap).build());
            }
        } catch (Exception e) {
            logger.error("发送消息通知失败", e);
        }

        return ServiceResponse.success();
    }

    private String getUrlParams(Map<String, Object> extendContent) {
        String data = extendContent != null ? JSONObject.toJSONString(extendContent) : null;

        if (StringUtils.isNotBlank(data)) {
            try {
                data = URLEncoder.encode(data, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        }
        return data;
    }

    private void sendMessage(NotifyMessageBatchQDTO notifyMessageBatchQDTO, List<StaffClerkRelationDTO> list, Set<String> userIdSet, WxEnterpriseQwDTO qwDTO) {

        //企业微信模板
        List<TemplateContentBO> contentList = getDescriotion(notifyMessageBatchQDTO);
        //好办模板
        String haobanNotice = getHaobanNotice(notifyMessageBatchQDTO);
        //模板不存在
        if (CollectionUtils.isEmpty(contentList) || StringUtils.isBlank(haobanNotice)) {
            logger.info("没有模板，无法发送消息：{}", notifyMessageBatchQDTO.getTemplateCode());
            return;
        }
        NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(notifyMessageBatchQDTO.getMessageType());
        if (messageTypeEnum == null) {
            logger.error("无消息模板：{}", JSON.toJSONString(notifyMessageBatchQDTO));
            return;
        }
        List<String> wxUserIdList = new ArrayList<>();
        List<NoticeMessageBO> noticeMessageBOList = new ArrayList<>();
        for (StaffClerkRelationDTO relationDTO : list) {
            String wxUserId = relationDTO.getQwUserId();
            if (qwDTO.needOpenUserId3th()) {
                wxUserId = relationDTO.getOpenUserId();
            }
            if (userIdSet.add(wxUserId)) {
                wxUserIdList.add(wxUserId);
            }
            //消息组装 新增消息
            NoticeMessageBO noticeMessageBO = new NoticeMessageBO();
            noticeMessageBO.setCategoryType(messageTypeEnum.getCategory());
            noticeMessageBO.setMessageType(notifyMessageBatchQDTO.getMessageType());
            noticeMessageBO.setClerkId(relationDTO.getClerkId() != null ? relationDTO.getClerkId() : "-1");
            noticeMessageBO.setStoreId(relationDTO.getStoreId() != null ? relationDTO.getStoreId() : "-1");
            noticeMessageBO.setTitle(StringUtils.isNotBlank(notifyMessageBatchQDTO.getTitle()) ? notifyMessageBatchQDTO.getTitle() : messageTypeEnum.getName());
            noticeMessageBO.setTemplateCode(messageTypeEnum.getTemplateCode());
            noticeMessageBO.setDescription(haobanNotice);
            noticeMessageBO.setEnterpriseId(notifyMessageBatchQDTO.getEnterpriseId());
            noticeMessageBO.setRelationId(notifyMessageBatchQDTO.getOptTargetId());
            noticeMessageBO.setMessageContent(notifyMessageBatchQDTO.getExtendContent() != null ? JSONObject.toJSONString(notifyMessageBatchQDTO.getExtendContent()) : null);
            noticeMessageBOList.add(noticeMessageBO);
        }
        noticeMessageService.addNoticeMessageBatch(noticeMessageBOList);

        QywxTemplateCardSendMessageDTO messageDTO = new QywxTemplateCardSendMessageDTO();
        String data = notifyMessageBatchQDTO.getExtendContent() != null ? JSONObject.toJSONString(notifyMessageBatchQDTO.getExtendContent()) : null;
        String title = StringUtils.isNotBlank(notifyMessageBatchQDTO.getTitle()) ? notifyMessageBatchQDTO.getTitle() : messageTypeEnum.getName();
        if (StringUtils.isNotBlank(data)) {
            try {
                data = URLEncoder.encode(data, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        }
        String appUrl = messageTypeEnum.getPageUrl();
        if (StringUtils.isNotBlank(messageTypeEnum.getPageType())) {
            appUrl += messageTypeEnum.getPageType();
        }
        appUrl += "&data=" + data;
        messageDTO.setAppid(qwDTO.getHbWxaAppid());
        messageDTO.setAgentId(Integer.parseInt(qwDTO.getAgentId()));
        messageDTO.setAgentName(qwDTO.getAgentName());
        messageDTO.setUserIds(wxUserIdList);
        messageDTO.setPage(appUrl);
        messageDTO.setTitle(StringUtils.isNotBlank(title) ? title : messageTypeEnum.getName());
        messageDTO.setContent(contentList.get(0).getVal());
        boolean sendMessage = qywxSuiteApiService.sendMessage(qwDTO.getThirdCorpid(), qwDTO.getSelf3thSecret(), messageDTO, qwDTO.isSelf(), qwDTO.getUrlHost());
        NotifyMessageMQDTO mqdto = new NotifyMessageMQDTO();
        List<String> clerkIdList = list.stream().map(StaffClerkRelationDTO::getClerkId).collect(Collectors.toList());
        mqdto.setClerkIdList(clerkIdList);
        mqdto.setEnterpriseId(notifyMessageBatchQDTO.getEnterpriseId());
        mqdto.setTemplateCode(messageTypeEnum.getTemplateCode());
        mqdto.setExtendContent(notifyMessageBatchQDTO.getExtendContent());
        mqdto.setResult(sendMessage ? Constant.FLAG_TRUE : Constant.FLAG_FALSE);
        try {
            GICMQClientUtil.getClientInstance().sendMessage("haobanNotifyEvent", JSON.toJSONString(mqdto));
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
    }

    @Override
    public ServiceResponse<Page<NoticeMessageInfoDTO>> pageNoticeMessage(String enterpriseId, String storeId, String clerkId, int categoryType, BasePageInfo pageInfo) {
        if (StringUtils.isAnyBlank(enterpriseId, storeId)) {
            return ServiceResponse.failure(HaoBanErrCode.ERR_0001.getCode(), HaoBanErrCode.ERR_0001.getMsg());
        }
        Page<NoticeMessageBO> retPage = noticeMessageService.pageNoticeMessage(enterpriseId, storeId, clerkId, categoryType, pageInfo);
        Page<NoticeMessageInfoDTO> tPage = PageHelperUtils.changePageToCurrentPage(retPage, NoticeMessageInfoDTO.class);
        if (retPage != null && CollectionUtils.isNotEmpty(tPage.getResult())) {
            tPage.getResult().forEach(mid -> {
                NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(mid.getMessageType());
                mid.setPageType(messageTypeEnum.getPageType());
            });
        }
        return ServiceResponse.success(tPage);
    }

    @Override
    public ServiceResponse<Integer> countUnReadNoticeMessage(String enterpriseId, String storeId, String clerkId) {
        int count = noticeMessageService.countUnreadNoticeMessage(enterpriseId, storeId, clerkId);
        return ServiceResponse.success(count);
    }

    @Override
    public ServiceResponse<Boolean> updateReadFlagById(Long id) {
        NoticeMessageBO noticeMessageBO = new NoticeMessageBO();
        noticeMessageBO.setNoticeMessageId(id);
        noticeMessageBO.setReadFlag(Constant.NUMBER_1);
        noticeMessageService.addOrCreateNoticeMessage(noticeMessageBO);
        return ServiceResponse.success(true);
    }

    @Override
    public ServiceResponse<Boolean> updateWriteFlagByClerkId(String enterpriseId, String clerkId, int categoryType) {
        noticeMessageService.updateNoticeMessageReadFlag(enterpriseId, clerkId, categoryType);
        return ServiceResponse.success(true);
    }

    @Override
    public ServiceResponse<Boolean> addOrCreateNoticeMessage(List<com.gic.haoban.manage.api.dto.qdto.NoticeMessageQDTO> qdto) {

        noticeMessageService.addNoticeMessageBatch(EntityUtil.changeEntityListByJSON(NoticeMessageBO.class, qdto));
        return ServiceResponse.success();
    }

    /**
     * 获取详情
     *
     * @param messageQDTO
     * @return
     */
    private List<TemplateContentBO> getDescriotion(NoticeMessageQDTO messageQDTO) {
        List<TemplateContentBO> templateMessage = noticeMessageTemplateService.getQywxTemplateMessage(messageQDTO.getEnterpriseId(), messageQDTO.getTemplateCode());
        if (CollectionUtils.isEmpty(templateMessage)) {
            logger.info("不存在模板");
            return null;
        }

        //需要替换的数据
        Map<String, String> contentMap = messageQDTO.getContentMap();
        if (MapUtils.isEmpty(contentMap)) {
            return templateMessage;
        }

        //替换的内容
        for (TemplateContentBO templateContentBO : templateMessage) {
            contentMap.forEach((k, v) -> {
                templateContentBO.setVal(templateContentBO.getVal().replaceAll("\\#\\{" + k + "\\}", v));
            });
        }
        return templateMessage;
    }


    /**
     * 获取详情好办的通知
     *
     * @param messageQDTO
     * @return
     */
    private String getHaobanNotice(NoticeMessageQDTO messageQDTO) {
        final String[] haobanTemplateMessage = {noticeMessageTemplateService.getHaobanTemplateMessage(messageQDTO.getEnterpriseId(), messageQDTO.getTemplateCode())};
        if (StringUtils.isBlank(haobanTemplateMessage[0])) {
            logger.info("不存在好办的通知模板模板");
            return null;
        }
        //需要替换的数据
        Map<String, String> contentMap = messageQDTO.getContentMap();
        if (MapUtils.isEmpty(contentMap)) {
            return haobanTemplateMessage[0];
        }
        //替换的内容
        contentMap.forEach((k, v) -> {
            haobanTemplateMessage[0] = haobanTemplateMessage[0].replaceAll("\\#\\{" + k + "\\}", v);
        });
        return haobanTemplateMessage[0];
    }

    /**
     * 发送消息
     *
     * @param contentList
     * @param
     * @param messageTypeEnum
     */
    private void sendMessage(List<TemplateContentBO> contentList, String wxEnterpriseId, String staffId, NoticeMessageTypeEnum messageTypeEnum, String data, String title) {
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        QywxXcxSendMessageDTO messageDTO = new QywxXcxSendMessageDTO();
        String corpid = qwDTO.getThirdCorpid();
        TabHaobanStaff tabHaobanStaff = staffService.selectById(staffId);
        if (tabHaobanStaff == null) {
            logger.error("未查询到员工：staffId:{}", staffId);
            return;
        }
        String wxUserId = tabHaobanStaff.getWxUserId();
        if (qwDTO.needOpenUserId3th()) {
            wxUserId = tabHaobanStaff.getWxOpenUseId();
        }
        List<ItemDTO> items = contentList.stream().map(bo -> {
            ItemDTO item = new ItemDTO();
            item.setKey(bo.getKey());
            item.setValue(bo.getVal());
            return item;
        }).collect(Collectors.toList());
        if (StringUtils.isNotBlank(data)) {
            try {
                data = URLEncoder.encode(data, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        }
        String appUrl = messageTypeEnum.getPageUrl();
        if (StringUtils.isNotBlank(messageTypeEnum.getPageType())) {
            appUrl += messageTypeEnum.getPageType();
        }
        appUrl += "&data=" + data;

        List<String> userList = new ArrayList<>();
        userList.add(wxUserId);
        messageDTO.setAppid(qwDTO.getHbWxaAppid());
        messageDTO.setUserIds(userList);
        messageDTO.setPage(appUrl);
        messageDTO.setTitle(StringUtils.isNotBlank(title) ? title : messageTypeEnum.getName());
        messageDTO.setItems(items);
        qywxSuiteApiService.sendMessage(corpid, qwDTO.getSelf3thSecret(), messageDTO, qwDTO.isSelf(), qwDTO.getUrlHost());
    }

    public void sendMessageForOpenStaff(String enterpriseId, String accountName, String reason) {
        Map<String, String> map = new HashMap<>();
        map.put("accountName", accountName);
        map.put("errorTime", DateUtil.dateToStr(new Date(), "yyyy年MM月dd日 HH:mm"));
        map.put("reason", reason);
        String mqName = "haobanNotice";
        NoticeMessageForm noticeMessageForm = new NoticeMessageForm();
        noticeMessageForm.setMessageCode("haobanOpenStaffNotice");
        noticeMessageForm.setMqRouterCode(mqName);
        noticeMessageForm.setEnterpriseId(enterpriseId);
        noticeMessageForm.setBusinessId(ToolUtil.randomUUID());
        noticeMessageForm.setUniqueKey(UniqueIdUtils.uniqueLongHex());
        noticeMessageForm.setUserIdList(null);
        noticeMessageForm.setCreateTime(new Date());
        noticeMessageForm.setVariableMap(map);
        try {
            GicMQClient client = GICMQClientUtil.getClientInstance();
            client.sendMessage(mqName, JSON.toJSONString(noticeMessageForm));
        } catch (Exception e) {
            logger.error("路由规则名称：" + mqName + ",message:" + JSON.toJSONString(noticeMessageForm), e);
        }
    }

}
