/*
 *
 *      Copyright (c) 2018-2025, avenue All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: avenue
 *
 */

package com.emergency.avenue.common.log.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.emergency.avenue.admin.api.dto.SysLogDTO;
import com.emergency.avenue.common.core.util.KeyStrResolver;
import com.emergency.avenue.common.log.annotation.SysLog;
import com.emergency.avenue.common.log.event.SysLogEvent;
import com.emergency.avenue.common.log.util.LogTypeEnum;
import com.emergency.avenue.common.log.util.SysLogUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.expression.EvaluationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 操作日志使用spring event异步入库
 *
 * @author L.cm
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
public class SysLogAspect {

	private final ApplicationEventPublisher publisher;

	private final KeyStrResolver tenantKeyStrResolver;

	@SneakyThrows
	@Around("@annotation(sysLog)")
	public Object around(ProceedingJoinPoint point, SysLog sysLog) {
		String strClassName = point.getTarget().getClass().getName();
		String strMethodName = point.getSignature().getName();
		log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

		String value = sysLog.value();
		String expression = sysLog.expression();
		// 当前表达式存在 SPEL，会覆盖 value 的值
		if (StrUtil.isNotBlank(expression)) {
			// 解析SPEL
			MethodSignature signature = (MethodSignature) point.getSignature();
			EvaluationContext context = SysLogUtils.getContext(point.getArgs(), signature.getMethod());
			try {
				value = SysLogUtils.getValue(context, expression, String.class);
			}
			catch (Exception e) {
				// SPEL 表达式异常，则获取 value 的值
				log.error("@SysLog 解析SPEL {} 异常", expression);
			}
		}

		SysLogDTO logDTO = SysLogUtils.getSysLog();
		logDTO.setTitle(value);
		// 发送异步日志事件
		Long startTime = System.currentTimeMillis();
		Object obj;
		try {
			obj = point.proceed();

			logDTO.setRequestParam(getMethodArgs(point));
			logDTO.setResponseParam(handlerResult(obj));
		}
		catch (Exception e) {
			logDTO.setLogType(LogTypeEnum.ERROR.getType());
			logDTO.setException(e.getMessage());
			throw e;
		}
		finally {
			Long endTime = System.currentTimeMillis();
			logDTO.setTime(endTime - startTime);
			logDTO.setTenantId(Long.parseLong(tenantKeyStrResolver.key()));
			publisher.publishEvent(new SysLogEvent(logDTO));
		}
		return obj;
	}

	private String getMethodArgs(JoinPoint point) {
		Object[] args = point.getArgs();
		if (args == null || args.length == 0) {
			return "";
		}
		try {
			Map<String, Object> params = new HashMap<>();
			String[] parameterNames = ((MethodSignature) point.getSignature()).getParameterNames();
			for (int i = 0; i < parameterNames.length; i++) {
				Object arg = args[i];
				// 过滤不能转换成JSON的参数
				if ((arg instanceof ServletRequest) || (arg instanceof ServletResponse)) {
					continue;
				} else if ((arg instanceof MultipartFile)) {
					arg = arg.toString();
				}
				params.put(parameterNames[i], arg);
			}
			return JSONUtil.toJsonStr(params);
		} catch (Exception e) {
			log.error("接口出入参日志打印切面处理请求参数异常", e);
		}
		return Arrays.toString(args);
	}

	/**
	 * 返回结果简单处理
	 * 1）把返回结果转成String，方便输出。
	 * 2）返回结果太长则截取（最多3072个字符），方便展示。
	 *
	 * @param result 原方法调用的返回结果
	 * @return 处理后的
	 */
	private String handlerResult(Object result) {
		if (result == null) {
			return null;
		}
		String resultStr;
		try {
			if (result instanceof String) {
				resultStr = (String) result;
			} else {
				resultStr = JSONUtil.toJsonStr(result);// 如果返回结果非String类型，转换成JSON格式的字符串
			}

			if (resultStr.length() > 3072) {
				resultStr = resultStr.substring(0, 3072);
			}
		} catch (Exception e) {
			resultStr = result.toString();
			log.error("接口出入参日志打印切面处理返回参数异常", e);
		}
		return resultStr;
	}
}
