package cn.hanghui.outapi.platform.common.config;

import cn.hanghui.outapi.platform.common.annotation.DecryptParam;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {

    @Value("${swagger.enabled}")
    private Boolean swaggerEnabled;

    @Value("${server.port}")
    private String port;

    @Bean
    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerEnabled)
                .securitySchemes(securitySchemes())
                .globalRequestParameters(globalRequestParameters())
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .groupName("1.X版本")
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)
                        .or(RequestHandlerSelectors.withClassAnnotation(DecryptParam.class)))
                .paths(PathSelectors.any())
                .build();
    }

    private List<RequestParameter> globalRequestParameters() {
        RequestParameterBuilder parameterBuilder = new RequestParameterBuilder()
                //每次请求加载header
                .in(ParameterType.HEADER)
                //头标签
                .name("Authorization")
                .required(false)
                .query(param -> param.model(model -> model.scalarModel(ScalarType.STRING)));
        return Collections.singletonList(parameterBuilder.build());
    }

    private ApiInfo apiInfo() {
        String apiDocUrl = "http://localhost:" + port + "/hanghui/outapi/doc.html#/home";
        System.out.println("接口文档地址：" + apiDocUrl);
        System.out.println("admin/hanghui2023");
        return new ApiInfoBuilder()
                .title("航汇外部接口服务")
                .description("航汇外部接口服务")
                .termsOfServiceUrl(apiDocUrl)
                .version("1.0")
                .build();
    }


    private List<SecurityScheme> securitySchemes() {
        return Collections.singletonList(new ApiKey("Authorization", "令牌", In.HEADER.name()));
    }
}
