package cn.reghao.tnb.sb.config;

import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

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

/**
 * @author reghao
 * @date 2021-11-14 14:31:02
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**")
                .addResourceLocations("classpath:/static/img/");
    }

    /**
     * Tomcat 配置多端口启动
     *
     * @param
     * @return
     * @date 2025-06-09 14:48:24
     */
    //@Bean
    public TomcatServletWebServerFactory getFactory() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        Connector[] connectors = this.connectors();
        if (connectors != null && connectors.length > 0) {
            tomcat.addAdditionalTomcatConnectors(connectors);
        }
        return tomcat;
    }

    private Connector[] connectors() {
        String ports = "8081,8082,8083,8084";
        if (StringUtils.isEmpty(ports)) {
            return null;
        }
        String[] port = ports.split(",");
        List<Connector> connectors = new ArrayList<>();
        for (String s : port) {
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setPort(Integer.parseInt(s));
            connector.setScheme("http");
            //connector.setRedirectPort(8041);
            connectors.add(connector);
        }
        return connectors.toArray(new Connector[]{});
    }
}
