package com.elab.log.ext;

import com.alibaba.fastjson.JSON;
import com.dianping.cat.Cat;
import com.elab.log.model.CatCrossIdModel;
import com.elab.log.utils.EventProcessUtils;
import com.jay.monitor.data.client.ext.MonitorRuleCallback;
import com.jay.monitor.data.core.model.serializable.base.BaseDTO;
import com.jay.monitor.data.core.model.serializable.base.TranceLogData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 消息监控规则
 *
 * @author liukaixong
 */
public class CatIdMonitorRule implements MonitorRuleCallback {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void registerRule(Map<String, BiConsumer<String, ? super BaseDTO>> ruleMap) {
        ruleMap.put(MonitorRuleCallback.allMatchRuleType, (value, mqData) -> {

            if (mqData instanceof TranceLogData) {
                TranceLogData tranceLogData = (TranceLogData)mqData;
                invokeTraceId(value, tranceLogData);
                // 这里不用get_catChildMessageId的原因是因为生产者是不确定下游的消费者是谁的。
                // 这里还是用当前线程产生的LogId。这个id非常重要。
                tranceLogData.setLogId(Cat.getCurrentMessageId());
            }

        });
    }

    private void invokeTraceId(String value, TranceLogData tranceLogData) {
        try {
            CatCrossIdModel catCrossIdModel = JSON.parseObject(value, CatCrossIdModel.class);
            if (catCrossIdModel.get_catRootMessageId() != null) {
                tranceLogData.setRootLogId(catCrossIdModel.get_catRootMessageId());
                tranceLogData.setParentLogId(catCrossIdModel.get_catParentMessageId());
            }
        } catch (Exception e) {
            logger.warn("消息处理异常" + e.getMessage() + "\t 异常的值: " + value);
            EventProcessUtils.warnMsg("CatIdMonitorRule_warn", e.getMessage() + "\t" + value);
        }
    }

    public static void main(String[] args) {
        List<CatCrossIdModel> list = new ArrayList<>();
        list.add(new CatCrossIdModel());
        String value = JSON.toJSONString(list);
        CatCrossIdModel catCrossIdModel = JSON.parseObject(value, CatCrossIdModel.class);
        System.out.println(catCrossIdModel);
    }
}