package com.kcim.common.token;

import cn.dev33.satoken.interceptor.SaInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.service.ApiKey;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

import static cn.hutool.core.collection.CollUtil.newArrayList;

/**
 * @program: CostAccount
 * @description: 跨域 统一鉴权处理
 * @author: Wang.YS
 * @create: 2023-09-19 17:36
 **/
@Configuration
@EnableSwagger2
public class SaTokenConfigure implements WebMvcConfigurer {

    /**
     * 注册统一鉴权注册器
     *
     * @param registry 拦截器注册器
     */
    @Order(value = Integer.MAX_VALUE)
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 是否需要登录的 登录拦截器
//        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
        registry.addInterceptor(new SaInterceptor())

                .addPathPatterns("/**")
                // 主要配置登录注销接口，还有swagger相关文件 这里不需要带上server.context-path
                .excludePathPatterns(
                        "/v2/api-docs", "/swagger-ui.html",
                        "/static/js/**", "/swagger-resources/**");

        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
//        registry.addInterceptor(new SaAnnotationInterceptor())
//                .addPathPatterns("/**");
//        SaRouteFunction function = (req,resp,hand) -> StpUtil.checkLogin();
//        SaRouteInterceptor saRouteInterceptor = SaRouteInterceptor.newInstance(function);
    }



    private List<ApiKey> security() {
        // 注意 Sa-token token 前缀配置
        return newArrayList(new ApiKey("token", "token", "header"));
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}
