package com.iformall.log;


import com.iformall.annotation.SystemControllerLog;
import com.iformall.annotation.SystemServiceLog;
import com.iformall.domain.po.MallUserAction;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.enums.EnumMallUserAction;
import com.iformall.service.MallUserActionService;
import com.iformall.shiro.UserSession;
import com.iformall.utils.IPUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class SystemLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    @Autowired
    private MallUserActionService mallUserActionService;

    @Pointcut("@annotation(com.iformall.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }

    @Pointcut("@annotation(com.iformall.annotation.SystemServiceLog)")
    public void serviceAspect(){
    }

    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MallUserInfo user = (MallUserInfo) request.getSession().getAttribute(UserSession.userInfo);
        if(user == null) {
            logger.error("session 获取 user 失败");
            return;
        }
        String ipaddress = IPUtil.getIpAddr(request);

        try {
            logger.info("===前置通知开始=== [" +
                    (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()) + "]" +
                    getControllerMethodDescription(joinPoint) + " " + user.getUsername() +
                    " ip:" + ipaddress);

            MallUserAction action = new MallUserAction();
            action.setTenantId(user.getTenantId());
            action.setType(EnumMallUserAction.CONTROLLER.getCode());
            action.setIp(ipaddress);
            action.setUserId(user.getId());
            action.setActionDesc(getControllerMethodDescription(joinPoint));
            action.setActionTime(new Date());

            mallUserActionService.saveOrUpdate(action);
        } catch (Exception e) {
            logger.error("===前置通知异常信息：{}",e.getMessage());
        }
    }

    /**
     * @Description  异常通知 用于拦截service层记录异常日志
     * @date 2019年3月29日
     */
    @AfterThrowing(pointcut = "serviceAspect()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable e){
        /*
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        MallUserInfo user = (MallUserInfo) request.getSession().getAttribute(UserSession.userInfo);
        //获取请求ip
        String ipaddress = IPUtil.getIpAddr(request);
        //获取用户请求方法的参数并序列化为JSON格式字符串
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
            }
        }
        try{
            // ========控制台输出=========
            System.out.println("=====异常通知开始=====");
            System.out.println("异常代码:" + e.getClass().getName());
            System.out.println("异常信息:" + e.getMessage());
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("方法描述:" + getServiceMethodDescription(joinPoint));
            System.out.println("请求人:" + user.getUsername());
            System.out.println("请求IP:" + ipaddress);
            System.out.println("请求参数:" + params);


            MallUserAction action = new MallUserAction();
            action.setTenantId(user.getTenantId());
            action.setUserId(user.getId());
            action.setType(EnumMallUserAction.CONTROLLER.getCode());
            action.setIp(ipaddress);
            action.setDesc(getControllerMethodDescription(joinPoint));
            action.setActionTime(new Date());

            mallUserActionService.saveOrUpdate(action);
        }catch (Exception ex){
            //记录本地异常日志
            logger.error("==异常通知异常==");
            logger.error("异常信息:{}", ex.getMessage());
        }
        */
    }

    /**
     * @author Stormeye
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     * @date 2019年3月29日
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        //TODO 调试使用
        //return String.format("%s%s",description, Arrays.asList(arguments));
        return description;
    }

    /**
     * @Description  获取注解中对方法的描述信息 用于service层注解
     * @date 2018年9月3日 下午5:05
     */
    public static String getServiceMethodDescription(JoinPoint joinPoint)throws Exception{
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemServiceLog.class).description();
                    break;
                }
            }
        }
        return description;
    }

}
