package com.shr.aop;

import com.google.gson.Gson;
import com.shr.annotion.AccessLog;
import com.shr.log.LogManager;
import com.shr.log.factory.LogTaskFactory;
import com.shr.utils.JsonUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 记录访问日志
 *
 * @author Inori
 */
@Aspect
@Component
public class LogAop {

    private Logger log = LoggerFactory.getLogger(this.getClass());


    @Pointcut(value = "@annotation(com.shr.annotion.AccessLog)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
        //先执行业务
        Object result = point.proceed();
        try {
            handle(point, result);
        } catch (Exception e) {
            log.error("日志记录错误!", e);
        }
        return result;
    }

    private void handle(ProceedingJoinPoint point, Object result) throws Exception {
        //获取拦截的方法
        Signature signature = point.getSignature();
        MethodSignature methodSignature;
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;
        Object target = point.getTarget();

        Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
        AccessLog annotation = currentMethod.getAnnotation(AccessLog.class);
        //获取操作名称
        String content = annotation.value();
        String systemType = getSystemType(point);

        LogManager.me().executeLog(LogTaskFactory.log(content, systemType, new Gson().toJson(result)));
    }

    private String getSystemType(ProceedingJoinPoint point) {
        Object[] args = point.getArgs();
        Object[] arguments = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                //ServletRequest，ServletResponse,MultipartFile不能序列化
                continue;
            }
            arguments[i] = args[i];
        }

        String systemType = "systemType";
        Map<String, Object> map = JsonUtil.toMap(JsonUtil.toString(arguments[0]), String.class, Object.class);
        if (map.containsKey(systemType)) {
            return map.get(systemType).toString();
        }
        return "";
    }


}
