package com.mortals.xhx.base.framework.config;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.*;

/**
 * @author: zxfei
 * @date: 2022/2/15 13:16
 * @description:
 **/
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Bean
    public CorsFilter corsFilter(){

        //初始化配置对象
        CorsConfiguration configuration = new CorsConfiguration();
        //允许跨域访问的域名
        configuration.addAllowedOrigin("*");
        // configuration.setAllowCredentials(true);  //运行携带cookie
        configuration.addAllowedMethod("*"); //代表所有请求方法
        configuration.addAllowedHeader("*"); //允许携带任何头信息

        //初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource=new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",configuration);

        //返回CorSfilter实例，参数
        return new CorsFilter(configurationSource);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedMethods(new String[] { "GET", "POST","PUT","DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }

    public void addInterceptors(InterceptorRegistry registry) {
      //  registry.addInterceptor(tokenInterceptor).addPathPatterns("/**");
    }

   @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 将根路径 "/" 的请求重定向到 "/index.html"
        registry.addViewController("/").setViewName("forward:/index.html");
        WebMvcConfigurer.super.addViewControllers(registry);
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 添加资源处理器，用于映射静态资源路径
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}
