package com.mosty.operation.log.aspect;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.SimplePropertyPreFilter;
import com.mosty.common.base.entity.log.Log;
import com.mosty.common.base.entity.log.SysOperLog;
import com.mosty.common.base.exception.BusinessStatus;
import com.mosty.common.base.threadpool.SimpleThreadPool;
import com.mosty.common.base.util.IpUtil;
import com.mosty.common.base.util.ServletUtils;
import com.mosty.common.base.util.SpringIocContext;
import com.mosty.common.base.util.StringUtils;
import com.mosty.common.token.JWTUtil;
import com.mosty.common.token.UserInfo;
import com.mosty.operation.log.aspect.feign.OperationLogClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static com.mosty.common.base.constant.SystemConfigConstants.TOKEN_HEADER;
import static com.mosty.common.base.entity.log.LogConst.LOG_THREAD_POOL;


/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperationLogClient operationLogClient;

    // 排除敏感属性字段
    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword", "zb"};

    // 配置织入点
    @Pointcut("@annotation(com.mosty.common.base.entity.log.Log)")
    public void logPointCut() {
    }

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

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

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            String token = ServletUtils.getRequest().getHeader(TOKEN_HEADER);
            // 获取当前的用户 从header中获取
            UserInfo userInfo = JWTUtil.getUserInfo(token);
            String ipAddress = IpUtil.getIpAddress(ServletUtils.getRequest());
            // *========数据库日志=========*//
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            operLog.setOperIp(ipAddress);
            String url = ServletUtils.getRequest().getRequestURI();
            operLog.setOperUrl(url);
            //  添加服务名称
            if (url != null && url.length() >= 11) {
                String[] s = url.split("/");
                if (s.length >= 2 && s[1].contains("mosty-")) {
                    operLog.setMkmc(s[1]);
                }
            }
            if (userInfo != null) {
                operLog.setOperName(userInfo.getUserLoginName());
                operLog.setOperUserId(String.valueOf(userInfo.getUserId()));
                operLog.setOperSfzh(userInfo.getIdEntityCard());
                if (StringUtils.isNotNull(userInfo.getDeptId())
                        && StringUtils.isNotEmpty(userInfo.getDeptName())) {
                    operLog.setSsbm(userInfo.getDeptName());
                    operLog.setSsbmid(String.valueOf(userInfo.getDeptId()));
                    operLog.setSsbmdm(userInfo.getDeptCode());
                }
            }
            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
            SimpleThreadPool.execute(LOG_THREAD_POOL, () -> {
                operationLogClient.addOperationLog(operLog);
            });
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    // 获取注解中对方法的描述信息 用于Controller层注解
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception {
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
            operLog.setJsonResult(StringUtils.substring(JSONObject.toJSONString(jsonResult), 0, 2000));
        }

        if (log.isScSj() && 0 == operLog.getStatus()) {
            operLog.setSfsc(1);
        }
    }

    // 获取请求的参数，放到log中
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        if (map != null) {
            SimplePropertyPreFilter filter = excludePropertyPreFilter();
            Map<String, String[]> newMap = new HashMap<>();
            for(String key : map.keySet()){
                if(!filter.getExcludes().contains(key)){
                    newMap.put(key, map.get(key));
                }
            }
            String params = JSONObject.toJSONString(newMap);
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        } else {
            Object[] args = joinPoint.getArgs();
            if (ObjectUtils.isNotEmpty(args)) {
                JSONArray ja = JSONArray.of(args);
                if(ObjectUtils.isNotEmpty(ja)){
                    String params = ja.getString(0);
                    operLog.setOperParam(StringUtils.substring(params, 0, 2000));
                }
            }
        }
    }

    // 忽略敏感属性
//    public PropertyPreFilters.MySimplePropertyPreFilter excludePropertyPreFilter() {
//        return new PropertyPreFilters().addFilter().addExcludes(EXCLUDE_PROPERTIES);
//    }
    public SimplePropertyPreFilter excludePropertyPreFilter() {
        SimplePropertyPreFilter filters = new SimplePropertyPreFilter();
        filters.getExcludes().addAll(Arrays.asList(EXCLUDE_PROPERTIES));
        return filters;
    }

    // 参数拼装
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        if(excludePropertyPreFilter().getExcludes().contains(o)){
                            Object jsonObj = JSONObject.toJSONString(o, JSONWriter.Feature.WriteNonStringValueAsString);
                            params.append(jsonObj.toString()).append(" ");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return params.toString().trim();
    }

    // 判断是否需要过滤的对象
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
