package com.bonus.zlpt.common.swagger;

import com.bonus.zlpt.common.core.annotation.Excel;
import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.schema.Annotations;
import springfox.documentation.schema.ModelSpecification;
import springfox.documentation.schema.property.ModelSpecificationFactory;
import springfox.documentation.service.AllowableValues;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.schema.ApiModelPropertyPropertyBuilder;

import java.lang.reflect.AnnotatedElement;
import java.util.Optional;

/**
 * swagger扩展
 */
//@Component
//@Order(-2147482649)
public class ApiModelPropertyPropertyBuilderExtend extends ApiModelPropertyPropertyBuilder {

    private final DescriptionResolver descriptions;
    private final ModelSpecificationFactory modelSpecifications;

    public ApiModelPropertyPropertyBuilderExtend(DescriptionResolver descriptions, ModelSpecificationFactory modelSpecifications, DescriptionResolver descriptions1, ModelSpecificationFactory modelSpecifications1) {
        super(descriptions, modelSpecifications);
        this.descriptions = descriptions1;
        this.modelSpecifications = modelSpecifications1;
    }

    @Override
    public void apply(ModelPropertyContext context) {
        System.err.println("开始加载");
        Optional<Excel> annotation = Optional.empty();
        if (context.getAnnotatedElement().isPresent()) {
            System.err.println("1");
            annotation = (Optional)annotation.map(Optional::of).orElse(ApiModelPropertiesExtend.findApiModePropertyAnnotation((AnnotatedElement)context.getAnnotatedElement().get()));
        }

        if (context.getBeanPropertyDefinition().isPresent()) {
            System.err.println("2");
            annotation = (Optional)annotation.map(Optional::of).orElse(Annotations.findPropertyAnnotation((BeanPropertyDefinition)context.getBeanPropertyDefinition().get(), Excel.class));
        }

        if (annotation.isPresent()) {
            ModelSpecification modelSpecification = (ModelSpecification)annotation.map((a) -> {
                return !a.defaultValue().isEmpty() ? this.modelSpecifications.create(context.getOwner(), (ResolvedType)ApiModelPropertiesExtend.toType(context.getResolver()).apply(a)) : null;
            }).orElse(null);
            context.getSpecificationBuilder().description((String)annotation.map(ApiModelPropertiesExtend.toDescription(this.descriptions)).orElse(null));

            context.getBuilder().allowableValues((AllowableValues)annotation.map(ApiModelPropertiesExtend.toAllowableValues()).orElse(null));
        }

    }
}
