package com.zanxiang.game.data.serve.aspectj;


import com.zanxiang.erp.security.util.SecurityUtil;
import com.zanxiang.game.data.serve.annotation.Log;
import com.zanxiang.game.data.serve.mangae.AsyncManager;
import com.zanxiang.game.data.serve.mangae.factory.AsyncFactory;
import com.zanxiang.game.data.serve.pojo.dto.WebLogDTO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志切面
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            System.out.println("写入日志");

            //获取当前用户id
            Long sysUserId = SecurityUtil.getUserId();
            //标题名称
            WebLogDTO webLogDTO = new WebLogDTO();
            webLogDTO.setTitle(controllerLog.title());
            if(sysUserId!=null){
                webLogDTO.setUserId(sysUserId.toString());
            }
            LocalDateTime now = LocalDateTime.now();
            String dateTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            webLogDTO.setVisitTime(dateTime);
            // 发到kafka
            AsyncManager.me().execute(AsyncFactory.webVisitLog(webLogDTO));
        } catch (Exception exp) {
            // 记录日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

}
