package com.cool.bang.core.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cool.bang.common.tools.secure.SecurityUtil;
import com.cool.bang.common.tools.servlet.ServletUtil;
import com.cool.bang.modules.system.domain.po.Log;
import com.cool.bang.modules.system.domain.po.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Web Log Aspect (日志切面)
 *
 * @author PeiZhi Guo
 * 2021-04-23 10:13
 */
@Aspect
@Component
public class WebLogAspect {

    @Resource
    private AsyncLog asyncLog;

    private final ThreadLocal<Long> startTime = new ThreadLocal<>();

    //切入点描述
    @Pointcut("@annotation(com.cool.bang.core.annotation.Log)")
    public void webLog() { }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        //记录开始时间
        startTime.set(System.currentTimeMillis());
    }

    /**
     * 处理完请求后执行
     */
    @AfterReturning(returning = "result", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object result) { handleLog(joinPoint, null, result); }

    /**
     * 拦截异常操作
     */
    @AfterThrowing(value = "webLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object result) {
        HttpServletRequest request = ServletUtil.getRequest();
        HttpSession session = ServletUtil.getSession();
        try {
            //获取日志注解
            com.cool.bang.core.annotation.Log log = getAnnotationLog(joinPoint);
            if (log == null) {
                return;
            }
            //数据库日志实体对象
            Log sysLog = new Log();
            sysLog.setTitle(log.title());
            sysLog.setOperationType(log.operationType().ordinal());
            sysLog.setStatus(1);
            //ip地址
            String ip = ServletUtil.getClientIp(request);
            sysLog.setRemoteAddr(ip);
            //操作人
            User sysUser = SecurityUtil.getCurrentUser();
            if (sysUser != null) {
                sysLog.setUsername(sysUser.getRealName());
            }
            //请求URI
            sysLog.setRequestUri(request.getRequestURL().toString());
            //请求类型.方法
            sysLog.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            //操作方式
            sysLog.setHttpMethod(request.getMethod());
            //获取传入目标方法的参数
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                if (arg instanceof ServletRequest || arg instanceof ServletResponse || arg instanceof MultipartFile) {
                    arg = arg.toString();
                }
            }
            String paramStr = JSON.toJSONString(args);
            sysLog.setQueryParams(paramStr.length() > 5000 ? JSON.toJSONString("请求参数数据过长不与显示") : paramStr);
            //sessionId
            if (session != null) {
                sysLog.setSessionId(session.getId());
            }
            //返回内容
            String retString = JSON.toJSONString(result);
            sysLog.setResponse(retString.length() > 5000 ? JSONObject.toJSONString("返回参数数据过长不与显示") : retString);
            //方法执行时间
            sysLog.setUseTime(System.currentTimeMillis() - startTime.get());
            //操作系统、浏览器信息
            Map<String, String> browserMap = ServletUtil.getOsAndBrowserInfo(request);
            sysLog.setBrowser(browserMap.get("os") + "-" + browserMap.get("browser"));
            //地区、省、市、网络服务提供商
            if (!"127.0.0.1".equals(ip)) {
                Map<String, String> map = (Map<String, String>) session.getAttribute("addressIp");
                if (map == null) {
                    map = ServletUtil.getAddressByIP(ServletUtil.getClientIp(request));
                    session.setAttribute("addressIp", map);
                }
                sysLog.setArea(map.get("area"));
                sysLog.setProvince(map.get("province"));
                sysLog.setCity(map.get("city"));
                sysLog.setIsp(map.get("isp"));
            }
            //异常信息
            if (e != null) {
                sysLog.setStatus(0);
                sysLog.setResponse(null);
                sysLog.setException(e.getMessage());
            }
            //保存数据库
            asyncLog.record(sysLog);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private com.cool.bang.core.annotation.Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(com.cool.bang.core.annotation.Log.class);
        }
        return null;
    }

}
