package com.njcn.swagger.config;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @author hongawen
 * @version 1.0.0
 * @createTime 2021年03月23日 19:51
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jSwaggerConfig {

    // 定义分隔符
    private static final String SPLITOR = ";";

    @Value("${microservice.name}")
    private String microserviceName;

    @Value("${microservice.version}")
    private String microserviceVersion;

    @Value("${microservice.gateway.url}")
    private String gatewayUrl;

    @Value("${swagger.enable:true}")
    private Boolean swaggerEnable;

    /**
     * swagger通用配置
     */
    @Bean(value = "defaultApi")
    @Order(value = 1)
    public Docket defaultApi() {
        List<String> controllerPath = Stream.of(
                "com.njcn.user.controller",
                "com.njcn.prepare.harmonic.controller",
                "com.njcn.prepare.event.controller",
                "com.njcn.device.pq.controller",
                "com.njcn.device.terminal.controller",
                "com.njcn.device.pms.controller",
                "com.njcn.auth.controller",
                "com.njcn.system.controller",
                "com.njcn.harmonic.controller",
                "com.njcn.event.controller",
                "com.njcn.energy.controller",
                "com.njcn.quality.controller",
                "com.njcn.process.controller",
                "com.njcn.advance.controller",
                "com.njcn.algorithm.controller",
                "com.njcn.access.controller",
                "com.njcn.csdevice.controller",
                "com.njcn.cswarn.controller",
                "com.njcn.csharmonic.controller",
                "com.njcn.cssystem.controller",
                "com.njcn.csreport.controller",
                "com.njcn.advance.controller",
                "com.njcn.stat.controller",
                "com.njcn.rt.controller",
                "com.njcn.zlevent.controller",
                "com.njcn.cloud.controller",
                "com.njcn.zlevent.controller",
                "com.njcn.prepare",
                "com.njcn.supervision.controller",
                "com.njcn.algorithm",
                "com.njcn.dataProcess",
                "com.njcn.migration",
                "com.njcn.harmonic.rstatlimitrate.controller",
                "com.njcn.device.device.controller",
                "com.njcn.device.userledger.controller",
                "com.njcn.migration.read.controller"
                )
                .collect(Collectors.toList());
        List<GrantType> grantTypes = new ArrayList<>();
        String passwordTokenUrl = "http://" + gatewayUrl + "/pqs-auth/oauth/token";
        ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl);
        grantTypes.add(resourceOwnerPasswordCredentialsGrant);
        OAuth oAuth = new OAuthBuilder().name("oauth2").grantTypes(grantTypes).build();
        //schemas
        List<SecurityScheme> securitySchemes = Lists.newArrayList(oAuth);
        //securyContext
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(swaggerEnable)
                .select()
//                指定添加swagger注解的方法
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //这里指定Controller扫描包路径
                .apis(basePackage(String.join(SPLITOR, controllerPath)))
                .paths(PathSelectors.any())
                .build()
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes);
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(microserviceName).description(microserviceName)
                .version(microserviceVersion)
                .contact(contact())
                .build();
    }

    private Contact contact() {
        return new Contact("灿能系统组", "", "13914774158@163.com");
    }


    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.ant("/**"))
                        .build());
        return securityContexts;
    }

    List<SecurityReference> defaultAuth() {
        //scope方位
        List<AuthorizationScope> scopes = new ArrayList<>();
        scopes.add(new AuthorizationScope("read", "read  resources"));
        scopes.add(new AuthorizationScope("write", "write resources"));
        scopes.add(new AuthorizationScope("reads", "read all resources"));
        scopes.add(new AuthorizationScope("writes", "write all resources"));
        SecurityReference securityReference = new SecurityReference("oauth2", scopes.toArray(new AuthorizationScope[]{}));
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(securityReference);
        return securityReferences;
    }

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

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

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


}
