package com.wecloud.dispatch.swagger;

import com.google.common.base.Optional;
import com.wecloud.dispatch.annotation.ActionMapping;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.condition.NameValueExpression;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class CustomOperationPlugin implements OperationBuilderPlugin {
    private final DescriptionResolver descriptions;
    @Autowired
    public CustomOperationPlugin(DescriptionResolver descriptions) {
        this.descriptions = descriptions;
    }
    @Override
    public void apply(OperationContext context) {
        Optional<ApiOperation> apiOperationOp = context.findAnnotation(ApiOperation.class);
        Optional<ActionMapping> acOp = context.findAnnotation(ActionMapping.class);
        if (apiOperationOp.isPresent() || acOp.isPresent()) {
            String notes = "";
            if(apiOperationOp.isPresent()) {
                notes = apiOperationOp.get().notes();
            }
            Optional<ActionMapping> hasActionMapping = context.findAnnotation(ActionMapping.class);
            //添加权限码到notes中
            if (hasActionMapping.isPresent()) {
                notes = notes + "需要注意的是：<br/> 1、这是websocket接口；<br/> 2、请用ws://调用 <br/> 3、请求参数外层需要包一层：" +
                        "{  <br/>" +
                        "\t\"reqId\": Long类型,  <br/>" +
                        "\t\"action\": 字符串类型（就是上面的地址）  <br/>" +
                        "\t\"data\": 真正的请求参数(就是下面的请求参数),  <br/>" +
                        "} ";
                //编辑api文档信息, notes
                context.operationBuilder().notes(descriptions.resolve(notes));
            }
        }
    }
    @Override
    public boolean supports(DocumentationType documentationType) {
        return SwaggerPluginSupport.pluginDoesApply(documentationType);
    }
}
