package com.ygtx.framework.interceptor;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson2.JSON;
import com.ygtx.common.annotation.RepeatSubmit;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.utils.ServletUtils;

/**
 * 防止重复提交拦截器
 *
 * @author ruoyi
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (handler instanceof HandlerMethod)
        {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null)
            {
                if (this.isRepeatSubmit(request, annotation))
                {
                    AjaxResult ajaxResult = AjaxResult.error(annotation.message());
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }
            }
            return true;
        }
        else
        {
            checkFileCoding(request, response);
            return true;
        }
    }

    public void checkFileCoding(HttpServletRequest request, HttpServletResponse response){
        String uri = request.getRequestURI();
        if (isTextFile(uri)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain; charset=utf-8");
            request.setAttribute("org.springframework.web.servlet.HandlerMapping.skipContentType", true);
        }
    }

    private boolean isTextFile(String uri) {
        if (uri == null) return false;
        String lowerUri = uri.toLowerCase();
        return lowerUri.endsWith(".txt") ||
                lowerUri.endsWith(".log") ||
                lowerUri.endsWith(".ini") ||
                lowerUri.endsWith(".conf") ||
                lowerUri.endsWith(".properties");
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request 请求信息
     * @param annotation 防重复注解参数
     * @return 结果
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
}
