package com.cool.store.config.swagger;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 * @author zhangchenbiao
 * @description:
 * @date 2023/05/15 02:52
 */
@Profile({"local", "test", "pre"})
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {

    /**
     * 扫描接口地址的包名
     */
    public static final String BASE_PACKAGE = "com.cool.store.controller";

    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title("xfsg")
                .description("接口文档")
                .version("1.0")
                .build();
    }

    private Docket createDocket (String groupName, String... packages){
        List<Parameter> pars = getParameters();
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(Boolean.TRUE)
                .apiInfo(this.getApiInfo())
                .groupName(groupName)
                .select()
                .apis(this.scanBasePackage(packages))
                //.paths(PathSelectors.regex(".*/getPartnerIntentInfo|.*/queryPartnerClerkInfoList|.*/queryPartnerBaseInfo"))
                .build()
                .globalOperationParameters(pars);
    }

    private List<Parameter> getParameters() {
        return new ArrayList<>();
    }

    private Predicate<RequestHandler> scanBasePackage(final String... controllerPack) {
        Predicate<RequestHandler> predicate = null;
        for (String strBasePackage : controllerPack) {
            if(StringUtils.isNotBlank(strBasePackage)){
                Predicate<RequestHandler> tempPredicate = RequestHandlerSelectors.basePackage(strBasePackage);
                predicate = predicate == null ? tempPredicate : Predicates.or(tempPredicate,predicate);
            }
        }
        return predicate;
    }


    @Bean
    public Docket allApi() {
        return this.createDocket("全部", BASE_PACKAGE);
    }

}

