package com.seer.teach.admin.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Captain
 * @Autograph: 安稳
 * @Description: 跨域处理类
 * @Date: 2023-07-03 16:15:51
 */
@Slf4j
@Configuration
public class CorsConfig {

    public CorsConfig() {
        log.info("CORS 配置类 CorsConfig已加载");
    }

    @Bean
    @ConfigurationProperties(prefix = "zs.cors")
    public Cors cors() {
        return new Cors();
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public CorsFilter corsFilter(Cors cors) {
        CorsConfiguration config = new CorsConfiguration();
        // 设置允许的域名
        config.setAllowedOriginPatterns(cors.getOrigins());
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许所有方法
        config.addAllowedMethod("*");
        // 允许携带认证信息
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    public static class Cors {
        private List<String> origins = new ArrayList<>();

        public List<String> getOrigins() {
            return origins;
        }

        public void setOrigins(List<String> origins) {
            this.origins = origins;
        }
    }
}