MessageCenterBizService.java 7.56 KB
package cn.fw.hestia.service.buz;

import cn.fw.common.data.mybatis.pagination.PageData;
import cn.fw.common.page.AppPage;
import cn.fw.hestia.common.constant.MessageStr;
import cn.fw.hestia.common.utils.DateUtil;
import cn.fw.hestia.common.utils.StringUtils;
import cn.fw.hestia.component.SendMsgProducer;
import cn.fw.hestia.domain.db.MessageHistory;
import cn.fw.hestia.domain.db.SendLog;
import cn.fw.hestia.domain.enums.MessageStateEnum;
import cn.fw.hestia.domain.vo.HistoryQuery;
import cn.fw.hestia.domain.vo.MessageHistoryVO;
import cn.fw.hestia.rpc.passport.TemplateMessageService;
import cn.fw.hestia.rpc.passport.dto.TMParam;
import cn.fw.hestia.sdk.params.TemplateMessageParam;
import cn.fw.hestia.sdk.result.MessageSendMq;
import cn.fw.hestia.service.data.MessageHistoryService;
import cn.fw.hestia.service.data.SendLogService;
import cn.fw.passport.sdk.api.param.WxMpTempMessageData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static cn.fw.common.businessvalidator.Validator.BV;

/**
 * @author : kurisu
 * @className : MessageCenterBizService
 * @description : 消息中心处理类
 * @date: 2021-09-24 17:10
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MessageCenterBizService {
    private final MessageHistoryService messageHistoryService;
    private final SendLogService sendLogService;
    private final TemplateMessageService templateMessageService;
    private final SendMsgProducer sendMsgProducer;

    /**
     * 消息模板Code
     */
    @Getter
    private final String templateCode = "OPENTM412432053";

    /**
     * 发送
     *
     * @param templateMessageParam
     * @return token
     */
    @Transactional(rollbackFor = Exception.class)
    public Long saveMessage(TemplateMessageParam templateMessageParam) {
        MessageHistory messageHistory = createBean(templateMessageParam);
        messageHistoryService.save(messageHistory);
        return messageHistory.getId();
    }


    /**
     * 发送模板消息
     *
     * @param history
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendMessage(MessageHistory history) {
        TMParam tmParam = createTmParam(history);
        String result = templateMessageService.sendTemplateMessage(tmParam);
        boolean succeed = MessageStr.SUCCEED_STR.equals(result);
        final int frequency = history.getFrequency() + 1;
        history.setFrequency(frequency);
        if (succeed) {
            history.setState(MessageStateEnum.SUMI);
            //发送成功发送mq
            sendMsgProducer.send(new MessageSendMq(history.getId(), new Date()));
        } else {
            history.setSendTime(DateUtil.getExpired(history.getSendTime(), 1 << frequency, Calendar.MINUTE));
        }
        messageHistoryService.updateById(history);
        SendLog sendLog = new SendLog();
        sendLog.setMessageId(history.getId());
        sendLog.setSendTime(new Date());
        sendLog.setSucceed(succeed);
        sendLog.setResult(result);
        sendLogService.save(sendLog);
    }

    /**
     * 撤回消息
     *
     * @param sceneToken
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean revokeMessage(Long sceneToken) {
        MessageHistory history = messageHistoryService.getById(sceneToken);
        if (Objects.isNull(history)) {
            return Boolean.TRUE;
        }
        history.setYn(Boolean.FALSE);
        return messageHistoryService.updateById(history);
    }

    /**
     * 查询未读数
     *
     * @param memberId
     * @return
     */
    public int unreadCount(Long memberId) {
        return messageHistoryService.count(Wrappers.<MessageHistory>lambdaQuery()
                .eq(MessageHistory::getMemberId, memberId)
                .eq(MessageHistory::getReadz, Boolean.FALSE)
                .eq(MessageHistory::getYn, Boolean.TRUE)
        );
    }

    /**
     * 查询页面所需参数
     *
     * @param sceneToken
     * @return
     */
    public Map<String, String> queryPageParams(Long sceneToken) {
        MessageHistory history = messageHistoryService.getById(sceneToken);
        BV.notNull(history, () -> "消息不存在或者已经被撤销");
        readMessage(history);
        String pageParams = history.getPageParams();
        if (StringUtils.isEmpty(pageParams)) {
            return new HashMap<>(0);
        }
        return JSON.<HashMap<String, String>>parseObject(pageParams, HashMap.class);
    }

    /**
     * 查询历史消息记录
     * @param query
     * @return
     */
    public AppPage<MessageHistoryVO> queryHistory(HistoryQuery query) {
        PageData<MessageHistory> pageData = messageHistoryService.page(new PageData<>(query), Wrappers.<MessageHistory>lambdaQuery()
                .eq(MessageHistory::getMemberId, query.getMemberId())
                .eq(MessageHistory::getYn, Boolean.TRUE)
                .orderByDesc(MessageHistory::getCreateTime)
        );
        AppPage<MessageHistoryVO> page = AppPage.empty(query);
        page.setCurrent((int) pageData.getCurrent());
        page.setPageSize((int) pageData.getSize());
        page.setTotal(pageData.getTotal());
        page.setData(new ArrayList<>());
        if (!CollectionUtils.isEmpty(pageData.getRecords())) {
            List<MessageHistoryVO> voList = pageData.getRecords().stream().map(MessageHistoryVO::with).collect(Collectors.toList());
            page.setData(voList);
        }
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    protected void readMessage(MessageHistory history) {
        if (Boolean.FALSE.equals(history.getReadz())) {
            history.setReadz(Boolean.TRUE);
            messageHistoryService.updateById(history);
        }
    }

    private MessageHistory createBean(TemplateMessageParam param) {
        MessageHistory messageHistory = new MessageHistory();
        messageHistory.setMemberId(param.getMemberId());
        messageHistory.setTemplateCode(getTemplateCode());
        messageHistory.setTitle(param.getTitle());
        messageHistory.setRemark(param.getRemark());
        messageHistory.setPagePath(param.getPath());
        messageHistory.setReadz(Boolean.FALSE);
        messageHistory.setFrequency(0);
        messageHistory.setYn(Boolean.TRUE);
        messageHistory.setSendTime(new Date());
        messageHistory.setState(MessageStateEnum.MADA);
        List<WxMpTempMessageData> keywords = Arrays.asList(
                new WxMpTempMessageData(param.getChangeType()),
                new WxMpTempMessageData(param.getChangeResult())
        );
        messageHistory.setKeywords(JSONArray.toJSONString(keywords));
        if (!CollectionUtils.isEmpty(param.getParamMap())) {
            messageHistory.setPageParams(JSON.toJSONString(param.getParamMap()));
        }
        return messageHistory;
    }

    private TMParam createTmParam(MessageHistory history) {
        TMParam tmParam = new TMParam();
        tmParam.setSceneToken(history.getId());
        tmParam.setTitle(history.getTitle());
        tmParam.setRemark(history.getRemark());
        tmParam.setPath(history.getPagePath());
        tmParam.setTemplateCode(history.getTemplateCode());
        tmParam.setMemberId(history.getMemberId());
        tmParam.setKeywords(history.getKeywords());
        return tmParam;
    }
}