package com.nmgs.config;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.function.Function;
import java.util.function.Predicate;

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "dockerBean")
    public Docket dockerBean() {
        //指定使用Swagger2规范
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        //描述字段支持Markdown语法
                        .description("积分信息")
                        .termsOfServiceUrl("http://域名:端口/IntegralManager/")
                        .contact("天润科丰")
                        .version("1.0")
                        .build())
                //分组名称
                .groupName("积分服务")
                .select()
                //这里指定Controller扫描包路径
                .apis(basePackage("com.nmgs.controller"+";"+"com.nmgs.AppController"))
                //.apis(basePackage("com.nmgs.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    /**
     * 扫描多个包
     * @param basePackage
     * @return
     */
    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return (input) -> {
                // 循环判断匹配
                for (String strPackage : basePackage.split(";")) {
                    boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                    if (isMatch) {
                        return true;
                    }
                }
                return false;
            };
    }

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return (input) -> {
            return (Boolean)declaringClass(input).map(handlerPackage(basePackage)).orElse(true);
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.ofNullable(input.declaringClass());
    }
}