package com.huatek.busi.common.aop;

import com.alibaba.dubbo.config.annotation.Reference;
import com.huatek.frame.base.entity.RequestLog;
import com.huatek.frame.base.service.RequestLogService;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.frame.base.util.IpUtil;
import com.huatek.frame.base.vo.WebLog;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 统一日志处理切面
 */
@Aspect
@Component
public class WebLogAspect {

    @Reference(check = false)
    RequestLogService requestLogService;

    @Pointcut("execution(public * com.huatek.busi..controller..*.*(..))")
    public void webLog() {
    }

    @After(value = "webLog()")
    public void doAround(JoinPoint joinPoint) {
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        WebLog webLog = new WebLog();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation log = method.getAnnotation(ApiOperation.class);
            webLog.setModelName(log.value());
        }

        webLog.setRequestUrl(request.getRequestURL().toString());
        webLog.setRequestMethod(request.getMethod());
        webLog.setIpAddress(IpUtil.getIPAddress(request));
        webLog.setParam(Arrays.toString(joinPoint.getArgs()));
        webLog.setMethodName(method.getName());

        RequestLog requestLog = new RequestLog();
        BeanUtils.copyProperties(webLog, requestLog);
        Runnable runnable = () -> requestLogService.addLogs(requestLog);
        new Thread(runnable).start();
    }
}
