package com.zhgd.xmgl.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.zhgd.annotation.OperLog;
import com.zhgd.xmgl.modules.basicdata.entity.OperationLog;
import com.zhgd.xmgl.modules.basicdata.service.IOperationLogService;
import com.zhgd.xmgl.security.SecurityUser;
import com.zhgd.xmgl.security.SecurityUtil;
import com.zhgd.xmgl.util.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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 org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: wisdomSite
 * @description: 切面处理类，操作日志记录处理
 * @author: Mr.Peng
 * @create: 2021-05-06 18:04
 **/
@Aspect
@Component
public class OperLogAspect {

    @Autowired
    private IOperationLogService operationLogService;


    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
    */
    @Pointcut("@annotation(com.zhgd.annotation.OperLog)")
        public void operLogPoinCut() {
    }

    /**
    * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
    */
    @Pointcut("execution(* com.*.*.*.*.controller..*.*(..))")
        public void operExceptionLogPoinCut() {
    }


    /**
    * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
    *
    * @param joinPoint 切入点
    * @param keys      返回结果
    */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
         // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        OperationLog operlog = new OperationLog();
        try {
            //operlog.setOperId(IdGenerator.getUUID()); // 主键ID
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            OperLog opLog = method.getAnnotation(OperLog.class);
            if (opLog != null) {
                String operModul = opLog.operModul();
                String operType = opLog.operType();
                String operDesc = opLog.operDesc();
                operlog.setOperModule(operModul); // 操作模块
                operlog.setOperType(operType); // 操作类型
                operlog.setOperDesc(operDesc); // 操作描述
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;

            operlog.setOperMethod(methodName);

            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);

            operlog.setOperRequParam(params); // 请求参数

            // 请求用户ID
//            String operUserId = request.getHeader("operateId");
//            if(StringUtils.isNotEmpty(operUserId)) {
//                operlog.setOperUserId(operUserId);
//            }
            //operlog.setOperUserName(); // 请求用户名称
            operlog.setOperIp(IpUtil.getRemortIP(request)); // 请求IP
            operlog.setOperUri(request.getRequestURI()); // 请求URI
            operlog.setOperMethod(request.getMethod()); // 请求方法
            operlog.setOperCreateTime(new Date()); // 创建时间
            SecurityUser user = SecurityUtil.getUser();
            if (user != null) {
                operlog.setOperUserId(user.getUserId()); // 请求用户ID
                operlog.setOperUserName(user.getRealName()); //请求用户真实姓名
            }
            if("com.zhgd.xmgl.modules.basicdata.controller.LoginController.login".equals(operlog.getOperMethod())){
                if (keys != null) {
                    JSONObject json=JSONUtil.parseObj(keys);
                    if("200".equals(json.getStr("code"))){
                        JSONObject jsonObject=json.getJSONObject("result");
                        String userId=jsonObject.getStr("userId");
                        if (StringUtils.isNotEmpty(userId)) {
                            operlog.setOperUserId(userId);
                            operationLogService.save(operlog);
                        }
                    }
                }
            }else {
//                if (StringUtils.isNotEmpty(operUserId)) {
                    operationLogService.save(operlog);
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

     /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
     public Map<String, String> converMap(Map<String, String[]> paramMap) {
         Map<String, String> rtnMap = new HashMap<String, String>();
         for (String key : paramMap.keySet()) {
                 rtnMap.put(key, paramMap.get(key)[0]);
             }
         return rtnMap;
     }

}
