package com.qmth.teachcloud.cas.aspect;

import com.qmth.boot.api.exception.ApiException;
import com.qmth.teachcloud.exchange.common.contant.SystemConstant;
import com.qmth.teachcloud.exchange.common.util.JacksonUtil;
import com.qmth.teachcloud.exchange.common.util.ResultUtil;
import com.qmth.teachcloud.exchange.common.util.ServletUtil;
import org.aspectj.lang.ProceedingJoinPoint;
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.validation.BeanPropertyBindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Description: api aspect
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/5/12
 */
@Aspect
@Component
public class ApiCasControllerAspect {
    private final static Logger log = LoggerFactory.getLogger(ApiCasControllerAspect.class);

    /**
     * api切入点
     */
    @Pointcut("execution(public * com.qmth.teachcloud.cas.api.*.*(..))")
    public void apiAspect() {
    }

    /**
     * 后台环绕切入
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around(value = "apiAspect()")
    public Object aroundApiPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        StringJoiner stringJoiner = new StringJoiner("");
        try {
            MethodSignature msig = (MethodSignature) joinPoint.getSignature();
            String className = msig.getDeclaringTypeName();
            String methodName = msig.getName();
            Object[] args = joinPoint.getArgs();
            String[] paramsName = msig.getParameterNames();
            HttpServletRequest request = ServletUtil.getRequest();
            stringJoiner.add("============请求地址============:").add(request.getServletPath()).add("\r\n");
            stringJoiner.add("============类============:").add(className).add("\r\n");
            stringJoiner.add("============方法============:").add(methodName).add("\r\n");
            if (Objects.nonNull(args) && args.length > 0) {
                for (int i = 0; i < args.length; i++) {
                    if (Objects.nonNull(args[i]) && (args[i] instanceof HttpServletRequest || args[i] instanceof HttpServletResponse || args[i] instanceof CommonsMultipartFile || args[i] instanceof MultipartFile || args[i] instanceof BeanPropertyBindingResult)) {
                        continue;
                    } else {
                        stringJoiner.add("参数key:").add(JacksonUtil.parseJson(paramsName[i])).add(",参数value:").add(JacksonUtil.parseJson(args[i])).add("\r\n");
                    }
                }
            }
            return joinPoint.proceed();
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof ApiException) {
                return ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                return ResultUtil.error(e.getMessage());
            }
        } finally {
            long end = System.currentTimeMillis();
            stringJoiner.add("============耗时============:").add((end - start) / 1000 + "").add("秒");
            log.info("request:{}", stringJoiner.toString());
        }
    }
}