package com.yfd.platform.config;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
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.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletContext;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file-space.system}")
    private String systempath;

    private final ServletContext servletContext;

    public WebConfig(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
    @Bean
    public Cache<String, String> loginuserCache() {
        return CacheUtil.newLRUCache(200);//用户登录缓存数 缺省200
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source =
                new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(3600L);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
    private boolean isTomcatEnvironment() {
        // 在此处可以根据不同的条件来判断当前运行环境
        // 例如可以检查System.getProperty("catalina.home")是否存在
        // 或者检查是否存在某个特定的系统属性来区分环境
//        return System.getProperty("catalina.home") != null;
        return false;
    }

    @SneakyThrows
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (isTomcatEnvironment()) {
            // Tomcat部署环境
            String appRoot = servletContext.getRealPath("/");
            String iconPath = appRoot + "WEB-INF/classes/static/icon/";

            registry.addResourceHandler("/menu/**")
                    .addResourceLocations("file:" + iconPath)
                    .setCachePeriod(0);
        } else {
            // IDEA开发环境
            registry.addResourceHandler("/menu/**")
                    .addResourceLocations("classpath:/static/icon/")
                    .setCachePeriod(0);
            registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                    "classpath:/META-INF/resources/");
        }

        String menuUrl = "file:" + systempath + "menu/";
        registry.addResourceHandler("/menu/**").addResourceLocations(menuUrl).setCachePeriod(0);


        String systemUrl = "file:" + systempath + "user/";
        registry.addResourceHandler("/avatar/**").addResourceLocations(systemUrl).setCachePeriod(0);




    }

}
