package com.heketai.website.config.aspect;


import com.heketai.website.common.result.BaseResult;
import com.heketai.website.common.utils.MyStringUtils;
import com.heketai.website.common.utils.TokenByGetName;
import com.heketai.website.entity.LogOperational;
import com.heketai.website.service.ILogOperationalService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class ServiceLogAspect {

    public static final Logger log =
            LoggerFactory.getLogger(ServiceLogAspect.class);

    @Resource
    private ILogOperationalService logOperationalService;


    /*
     * AOP通知：
     * 1. 前置通知：在方法调用之前执行
     * 2. 后置通知：在方法正常调用之后执行
     * 3. 环绕通知：在方法调用之前和之后，都分别可以执行的通知
     * 4. 异常通知：如果在方法调用过程中发生异常，则通知
     * 5. 最终通知：在方法调用之后执行
     */

    /**
     * 切面表达式：
     * execution 代表所要执行的表达式主体
     * 第一处 * 代表方法返回类型 *代表所有类型
     * 第二处 包名代表aop监控的类所在的包
     * 第三处 .. 代表该包以及其子包下的所有类方法
     * 第四处 * 代表类名，*代表所有类
     * 第五处 *(..) *代表类中的方法名，(..)表示方法中的任何参数
     *
     *  param joinPoint
     *  return
     *  throws Throwable
     */
    @Around("execution(* com.heketai.website.web..*.*(..))")
    @Profile({"dev", "test"})
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {

        log.info("====== 开始执行 {}.{} ======",
                joinPoint.getTarget().getClass(),
                joinPoint.getSignature().getName());

        // 记录开始时间
        long begin = System.currentTimeMillis();

        // 执行目标 service
        Object result = joinPoint.proceed();

        // 记录结束时间
        long end = System.currentTimeMillis();
        long takeTime = end - begin;

        if (takeTime > 3000) {
            log.error("====== 执行结束，耗时：{} 毫秒 ======", takeTime);
        } else if (takeTime > 2000) {
            log.warn("====== 执行结束，耗时：{} 毫秒 ======", takeTime);
        } else {
            log.info("====== 执行结束，耗时：{} 毫秒 ======", takeTime);
        }

        return result;
    }

    @AfterReturning(pointcut ="execution(* com.heketai.website.web..*.*(..))",
            returning = "returnValue")
    @Transactional(propagation = Propagation.REQUIRED)
    public void log(JoinPoint point, Object returnValue) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            return;
        }
        String name = TokenByGetName.getName(token);
        if (StringUtils.isBlank(name)){
            return ;
        }
        BaseResult baseResult =null;
        try {
             baseResult = (BaseResult) returnValue;
        }catch (Exception e){
            return;
        }
        LogOperational logOperational = new LogOperational();
        String requestURI = request.getRequestURI();

        try {
            if ("200".equals(baseResult.getHttpCode())){
                //解析域名得到操作动作
                String substring = MyStringUtils.substring(requestURI, "/");
                String operationalMotion = MyStringUtils.urlByName(substring);
                if (operationalMotion==null){
                    return;
                }
                logOperational.setOperationalUser(name);
                logOperational.setOperationalTime(new Date());
                logOperational.setTargetWay(point.getSignature().getDeclaringTypeName()+"."+point.getSignature().getName());
                logOperational.setOperationalMotion(operationalMotion);
                logOperational.setOperatingParameter( Arrays.toString(point.getArgs()));
                logOperationalService.insert(logOperational);
            }
        }catch(Exception e){
            logOperational.setOperatingParameter("参数放不下");
            logOperationalService.insert(logOperational);
        }



//            System.out.println(token);
//            System.out.println("@AfterReturning：模拟日志记录功能...");
//            System.out.println("@AfterReturning：目标方法为：" +
//                    point.getSignature().getDeclaringTypeName() +
//                    "." + point.getSignature().getName());
//            System.out.println("@AfterReturning：参数为：" +
//                    Arrays.toString(point.getArgs()));
//            System.out.println("@AfterReturning：返回值为：" + returnValue);
//            System.out.println("@AfterReturning：被织入的目标对象为：" + point.getTarget());
    }


}
