package com.xy.config;

import com.xy.consts.CommConsts;
import com.xy.enums.SaTokenEnum;
import com.xy.error.CommRuntimeException;
import com.xy.swagger.Knife4jConfig;
import com.xy.utils.AuthorizeUtils;
import com.xy.utils.Emptys;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//@Component
@AllArgsConstructor
public class AuthorizeIntercetor extends HandlerInterceptorAdapter implements WebMvcConfigurer {

    private AuthorizeConfig authorizeConfig;

    /**
     * 方法执行前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //登录鉴权
        String satoken = request.getHeader(CommConsts.TOKEN_NAME);
        boolean isLogin = AuthorizeUtils.authByLogin(satoken);
        if (!isLogin) {
            throw new CommRuntimeException(SaTokenEnum.NO_LOGIN.getKey(), SaTokenEnum.NO_LOGIN.getName());
        }
        //接口鉴权
        String sysId = request.getHeader(CommConsts.SYS_ID);
        if (!Emptys.check(sysId)) {
            throw new CommRuntimeException(SaTokenEnum.NO_AUTHORITY.getKey(), SaTokenEnum.NO_AUTHORITY.getName());
        }
        String uri = request.getRequestURI();
        boolean isInterface = AuthorizeUtils.authByInterface(satoken, Long.valueOf(sysId), uri);
        if (!isInterface) {
            throw new CommRuntimeException(SaTokenEnum.NO_AUTHORITY.getKey(), SaTokenEnum.NO_AUTHORITY.getName());
        }
        //token续签
        AuthorizeUtils.renewTimeout(satoken);
        return true;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePaths = new ArrayList<>();
        excludePaths.addAll(authorizeConfig.getExcludePaths());
        excludePaths.addAll(Knife4jConfig.swaggerExcludes);
        excludePaths.addAll(Arrays.asList(
                "/**/js/**",
                "/**/lib/**",
                "/**/html/**",
                "/**/*.jpg/**",
                "/**/*.html/**",
                "/**/static/**"
                )
        );
        registry.addInterceptor(this)
                .excludePathPatterns(excludePaths)
                .addPathPatterns("/**");
    }
}
