package com.qmth.themis.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dao.TMRocketMessageMapper;
import com.qmth.themis.business.dto.MqDto;
import com.qmth.themis.business.entity.TMRocketMessage;
import com.qmth.themis.business.service.TMRocketMessageService;
import com.qmth.themis.business.util.JacksonUtil;
import com.qmth.themis.business.util.RedisUtil;
import com.qmth.themis.common.util.GsonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description: rocketmq消息 服务实现类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/9
 */
@Service
public class TMRocketMessageServiceImpl extends ServiceImpl<TMRocketMessageMapper, TMRocketMessage> implements TMRocketMessageService {

    @Resource
    RedisUtil redisUtil;

    /**
     * @param mqDto
     * @param key
     */
    @Override
    public void saveMqMessageSuccess(MqDto mqDto, String key) {
        mqDto.setAck(SystemConstant.STANDARD_ACK_TYPE);
        this.saveMessage(mqDto, key);
    }

    /**
     * 保存mq出错消息
     *
     * @param mqDto
     * @param key
     */
    @Override
    public void saveMqMessageError(MqDto mqDto, String key) {
        mqDto.setAck(SystemConstant.POSION_ACK_TYPE);
        this.saveMessage(mqDto, key);
    }

    /**
     * 保存消息
     *
     * @param mqDto
     * @param key
     */
    protected void saveMessage(MqDto mqDto, String key) {
        TMRocketMessage tmRocketMessage = GsonUtil.fromJson(GsonUtil.toJson(mqDto), TMRocketMessage.class);
        tmRocketMessage.setBody(JacksonUtil.parseJson(tmRocketMessage.getBody()));
//        tmRocketMessage.setSourceId(tmRocketMessage.getId());
//        tmRocketMessage.setId(SystemConstant.getNanoId());
        this.saveOrUpdate(tmRocketMessage);
        redisUtil.delete(key, mqDto.getId());
    }
}
