package com.sunda.spmsweb.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunda.spmscommon.entity.SysLog;
import com.sunda.spmscommon.service.ISysLogService;
import com.sunda.spmsweb.util.IPUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @program: spms
 * @description: login aspect
 * @author: Wayne Wu
 * @create: 2020-12-16 18:26
 **/
@Aspect
@Component
public class LoginAspect {

    @Autowired
    ISysLogService iSysLogService;

    @Pointcut("@annotation(com.sunda.spmsweb.aspect.Login)")
    public void pointcut() { }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        saveLoginLog(point, time, result);
        return result;
    }

    private void saveLoginLog(ProceedingJoinPoint joinPoint, long time, Object result) {
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SysLog sysLog = new SysLog();
        sysLog.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
        Method method = signature.getMethod();

        //日志类型 1操作；2登录；
        sysLog.setLogType("2");

        //操作类型 - 登录；查询；添加；修改；删除；导入；导出；
        // 获取注解上的描述
        Login logAnnotation = method.getAnnotation(Login.class);
        if (logAnnotation != null) {
            sysLog.setOperateType(logAnnotation.operateType());
        }

        //请求路径
        String path = request.getRequestURI();
        sysLog.setRequestUrl(path);

        // 设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));

        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        String userId = "";
        // 请求的方法参数值，获取尝试登录用户名
        if (request.getMethod().toUpperCase().equals("POST")){
            Object[] args = joinPoint.getArgs();
            if (args != null) {
                userId = args[0].toString();
            }
        }

        JSONObject resultObject = JSONObject.parseObject(JSON.toJSON(result).toString());
        if (Integer.parseInt(resultObject.get("code").toString()) == 200){
            //登录成功
            sysLog.setUserId(userId);
            sysLog.setLogContent("用户: " + userId + " 登录成功！");
        }else {
            //登录失败
            sysLog.setLogContent("用户: " + userId + " " + resultObject.get("msg").toString());
        }


        // 设置 http 请求类型
        sysLog.setRequestType(request.getMethod());

        // 设置程序执行耗时
        sysLog.setCostTime(time);

        //System.out.println("\n\n sysLog ================ " + sysLog.toString());
        // 保存系统日志
        iSysLogService.insertSysLog(sysLog);
    }
}
