package com.zksy.framework.config;

import com.zksy.framework.interceptor.ComfirmClientInterceptor;
import com.zksy.framework.interceptor.RepeatSubmitInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.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;

/**
 * 通用配置
 *
 * @author ruoyi
 */
@Slf4j
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;
    @Autowired
    private ComfirmClientInterceptor comfirmClientInterceptor;

    /**
     * 在配置文件中配置的文件保存路径
     */
    @Value("${local.fileserver.path}")
    private String localFileServerDir;

    @Value("${local.fileserver.mapping.path}")
    private String localFileServerMappingPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (localFileServerDir.equals("") || localFileServerDir.equals("${local.fileserver.path}")) {
            String imagesPath = ResourcesConfig.class.getClassLoader().getResource("").getPath();
            log.info("上传配置类imagesPath==" + imagesPath + "\n");
            if (imagesPath.indexOf(".jar") > 0) {
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            } else if (imagesPath.indexOf("classes") > 0) {
                imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
            localFileServerDir = imagesPath;
        }
        /** 本地文件上传路径 */
        log.info("上传配置类imagesPath=============" + localFileServerDir + "\n");
        registry.addResourceHandler(localFileServerMappingPath + "/**").addResourceLocations(localFileServerDir);
        log.info("上传配置类localFileServerDir==" + localFileServerMappingPath + "\n");
        /** swagger配置 */
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**").
                excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html", "/static/**").
                excludePathPatterns(localFileServerMappingPath + "/**");
        registry.addInterceptor(comfirmClientInterceptor).addPathPatterns(
                //get
                "/crmNewsRelease/findByPage",
                "/crmNewsRelease/getList",
                "/crmNewsRelease/getById/{borrowId}",
                "/system/dict/data/type/{dictType}",
                "/crmHighTechZoneEnterprises/getCreditScoreList",
                "/crmCreditRedlistInfo/findByPage",
                "/crmDishonestExecutor/findByPage",
                "/crmSeriouslyDishonestSubjects/findByPage",
                "/crmAdministrativeLicense/findByPage",
                "/crmAdministrativePenalty/findByPage",
                "/crmBusinessLicenseInformation/findByPage",
                "/crmBusinessLicenseInformation/getById/{borrowId}",
                "/commonFile/deleteFileById",
                "/owSelfReporting/downloadTemplateWord",
                "/owSelfReporting/checkInformationByUnicode",
                "/crmHighTechZoneEnterprises/getCreditScoreMostDetailsByUniCode",
                //post
                "/crmComplain/save",
                "/owSelfReporting/save",
                "/owLeavingMessage/save"
        );
    }

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

}