package com.blueland.config;


import com.blueland.annotation.ApiVersion;
import com.blueland.enums.Version;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.plugin.core.OrderAwarePluginRegistry;
import org.springframework.plugin.core.PluginRegistry;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.DocumentationPlugin;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.DocumentationPluginsManager;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Swagger3Config
 *
 * @author bigtian
 * @date 2021/4/16 16:50
 */
@Primary //自动装配时当出现多个Bean候选者时，被注解为@Primary的Bean将作为首选者，否则将抛出异常。（只对接口的多个实现生效）覆盖swagger自己的配置
@Configuration //定义配置类
//@EnableKnife4j //开启Knife4j
public class SwaggerDocumentationPluginsManager extends DocumentationPluginsManager {

    @Override
    public Collection<DocumentationPlugin> documentationPlugins() throws IllegalStateException {
        List<DocumentationPlugin> plugins = registry().getPlugins();
        ensureNoDuplicateGroups(plugins);
        return plugins.isEmpty() ? Collections.singleton(this.defaultDocumentationPlugin()) : plugins;
    }

    private void ensureNoDuplicateGroups(List<DocumentationPlugin> allPlugins) throws IllegalStateException {
        Map<String, List<DocumentationPlugin>> plugins = allPlugins.stream().collect(Collectors.groupingBy((input) -> {
            return Optional.ofNullable(input.getGroupName()).orElse("default");
        }, LinkedHashMap::new, Collectors.toList()));
        Iterable<String> duplicateGroups = plugins.entrySet().stream().filter((input) -> {
            return (input.getValue()).size() > 1;
        }).map(Map.Entry::getKey).collect(Collectors.toList());
        if (StreamSupport.stream(duplicateGroups.spliterator(), false).count() > 0L) {
            throw new IllegalStateException(String.format("Multiple Dockets with the same group name are not supported. The following duplicate groups were discovered. %s", String.join(",", duplicateGroups)));
        }
    }

    private DocumentationPlugin defaultDocumentationPlugin() {
        return new Docket(DocumentationType.OAS_30);
    }

    private SwaggerPluginRegistry registry() {
        List<Docket> list = new ArrayList<>();
        list.add(createRestApi());
        Version[] versions = Version.values();
        if (versions.length > 0) {
            for (Version version : versions) {
                Docket docket = new Docket(DocumentationType.OAS_30)
                        // 指定构建api文档的详细信息的方法：apiInfo()
                        .apiInfo(apiInfo(version.getVersion()))
                        .groupName(version.getVersion())
                        .select()
                        .apis(requestHandler -> {
                            //获取rest上的注解
                            Optional<ApiVersion> controllerAnnotation = requestHandler.findControllerAnnotation(ApiVersion.class);
                            // 如果rest上有ApiVersion注解，则不扫描类中方法，否则扫描类中方法
                            if (!controllerAnnotation.isPresent()) {
                                return findMehotds(version, requestHandler);
                            }
                            boolean flag = Arrays.asList(controllerAnnotation.get().groups()).contains(version);
                            if (!flag) {
                                return findMehotds(version, requestHandler);
                            }
                            return flag;
                        })
                        .paths(PathSelectors.any())
                        .build();
                list.add(docket);
            }
        }
        return new SwaggerPluginRegistry(list, new AnnotationAwareOrderComparator());
    }

    private boolean findMehotds(Version version, RequestHandler requestHandler) {
        Optional<ApiVersion> apiVersion = requestHandler.findAnnotation(ApiVersion.class);
        if (!apiVersion.isPresent()) {
            return false;
        }
        return Arrays.asList(apiVersion.get().groups()).contains(version);
    }

    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .groupName("All API")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.blueland"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(String version) {
        return new ApiInfoBuilder()
                .contact(new Contact("sys", null, null))
                // 设置页面标题
                .title("USM接口文档")
                .version(version)
                // 设置接口描述
                .description("通用框架接口")
                // 设置联系方式
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .contact(new Contact("sys", null, null))
                // 设置页面标题
                .title("USM接口文档")
                // 设置接口描述
                .description("通用框架接口")
                // 设置联系方式
                .build();
    }
}

/**
 * SwaggerPluginRegistry
 *
 * @author bigtian
 * @date 2021/4/16 16:55
 */
class SwaggerPluginRegistry extends OrderAwarePluginRegistry<DocumentationPlugin, DocumentationType> implements PluginRegistry<DocumentationPlugin, DocumentationType> {

    protected SwaggerPluginRegistry(List<Docket> plugins, Comparator<? super DocumentationPlugin> comparator) {
        super(plugins, comparator);
    }

    @Override
    public List<DocumentationPlugin> getPlugins() {
        return super.getPlugins();
    }
}
