package org.qinan.safetyeval.start;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 安全评价业务服务启动类
 * <p>
 * 基于GBS底座，复用GBS基础能力，扩展安全评价业务
 * </p>
 *
 * @author safety-eval
 */
@SpringBootApplication(scanBasePackages = {"org.qinan.safetyeval", "com.jjb.saas"})
@EnableDubbo
@EnableFeignClients(basePackages = {"org.qinan.safetyeval", "com.jjb.saas"})
@Slf4j
public class SafetyEvalApplication {

    public static void main(String[] args) {
        long startTimeMillis = System.currentTimeMillis();
        SpringApplication.run(SafetyEvalApplication.class, args);
        log.info("SafetyEvalApplication-启动成功-耗时：{} min", (((float)(System.currentTimeMillis() - startTimeMillis))/60000L));
    }

    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    removePathPatternHandlerMappings(bean);
                }
                return bean;
            }
        };
    }

    @SuppressWarnings("unchecked")
    private static void removePathPatternHandlerMappings(Object bean) {
        Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
        if (field == null) {
            return;
        }
        field.setAccessible(true);
        List<RequestMappingInfoHandlerMapping> mappings =
                (List<RequestMappingInfoHandlerMapping>) ReflectionUtils.getField(field, bean);
        if (mappings != null) {
            mappings.removeIf(mapping -> mapping.getPatternParser() != null);
        }
    }
}
