package com.sy.coinage.config;

import io.swagger.annotations.ApiOperation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

@EnableOpenApi
@Configuration
public class Swagger3Config {

    /**
     * 创建API
     */
    @Bean
    public Docket createRestApi() {

        ApiInfo apiInfo = new ApiInfoBuilder()
                        // 设置标题
                        .title("系统接口文档")
                        // 描述
                        .description("描述：...")
                        // 作者信息
                        .contact(new Contact("MaxPanda", null, null))
                        // 版本
                        .version("版本号:" + "1.0").build();
        return new Docket(DocumentationType.SWAGGER_2)
                        // 是否启用Swagger
                        .enable(true)
                        // 用来创建该API的基本信息，展示在文档的页面中（自定义展示的信息）
                        .apiInfo(apiInfo)
                        // 设置哪些接口暴露给Swagger展示
                        .select()
                        // 扫描所有有注解的api，用这种方式更灵活
                        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                        // 扫描指定包中的swagger注解
                        // .apis(RequestHandlerSelectors.basePackage("com.sy.coinage.project.controller"))
                        // 扫描所有
                        // .apis(RequestHandlerSelectors.any())
                        // .paths(PathSelectors.any())
                        .build()
        /* 设置安全模式，swagger可以设置访问token */
        // .securitySchemes(securitySchemes())
        // .securityContexts(securityContexts())
        // .pathMapping(pathMapping)
        ;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    /**
     * 解决springboot2.6 和springfox不兼容问题
     *
     * @return
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(
                            List<T> mappings) {
                List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
                                .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

}
