package com.iformall.mq.impl;

import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.enums.EnumMsgRecordStatus;
import com.iformall.mapper.WxMsgRecordMapper;
import com.iformall.mq.MQConfig;
import com.iformall.mq.MqBaseProducer;
import com.iformall.service.WxMsgRecordService;
import com.iformall.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * @Auther: Stormeye
 * @Date: 2019-01-31
 * @Description: RocketMQ消息生产者
 */
@Service
@Profile(MQConfig.Impl.RABBIT_MQ)
public class RabbitMqMessageProducer implements MqBaseProducer , RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WxMsgRecordMapper wxMsgRecordMapper;
    @Autowired
    private WxMsgRecordService wxMsgRecordService;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("confirm:: correlationData {}，ack {}, cause {}", correlationData,ack,cause);
        if(!ack){
            try {
                BaseMsg data = new BaseMsg();
                data.setUuid(correlationData.getId());
                data.setMsgStatus(EnumMsgRecordStatus.SEND_FAIL.getCode());
                data.setStatusMessage(cause);
                wxMsgRecordMapper.updateByBaseMsg(data);
            } catch (Exception e) {
                log.error(" RabbitMqMessageProducer.confirm.updateDb Error", e);
            }
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("returnedMessage::message {} 消息发送失败，应答码：{}, 应答描述：{} ,exchange: {} ,routingKey :{}", new String(message.getBody()), replyCode, replyText, exchange, routingKey);
    }

    @Override
    public void sendMessage(BaseMsg data, String topic, String tags, String keys) {
        String uuid = UUID.randomUUID().toString();
        try {
            data.setUuid(uuid);
            wxMsgRecordService.save(data);

            CorrelationData correlationData = new CorrelationData(uuid);
            rabbitTemplate.convertAndSend(topic, (Object) JsonUtil.obj2Json(data),correlationData);
//            data.setMsgStatus(EnumMsgRecordStatus.SEND_SUCC.getCode());
//            wxMsgRecordMapper.update(data);
            log.info(data.getUuid()+"发送mq成功。");
        } catch (Exception e) {
            log.error(uuid + " RabbitMqMessageProducer: Send Message Error", e);
        }
    }

}
