package com.fufan.mtsaas.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.collect.Lists;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
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.EnableSwagger2;

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

/**
 * @ClassName: Swagger2
 * @description: swagger2的配置文件
 * @author: Lihua
 * @date: 2021-11-01 13:39
 * @version: V1.0
 **/
/*@Configuration
@EnableSwagger2
//是否开启swagger，正式环境一般是需要关闭的（避免不必要的漏洞暴露！），可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable",  havingValue = "true")*/


/**
 * @author Lihua
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
@EnableConfigurationProperties({XhDocProperties.class})
@ConditionalOnProperty(value = "fufan.doc.enable", havingValue = "true", matchIfMissing = true)
public class Knife4jConfig {


    private final XhDocProperties properties;

    public Knife4jConfig(XhDocProperties properties) {
        this.properties = properties;
    }

    @Bean
    @Order(-1)
    public Docket groupRestApi() {

        List<ResponseMessage> responseList =getGlobalResponseMessage();
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<>();
        //添加head
        tokenPar.name("Authorization").description("登录令牌,没有可以传空字符串").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        parameters.add(tokenPar.build());
//        tokenPar = new ParameterBuilder();
        //添加head
//        tokenPar.name("adminid").description("登录令牌,没有可以传空字符串").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        parameters.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2).useDefaultResponseMessages(false)
//                .globalResponseMessage(RequestMethod.GET, responseList)
//                .globalResponseMessage(RequestMethod.POST, responseList)
//                .globalResponseMessage(RequestMethod.PUT, responseList)
//                .globalResponseMessage(RequestMethod.DELETE, responseList)
                .apiInfo(groupApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
                .paths(PathSelectors.any())

                .build().securityContexts(Lists.newArrayList(securityContext())).securitySchemes(Lists.<SecurityScheme>newArrayList(apiKey())).globalOperationParameters(parameters);
    }

    private ApiInfo groupApiInfo() {
        String description = String.format("<div style='font-size:%spx;color:%s;'>%s</div>",
                properties.getDescriptionFontSize(), properties.getDescriptionColor(), properties.getDescription());

        Contact contact = new Contact(properties.getName(), properties.getUrl(), properties.getEmail());

        return new ApiInfoBuilder()
                .title(properties.getTitle())
                .description(description)
                .termsOfServiceUrl(properties.getTermsOfServiceUrl())
                .contact(contact)
                .license(properties.getLicense())
                .licenseUrl(properties.getLicenseUrl())
                .version(properties.getVersion())
                .build();
    }

    private ApiKey apiKey() {
        return new ApiKey("BearerToken", "Authorization", "header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes));
    }

    /**
     * 封装通用响应信息
     */
    private List<ResponseMessage> getGlobalResponseMessage() {
        List<ResponseMessage> responseList = new ArrayList<>();
        responseList.add(new ResponseMessageBuilder().code(200).message("成功").responseModel(new ModelRef("ApiError")).build());
        responseList.add(new ResponseMessageBuilder().code(401).message("未登录").responseModel(new ModelRef("ApiError")).build());
        responseList.add(new ResponseMessageBuilder().code(501).message("TOKEN失效").responseModel(new ModelRef("ApiError")).build());
        responseList.add(new ResponseMessageBuilder().code(508).message("缺TOKEN").responseModel(new ModelRef("ApiError")).build());
        responseList.add(new ResponseMessageBuilder().code(400).message("请求失败").responseModel(new ModelRef("ApiError")).build());
        responseList.add(new ResponseMessageBuilder().code(500).message("系统异常").responseModel(new ModelRef("ApiError")).build());
        return responseList;
    }
}
