package com.zhongshu.card.server.core.service.openAPI;

import com.github.microservice.models.openAPI.OpenApiInfo;
import com.github.microservice.models.openAPI.RefreshApiParam;
import com.github.microservice.net.ResultContent;
import com.github.microservice.utils.OpenAPIScan;
import com.zhongshu.opengateway.client.type.ApiType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 注册平台所有的API
 *
 * @author TRX
 * @date 2024/9/29
 */
@Slf4j
@Service
public class OpenAPIRegisterService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.application.name}")
    private String serviceId;

    public ResultContent initRegisterPAIS() {
        String str = restTemplate.getForObject("http://" + serviceId + "/v3/api-docs", String.class);
        String sign = "openAPI";
        List<OpenApiInfo> openAPIS = OpenAPIScan.scanAPI(str, "一卡通", sign);
        RefreshApiParam param = new RefreshApiParam();
        param.setServerName(serviceId.toLowerCase());
        param.setPredicateArgs(String.format("/%s/**", sign));
        param.setOpenApiInfo(openAPIS);
        param.setApiType(ApiType.FullCard.name());
        param.setApiDocs(OpenAPIScan.filterOpenApi(str, sign));
        ResultContent content = restTemplate.postForObject("http://openapiserver/manager/gateway/api/refresh", param, ResultContent.class);
        if (content == null) {
            content = ResultContent.buildSuccess();
        }
        if (content.isFailed()) {
            log.info("openApi注册错误: {}", content.getMsg());
        } else {
            log.info("openApi注册成功");
        }
        str = null;
        return ResultContent.buildSuccess();
    }

}
