package cn.axzo.workflow.server.common.aspectj;

import cn.axzo.workflow.core.common.exception.WorkflowEngineException;
import cn.axzo.workflow.server.common.annotation.RepeatSubmit;
import cn.axzo.workflow.server.common.config.RepeatSubmitResolver;
import cn.axzo.workflow.server.common.util.RedisUtils;
import cn.azxo.framework.common.model.CommonResponse;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
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.Before;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Collection;
import java.util.Map;
import java.util.StringJoiner;

import static cn.axzo.workflow.core.common.code.OtherRespCode.REPEAT_SUBMIT_ERROR_TIPS;
import static cn.axzo.workflow.core.common.code.OtherRespCode.REPEAT_SUBMIT_TIME_ERROR_TIPS;

/**
 * 防止重复提交拦截器
 *
 * @author wangli
 */
@Aspect
@Slf4j
public class RepeatSubmitAspect implements Ordered {

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 2;
    }

    private final RepeatSubmitResolver repeatSubmitResolver;
    private static final ThreadLocal<String> KEY_CACHE = new ThreadLocal<>();
    private static final String REPEAT_SUBMIT_KEY = "global:repeat_submit:";

    public RepeatSubmitAspect(RepeatSubmitResolver repeatSubmitResolver) {
        this.repeatSubmitResolver =
                repeatSubmitResolver;
    }

    @Before("@annotation(repeatSubmit)")
    public void doBefore(JoinPoint point, RepeatSubmit repeatSubmit) throws Throwable {
        // 如果注解不为0 则使用注解数值
        long interval = repeatSubmit.timeUnit().toMillis(repeatSubmit.interval());
        // 获取注解中的 SpEL 表达式
        interval = repeatSubmitResolver.resolveExpression(repeatSubmit.intervalExpression(), interval);
        if (interval < 1000) {
            throw new WorkflowEngineException(REPEAT_SUBMIT_TIME_ERROR_TIPS,
                    String.valueOf((repeatSubmit.interval() / 1000)));
        }
        HttpServletRequest request = getRequest();
        String nowParams = argsArrayToString(point.getArgs());

        // 请求地址（作为存放cache的key值）
        String url = request.getRequestURI();

        // 唯一值（没有消息头则使用请求地址）

        String paramsKey = SecureUtil.md5(nowParams);
        // 唯一标识（指定key + url + 消息头）
        String cacheRepeatKey = REPEAT_SUBMIT_KEY + url + ":" + paramsKey;
        log.info("repeatSubmit key: {}", cacheRepeatKey);

        String key = RedisUtils.getCacheObject(cacheRepeatKey);
        if (key == null) {
            RedisUtils.setCacheObject(cacheRepeatKey, "", Duration.ofMillis(interval));
            KEY_CACHE.set(cacheRepeatKey);
        } else {
            log.warn("{}", repeatSubmit.message());
            throw new WorkflowEngineException(REPEAT_SUBMIT_ERROR_TIPS, repeatSubmit.message());
        }
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(repeatSubmit)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, RepeatSubmit repeatSubmit, Object jsonResult) {
        if (jsonResult instanceof CommonResponse) {
            CommonResponse<?> r = (CommonResponse<?>) jsonResult;
            try {
                // 成功则不删除redis数据 保证在有效时间内无法重复提交
                if (r.getCode() == HttpStatus.HTTP_OK) {
                    return;
                }
                RedisUtils.deleteObject(KEY_CACHE.get());
            } finally {
                KEY_CACHE.remove();
            }
        }
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(repeatSubmit)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, RepeatSubmit repeatSubmit, Exception e) throws Exception {
        if (StringUtils.hasText(KEY_CACHE.get())) {
            RedisUtils.deleteObject(KEY_CACHE.get());
            KEY_CACHE.remove();
        }
    }

    /**
     * 参数拼装
     */
    public static String argsArrayToString(Object[] paramsArray) {
        StringJoiner params = new StringJoiner(" ");
        if (ArrayUtil.isEmpty(paramsArray)) {
            return params.toString();
        }
        for (Object o : paramsArray) {
            if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                params.add(JSONUtil.toJsonStr(o));
            }
        }
        return params.toString();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public static 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.values()) {
                return value instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

    public static HttpServletRequest getRequest() {
        try {
            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return attributes.getRequest();
        } catch (Exception e) {
            return null;
        }
    }

}
