package com.elab.mq.utils;

import com.aliyun.openservices.ons.api.Message;
import com.dianping.cat.Cat;
import com.elab.mq.model.MessageModel;
import com.jay.monitor.data.client.MonitorSendProducer;
import com.jay.monitor.data.client.utils.MonitorUtils;
import com.jay.monitor.data.core.enums.MQTypeEnum;
import com.jay.monitor.data.core.model.serializable.MQDataDTO;

import java.util.Date;

/**
 * @Module 工具类
 * @Description 监控工具类
 * @Author liukaixiong
 * @Date 2021/1/19 10:53
 */
public class RocketMonitorUtils {

    public static void sendConsumerMonitorData(Message data, Integer status, Throwable e) {
        sendConsumerMonitorData(data, status, -1L, e);
    }

    public static void sendConsumerMonitorData(Message data, Integer status, Long requestTime) {
        sendConsumerMonitorData(data, status, requestTime, null);
    }

    public static void sendProducerMonitorData(MessageModel data, Integer status, Long requestTime, Throwable e) {
        String content = (String) data.getObject(String.class);
        MQDataDTO mqDataDTO = MonitorUtils.builderProducerMqDataDTO(data.getTopic(), data.getKey(), data.getTag(), data.getMsgID(), content, status, e);

        mqDataDTO.setMqType(MQTypeEnum.rocketMQ.name());

        builderRemoteId(data, mqDataDTO);

        MonitorSendProducer.sendMsg(data.getTopic(), mqDataDTO);
    }

    public static void sendConsumerMonitorData(Message data, Integer status, Long requestTime, Throwable e) {
        MessageModel messageModel = new MessageModel(data);

        String content = (String) messageModel.getObject(String.class);

        MQDataDTO mqDataDTO = MonitorUtils.builderConsumerRMQDataDTO(data.getTopic(), data.getKey(), data.getTag(), data.getMsgID(), content, status, requestTime, e);

        builderRemoteId(messageModel, mqDataDTO);

        MonitorSendProducer.sendMsg(data.getTopic(), mqDataDTO);
    }

    /**
     * 构建远程编号
     *
     * @param data
     * @param mqDataDTO
     */
    private static void builderRemoteId(MessageModel data, MQDataDTO mqDataDTO) {
        String rootId = data.getUserProperties(Cat.Context.ROOT);
        String parentId = data.getUserProperties(Cat.Context.PARENT);

        mqDataDTO.setParentLogId(parentId);
        mqDataDTO.setRootLogId(rootId);
        mqDataDTO.setLogId(Cat.getCurrentMessageId());

        /////////////////// 默认的关键索引线索 ///////////////////////

        if (mqDataDTO.getGroupKeyName() == null) {
            mqDataDTO.setGroupKeyName(data.getKey());
        }

        if (mqDataDTO.getGroupName() == null) {
            mqDataDTO.setGroupName(data.getModuleName());
        }

        if (mqDataDTO.getDataId() == null) {
            mqDataDTO.setDataId(data.getProducerId());
        }

        if (mqDataDTO.getSourceTime() == null && data.getConsumerTime() != null) {
            mqDataDTO.setSourceTime(new Date(data.getConsumerTime()));
        }

    }
}
