package com.enterprise.manage.core.config;

import com.enterprise.manage.common.constant.Constants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * Web Mvc Config (静态资源映射配置)
 *
 * @author PeiZhi Guo
 * @since 2021-04-17
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${enterprise.file-path}")
    private String filePath;

    @Value("${enterprise.static-path}")
    private String staticPath;

    /**
     * 前后端跨域
     *
     * Param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    /**
     * 访问静态资源
     *
     * Param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 前端映射路径，如果静态页面放到nginx,打包时可以注掉该映射。
        File web = new File("web");
        registry.addResourceHandler("/admin/**")
                .addResourceLocations("file:" + web.getAbsolutePath() + "/admin/");

        // 上传路径
        registry.addResourceHandler(Constants.IMG_CHANGE + "**")
                .addResourceLocations("file:///" + filePath);
    }

}
