package cn.axzo.msg.center.notices.manager.support;

import cn.axzo.msg.center.domain.entity.MNSMessageRequestLog;
import cn.axzo.msg.center.notices.common.annotation.ApiRequestLog;
import cn.axzo.msg.center.notices.manager.api.MessageRequestLogManager;
import cn.axzo.msg.center.notices.manager.api.dto.request.BaseRequestDto;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 切面日志实现类
 *
 * @author zhaoyong_sh
 * @see ApiRequestLogAspect
 * @since 2021-05-28 10:45
 */
@Aspect
@Slf4j
@Component
public class ApiRequestLogAspect {

  @Resource(name = "messageRequestLogManager")
  private MessageRequestLogManager messageRequestLogManager;

  @Around("@annotation(apiRequestLog)")
  public Object methodHandler(ProceedingJoinPoint jp, ApiRequestLog apiRequestLog) throws Throwable {
    Object[] params = jp.getArgs();
    Object param = params[0];
    Signature signature = jp.getSignature();
    // 方法名
    String methodName = signature.getName();
    // 类名
    String typeName = signature.getDeclaringType().getSimpleName();
    log.info("保存请求日志：{}.{} Begin Request : {}", typeName, methodName, JSON.toJSONString(param));
    // 保存requestLog
    BaseRequestDto baseRequestDto = BeanUtil.copyProperties(param, BaseRequestDto.class);
    MNSMessageRequestLog requestLog = new MNSMessageRequestLog();
    requestLog.setAppNo(baseRequestDto.getAppCode());
    requestLog.setRequestNo(baseRequestDto.getRequestNo());
    requestLog.setMethodName(methodName);
    requestLog.setRequestBody(JSON.toJSONString(param));
    Long requestLogId = messageRequestLogManager.saveRequestLog(requestLog);
    log.info("执行方法");
    Object result = jp.proceed();
    if(result != null) {
      messageRequestLogManager.updateRequestLog(JSON.toJSONString(result), requestLogId);
      log.info("返回Controller应答：{}", JSONUtil.toJsonStr(result));
    }
    return result;
  }

}
