package com.mvc;

import com.mvc.interceptor.IPRateLimitInterceptor;
import com.mvc.interceptor.JwtInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    private static final Logger log = LoggerFactory.getLogger(com.mvc.WebConfig.class);
    @Value("${upload-path}")
    public String uploadPath;
    @Value("${download-path}")
    public String downloadPath;
    @Value("${packlog-path}")
    public String packlogPath;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOriginPatterns("*")
                .allowedMethods("*");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("----------配置资源服务-------------");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:META-INF/resources/");
        registry.addResourceHandler("/image/**").addResourceLocations("file:" + uploadPath);
        registry.addResourceHandler("/download/**").addResourceLocations("file:" + downloadPath);
        registry.addResourceHandler("/**").addResourceLocations("file:" + packlogPath);
    }

    /**
     * 添加拦截器，并指定拦截路径
     * */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //用Jwt管理Token,考虑到小程序和APP,还不能启用 2023-05-13 guozhao
        registry.addInterceptor(jwtInterceptor())//添加接口忽略
                .excludePathPatterns("/FacUserAction/loginFacuser/**")//内部用户登陆接口
                .excludePathPatterns("/TDynamicrouterAction/**")//内部用户登陆接口
                .excludePathPatterns("/CustomUserAction/loginCustomUser/**")//客户登陆接口
                .excludePathPatterns("/swagger-ui/**", "/swagger-resources/**","/v3/**")//忽略swagger相关
                .excludePathPatterns("/WxTongjiAction/**","/WxUserAction/**")//小程序控制
                .addPathPatterns("/api/v1/records/**")
        ;

        //IP限流
        registry.addInterceptor(new IPRateLimitInterceptor()).addPathPatterns("/api/v1/**");
    }

    /**
     * jwt拦截器
     * */
    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }
}
