package com.gitee.sop.admin.config;

import com.gitee.sop.admin.common.context.SpringContext;
import com.gitee.sop.admin.common.util.SystemUtil;
import com.gitee.sop.admin.interceptor.LoginInterceptor;
import com.gitee.sop.admin.service.sys.UserCacheService;
import com.gitee.sop.admin.service.sys.impl.LocalUserCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
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.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author 六如
 */
@Configuration
@Slf4j
public class SopAdminConfiguration implements ApplicationContextAware, WebMvcConfigurer {

    @Value("${front-location:}")
    private String frontLocation;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContext.setApplicationContext(applicationContext);
    }

    @Bean
    @ConditionalOnProperty(value = "user.cache.type", havingValue = "local", matchIfMissing = true)
    public UserCacheService userCacheService() {
        return new LocalUserCacheService();
    }

    /**
     * 配置拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] excludes = {
                "/", "/error",
                // 排除前端资源
                "/*.html", "/*.ico", "/*.png", "/*.json", "/static/**", "/assets/**"
        };
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(excludes);
    }

    /**
     * 跨域设置
     */
    @Bean
    public CorsFilter corsFilter(
            @Value("${torna.cors.allowed-origin-pattern:*}") String allowedOriginPattern,
            @Value("${torna.cors.allowed-header:*}") String allowedHeader
    ) {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // SpringBoot升级2.4.0之后，跨域配置中的.allowedOrigins不再可用,改成addAllowedOriginPattern
        corsConfiguration.addAllowedOriginPattern(allowedOriginPattern);
        corsConfiguration.addAllowedHeader(allowedHeader);
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
        corsConfiguration.addExposedHeader("Content-Disposition");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }


    /**
     * 配置静态资源
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String homeDir = SystemUtil.getBinPath();
        String frontRoot;
        if (StringUtils.hasText(frontLocation)) {
            frontRoot = StringUtils.trimTrailingCharacter(frontLocation, '/');
        } else {
            frontRoot = homeDir + "/dist";
        }
        log.info("前端资源目录：{}", frontRoot);
        String location = "file:" + frontRoot;
        registry.addResourceHandler("/index.html").addResourceLocations(location + "/index.html");
        registry.addResourceHandler("/favicon.ico").addResourceLocations(location + "/favicon.ico");
        registry.addResourceHandler("/logo.png").addResourceLocations(location + "/logo.png");
        registry.addResourceHandler("/platform-config.json").addResourceLocations(location + "/platform-config.json");
        registry.addResourceHandler("/static/**").addResourceLocations(location + "/static/");
        registry.addResourceHandler("/assets/**").addResourceLocations(location + "/assets/");
    }

}
