package com.elab.spring.intercept;

import com.aliyun.openservices.ons.api.SendResult;
import com.dianping.cat.Cat;
import com.elab.core.utils.DateUtils;
import com.elab.core.utils.ObjectUtils;
import com.elab.core.utils.StringUtils;
import com.elab.mq.model.MessageModel;
import com.elab.mq.model.MqProducerLogEntity;
import com.elab.mq.msg.ProducerInterceptor;
import com.elab.mq.utils.RocketMonitorUtils;
import com.elab.spring.dao.IProducerDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.net.InetAddress;

/**
 * @Module 拦截器
 * @Description rmq生产者处理
 * @Author liukaixiong
 * @Date 2020/12/30 15:36
 */
public class RMQMsgTableProducerInterceptor implements ProducerInterceptor {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired(required = false)
    private IProducerDao producerDao;

    @Value("${spring.application.name}")
    private String moduleName;

    @Value(value = "${elab.mq.GROUP_ID:}")
    private String groupId;

    @Override
    public boolean check(MessageModel messageModel, String groupName) {
        int id = insertRecordProducer(messageModel);
        messageModel.setProducerId(id + "");
        return true;
    }

    @Override
    public void success(MessageModel messageModel, String groupName, SendResult result) {
        RocketMonitorUtils.sendProducerMonitorData(messageModel, 1, -1L, null);
    }

    @Override
    public void error(MessageModel messageModel, String groupName, Throwable e) {
        updateRecordProducer(Integer.valueOf(messageModel.getProducerId()), -1, e.getMessage());
        RocketMonitorUtils.sendProducerMonitorData(messageModel, -1, -1L, e);
    }

    /**
     * 往生产者表中写入数据
     *
     * @param message
     * @return
     */
    private int insertRecordProducer(MessageModel message) {
        int id = 0;
        try {
            MqProducerLogEntity producerEntity = new MqProducerLogEntity();
            String tag = message.getTag();
            if (StringUtils.isEmpty(message.getModuleName())) {
                producerEntity.setApplicationName(moduleName);
            } else {
                producerEntity.setApplicationName(message.getModuleName());
            }
            producerEntity.setApplicationIp(InetAddress.getLocalHost().getHostAddress());
            producerEntity.setPartitionName(tag);
            producerEntity.setLogId(Cat.getCurrentMessageId());
            producerEntity.setGroupId(groupId);
            producerEntity.setInvokeStatus(1);
            producerEntity.setMsgId(message.getMsgID());
            producerEntity.setMsgKey(message.getKey());
            producerEntity.setGroupId(message.getGroupId());
            producerEntity.setTopic(message.getTopic());
            producerEntity.setCreatedTime(DateUtils.getCurrentDateTime());
            id = producerDao.insert(producerEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("往生产者表中插入记录失败：，入参：" + ObjectUtils.objectParseJsonStr(message), e);
        }
        return id;
    }

    /**
     * 修改生产者数据
     *
     * @param id
     * @param result
     * @return
     */
    private void updateRecordProducer(int id, Integer status, String result) {
        if (id <= 0) {
            logger.warn("数据插入失败，无法修改生产消息日志表");
            return;
        }
        try {
            MqProducerLogEntity producerLogEntity = producerDao.selectById(id + "");
            if (producerLogEntity != null) {
                producerLogEntity.setInvokeStatus(status);
                producerDao.updateById(producerLogEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改生产者表中记录失败：，入参：" + id, e);
        }
    }

}
