package com.cool.store.mq;


import com.aliyun.openservices.ons.api.Constants;
import com.aliyun.openservices.ons.api.Message;
import com.cool.store.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * 切面处理类，操作日志异常日志记录处理
 * @author jiangjixiang
 */
@Aspect
@Component
@Slf4j
public class RocketMqLogAspect {


    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut(value = "execution(public * com.cool.store.mq.consumer.listener..*.consume(..))")
    public void rocketMqMdc() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @Before(value = "rocketMqMdc()")
    public void mqBeforeLog(JoinPoint joinPoint) {
        try {
            Object[] args = joinPoint.getArgs();
            Message message = (Message)args[0];
            String traceId = message.getMsgID() + Constants.TOPIC_PARTITION_SEPARATOR + message.getReconsumeTimes();
            String requestId = message.getUserProperties(CommonConstants.REQUEST_ID);
            MDC.put(CommonConstants.REQUEST_ID, requestId);
            MDC.put(CommonConstants.MESSAGE_ID, traceId);
        } catch (IllegalArgumentException e) {
            log.info("MDC mqBeforeLog", e);
        }
    }


    @AfterReturning(value = "rocketMqMdc()")
    public void doAfterReturning(JoinPoint joinPoint){
        try {
            MDC.clear();
        } catch (Exception e) {
            log.info("MDC doAfterReturning", e);
        }
    }
}