package com.mortals.xhx.module.api.common;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mortals.framework.util.ThreadPool;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author luoshichao
 * @Description
 * @date 2021/3/22 15:23
 */
@Aspect
@Component
public class ApiLogAspect {
    private final static Logger logger = LoggerFactory.getLogger(ApiLogAspect.class);
    @Around("execution(public  * com.mortals.xhx.module.api.web.*Controller.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String remoteAddr = request.getRemoteAddr();
        String url = request.getRequestURL().toString();
        Object[] args = joinPoint.getArgs();
        logger.info("source ip：{}，target url：{}，args:{}",  remoteAddr, url, JSONObject.toJSONString(args,  SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty));

        Object result = joinPoint.proceed(args);
        ThreadPool.getInstance().init(8);
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                printResult(remoteAddr, url, result);
            }
        });
        return result;

    }


    void printResult( String remoteAddr, String url,Object result){

        if(result != null){
            result = JSONObject.toJSONString(result);
            logger.info("source ip：{}，target url：{}，返回结果:{}",  remoteAddr, url, result);
        }
    }
}
