package com.ruoyi.monitor.aspect;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.monitor.domain.AuditLog;
import com.ruoyi.monitor.service.IAuditLogService;

/**
 * 审计日志切面处理类
 * 
 * @author ruoyi
 */
@Aspect
@Component
public class AuditLogAspect
{
    private static final Logger log = LoggerFactory.getLogger(AuditLogAspect.class);

    @Autowired
    private IAuditLogService auditLogService;

    @Autowired
    private ObjectMapper objectMapper;

    // 配置织入点 - 拦截所有Controller方法
    @Pointcut("@annotation(com.ruoyi.common.annotation.Log)")
    public void logPointCut()
    {
    }

    // 配置织入点 - 拦截债权相关操作
    @Pointcut("execution(* com.ruoyi.credit.service..*(..))")
    public void creditServicePointCut()
    {
    }

    // 配置织入点 - 拦截支付相关操作
    @Pointcut("execution(* com.ruoyi.payment.service..*(..))")
    public void paymentServicePointCut()
    {
    }

    // 配置织入点 - 拦截区块链相关操作
    @Pointcut("execution(* com.ruoyi.blockchain.service..*(..))")
    public void blockchainServicePointCut()
    {
    }

    // 配置织入点 - 拦截安全相关操作
    @Pointcut("execution(* com.ruoyi.security.service..*(..))")
    public void securityServicePointCut()
    {
    }

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

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

    /**
     * 环绕通知 - 记录债权相关操作
     */
    @Around("creditServicePointCut()")
    public Object aroundCreditService(ProceedingJoinPoint joinPoint) throws Throwable
    {
        return recordBusinessOperation(joinPoint, "CREDIT", "债权管理");
    }

    /**
     * 环绕通知 - 记录支付相关操作
     */
    @Around("paymentServicePointCut()")
    public Object aroundPaymentService(ProceedingJoinPoint joinPoint) throws Throwable
    {
        return recordBusinessOperation(joinPoint, "PAYMENT", "支付结算");
    }

    /**
     * 环绕通知 - 记录区块链相关操作
     */
    @Around("blockchainServicePointCut()")
    public Object aroundBlockchainService(ProceedingJoinPoint joinPoint) throws Throwable
    {
        return recordBusinessOperation(joinPoint, "BLOCKCHAIN", "区块链集成");
    }

    /**
     * 环绕通知 - 记录安全相关操作
     */
    @Around("securityServicePointCut()")
    public Object aroundSecurityService(ProceedingJoinPoint joinPoint) throws Throwable
    {
        return recordBusinessOperation(joinPoint, "SECURITY", "安全管理");
    }

    /**
     * 记录业务操作
     */
    private Object recordBusinessOperation(ProceedingJoinPoint joinPoint, String businessType, String module) throws Throwable
    {
        long beginTime = System.currentTimeMillis();
        Object result = null;
        Exception exception = null;

        try {
            result = joinPoint.proceed();
            return result;
        } catch (Exception e) {
            exception = e;
            throw e;
        } finally {
            long endTime = System.currentTimeMillis();
            
            // 记录业务操作日志
            recordBusinessAuditLog(joinPoint, businessType, module, beginTime, endTime, result, exception);
        }
    }

    /**
     * 记录业务审计日志
     */
    private void recordBusinessAuditLog(ProceedingJoinPoint joinPoint, String businessType, String module, 
                                       long beginTime, long endTime, Object result, Exception exception)
    {
        try {
            String methodName = joinPoint.getSignature().getName();
            String className = joinPoint.getTarget().getClass().getSimpleName();
            Object[] args = joinPoint.getArgs();

            // 构建操作描述
            String operationDescription = className + "." + methodName;
            
            // 确定风险等级
            String riskLevel = determineRiskLevel(methodName, businessType);
            
            // 序列化参数和结果
            String requestParams = null;
            String responseResult = null;
            
            try {
                if (args != null && args.length > 0) {
                    requestParams = objectMapper.writeValueAsString(args);
                }
                if (result != null) {
                    responseResult = objectMapper.writeValueAsString(result);
                }
            } catch (Exception e) {
                log.warn("序列化参数或结果失败: {}", e.getMessage());
            }

            // 创建审计日志
            AuditLog auditLog = new AuditLog();
            auditLog.setOperationType(businessType);
            auditLog.setOperationModule(module);
            auditLog.setOperationDescription(operationDescription);
            auditLog.setRequestParams(requestParams);
            auditLog.setResponseResult(responseResult);
            auditLog.setOperationTime(new Date(beginTime));
            auditLog.setExecutionTime(endTime - beginTime);
            auditLog.setRiskLevel(riskLevel);
            
            if (exception != null) {
                auditLog.setStatus("1");
                auditLog.setErrorMsg(exception.getMessage());
            } else {
                auditLog.setStatus("0");
            }

            // 获取用户信息
            try {
                auditLog.setUserId(SecurityUtils.getUserId());
                auditLog.setUserName(SecurityUtils.getUsername());
            } catch (Exception e) {
                auditLog.setUserId(0L);
                auditLog.setUserName("system");
            }

            // 获取请求信息
            try {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    auditLog.setIpAddress(IpUtils.getIpAddr(request));
                    auditLog.setUserAgent(request.getHeader("User-Agent"));
                    auditLog.setRequestUri(request.getRequestURI());
                    auditLog.setRequestMethod(request.getMethod());
                    auditLog.setSessionId(request.getSession().getId());
                }
            } catch (Exception e) {
                // 忽略获取请求信息失败
            }

            // 确保必需字段不为空
            ensureRequiredFields(auditLog);

            // 异步保存审计日志
            auditLogService.insertAuditLog(auditLog);
            
        } catch (Exception e) {
            log.error("记录业务审计日志失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 确定风险等级
     */
    private String determineRiskLevel(String methodName, String businessType)
    {
        String method = methodName.toLowerCase();
        
        // 高风险操作
        if (method.contains("delete") || method.contains("remove") || 
            method.contains("clean") || method.contains("clear") ||
            method.contains("transfer") || method.contains("payment") ||
            method.contains("approve") || method.contains("reject")) {
            return "HIGH";
        }
        
        // 中风险操作
        if (method.contains("update") || method.contains("modify") || 
            method.contains("edit") || method.contains("change") ||
            method.contains("create") || method.contains("add") ||
            method.contains("generate") || method.contains("deploy")) {
            return "MEDIUM";
        }
        
        // 特殊业务类型风险评估
        if ("SECURITY".equals(businessType) || "BLOCKCHAIN".equals(businessType)) {
            return "HIGH";
        }
        
        // 低风险操作（查询等）
        return "LOW";
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
    {
        try
        {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null)
            {
                return;
            }

            // 获取当前的用户
            LoginUser loginUser = SecurityUtils.getLoginUser();

            // *========数据库日志=========*
            AuditLog auditLog = new AuditLog();
            auditLog.setStatus("0");
            auditLog.setOperationTime(new Date()); // 设置操作时间
            
            // 设置默认风险等级
            auditLog.setRiskLevel("LOW");
            
            // 请求的地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            auditLog.setIpAddress(ip);
            auditLog.setRequestUri(ServletUtils.getRequest().getRequestURI());
            if (loginUser != null)
            {
                auditLog.setUserName(loginUser.getUsername());
                auditLog.setUserId(loginUser.getUserId());
            }

            if (e != null)
            {
                auditLog.setStatus("1");
                auditLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            auditLog.setRequestMethod(className + "." + methodName + "()");
            // 设置请求方式
            auditLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, auditLog, jsonResult);
            
            // 根据操作类型动态调整风险等级
            updateRiskLevelBasedOnOperation(auditLog, methodName);
            
            // 确保必需字段不为空
            ensureRequiredFields(auditLog);
            
            // 保存数据库
            auditLogService.insertAuditLog(auditLog);
        }
        catch (Exception exp)
        {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * 
     * @param log 日志
     * @param auditLog 审计日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, AuditLog auditLog, Object jsonResult) throws Exception
    {
        // 设置action动作
        auditLog.setOperationType(log.businessType().ordinal() + "");
        // 设置标题
        auditLog.setOperationModule(log.title());
        // 设置操作人类别
        auditLog.setOperationDescription(log.title());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData())
        {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, auditLog);
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult))
        {
            auditLog.setResponseResult(StringUtils.substring(jsonResult.toString(), 0, 2000));
        }
    }

    /**
     * 获取请求的参数，放到log中
     * 
     * @param auditLog 审计日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, AuditLog auditLog) throws Exception
    {
        String requestMethod = auditLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
        {
            String params = argsArrayToString(joinPoint.getArgs());
            auditLog.setRequestParams(StringUtils.substring(params, 0, 2000));
        }
    }

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

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray)
    {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (Object o : paramsArray)
            {
                if (StringUtils.isNotNull(o) && !isFilterObject(o))
                {
                    try
                    {
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 确保必需字段不为空
     */
    private void ensureRequiredFields(AuditLog auditLog)
    {
        // 确保操作时间不为空
        if (auditLog.getOperationTime() == null) {
            auditLog.setOperationTime(new Date());
        }
        
        // 确保风险等级不为空
        if (auditLog.getRiskLevel() == null || auditLog.getRiskLevel().trim().isEmpty()) {
            auditLog.setRiskLevel("LOW");
        }
        
        // 确保状态不为空
        if (auditLog.getStatus() == null) {
            auditLog.setStatus("0");
        }
    }

    /**
     * 根据操作更新风险等级
     */
    private void updateRiskLevelBasedOnOperation(AuditLog auditLog, String methodName)
    {
        String method = methodName.toLowerCase();
        String operationType = auditLog.getOperationType();
        
        // 高风险操作
        if (method.contains("delete") || method.contains("remove") || 
            method.contains("clean") || method.contains("clear") ||
            method.contains("transfer") || method.contains("payment") ||
            method.contains("approve") || method.contains("reject")) {
            auditLog.setRiskLevel("HIGH");
        }
        // 中风险操作
        else if (method.contains("update") || method.contains("modify") || 
                 method.contains("edit") || method.contains("change") ||
                 method.contains("create") || method.contains("add") ||
                 method.contains("generate") || method.contains("deploy")) {
            auditLog.setRiskLevel("MEDIUM");
        }
        // 特殊业务类型风险评估
        else if ("SECURITY".equals(operationType) || "BLOCKCHAIN".equals(operationType)) {
            auditLog.setRiskLevel("HIGH");
        }
        // 默认保持LOW风险等级
    }

    /**
     * 判断是否需要过滤的对象。
     * 
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @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;
    }
}