package com.microservices.mon.k8s.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.microservices.common.core.context.SecurityContextHolder;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.mon.k8s.domain.*;
import com.microservices.mon.k8s.domain.vo.*;
import com.microservices.mon.k8s.service.IK8sDashboardService;
import com.microservices.mon.k8s.service.IMicroManagementService;
import com.microservices.mon.k8s.service.IMonCommonAsyncService;
import com.microservices.mon.k8s.utils.*;
import com.microservices.system.api.RemoteGatewayService;
import com.microservices.system.api.RemoteRancherService;
import com.microservices.system.api.model.GraphqlQueryVo;
import com.microservices.system.api.utils.FeignUtils;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
@RefreshScope
public class MicroManagementServiceImpl extends CommonService implements IMicroManagementService {
    @Autowired
    private IMonCommonAsyncService monCommonAsyncService;
    @Autowired
    @Lazy
    private IK8sDashboardService dashboardService;
    @Autowired
    private RemoteRancherService remoteRancherService;
    @Autowired
    private RemoteGatewayService remoteGatewayService;


    @Override
    public List<K8sApplicationPod> getPodList() {
        return monCommonAsyncService.getPodList();
    }

    @Override
    public K8sPodContainerMetricOverview getPodStatus(String podName, Long step) {
        return monCommonAsyncService.getPodStatus(podName, step);
    }

    @Override
    public K8sApplication getApplicationDetail(String kind, String namespace, String applicationName) {
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        K8sApplication k8sApplication = new K8sApplication();
        JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
        if (applicationJson == null) {
            return k8sApplication;
        }
        RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
        k8sApplication = rancherApplicationVo.toK8sApplication();

        // 获取应用下pod列表
        List<K8sApplicationPod> podList = getK8sApplicationPodList(k8sApplication);
        k8sApplication.setPodList(podList);
        k8sApplication.setRestartCount(podList.stream().filter(x -> x.getRestartCount() != null).mapToInt(K8sApplicationPod::getRestartCount).sum());
        return k8sApplication;
    }

    @Override
    public Boolean deletePod(String namespace, String podName, Boolean isForce) {
        JSONObject deletePodBody = new JSONObject();
        if (isForce != null && isForce) {
            deletePodBody.put("force", true);
            deletePodBody.put("gracePeriod", 0);
        }
        try (Response response = remoteRancherService.deletePod(namespace, podName, deletePodBody, SecurityContextHolder.getUserKey())) {
            return RancherResponseHandler.handleBoolean(response, "删除容器");
        }
    }

    @Override
    public List<K8sApplicationPod> getK8sApplicationPodList(K8sApplication k8sApplication) {
        // 获取命名空间下pod列表
        JSONObject podListJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sPodListByNamespace(cluster_id, k8sApplication.getNamespace(), SecurityContextHolder.getUserKey()), "获取应用下容器列表");
        List<RancherPodVo> rancherPodVoList;
        if (podListJson != null && podListJson.containsKey("data")) {
            rancherPodVoList = podListJson.getJSONArray("data").toList(RancherPodVo.class);
            String podSelector = k8sApplication.getPodSelector();
            List<RancherPodVo> applicationToPodList = rancherPodVoList.stream()
                    .filter(rancherPodVo -> {
                        if (!StringUtils.isEmpty(podSelector)) {
                            String[] podSelectorArr = podSelector.split("=");
                            return rancherPodVo.getMetadata().getLabels().containsKey(podSelectorArr[0])
                                    && rancherPodVo.getMetadata().getLabels().get(podSelectorArr[0]).equals(podSelectorArr[1]);
                        }
                        return false;
                    })
                    .collect(Collectors.toList());
            return applicationToPodList.stream().map(RancherPodVo::toK8sApplicationPod).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public Boolean operateApplication(String kind, String namespace, String applicationName, String operationKey) {
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        ApplicationStartAndStopType applicationStartAndStopType = ApplicationStartAndStopType.getByKey(operationKey);
        if (!ApplicationStartAndStopType.containsKey(operationKey) || applicationStartAndStopType == null) {
            throw new ServiceException("该应用操作类型不存在(操作类型[%s])", operationKey);
        }
        if ("DaemonSet".equals(kind) && !applicationStartAndStopType.getIsDaemonSetOperation()) {
            throw new ServiceException("该应用操作类型不支持(操作类型[%s])", operationKey);
        }
        JSONObject applicationDetailJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
        if (applicationDetailJson == null || !applicationDetailJson.containsKey("metadata") || !applicationDetailJson.containsKey("spec")) {
            throw new ServiceException("该应用不存在或应用数据异常(应用类型[%s],命名空间[%s],应用名称[%s],)", kind, namespace, applicationName);
        }
        RancherApplicationVo rancherApplicationVo = applicationDetailJson.toJavaObject(RancherApplicationVo.class);
        K8sApplication k8sApplication = rancherApplicationVo.toK8sApplication();
        // 移除无用字段
        applicationDetailJson.remove("type");
        applicationDetailJson.remove("links");
        applicationDetailJson.remove("status");
        JSONObject metadataJson = applicationDetailJson.getJSONObject("metadata");
        metadataJson.remove("creationTimestamp");
        metadataJson.remove("generation");
        metadataJson.remove("managedFields");
        metadataJson.remove("relationships");
        metadataJson.remove("state");
        metadataJson.remove("uid");
        applicationDetailJson.put("metadata", metadataJson);
        JSONObject applicationSpecJson = applicationDetailJson.getJSONObject("spec");

        switch (applicationStartAndStopType) {
            case START: {
                if (k8sApplication.getReplicas() != null && k8sApplication.getReplicas() > 0) {
                    return true;
                }
                applicationSpecJson.put("replicas", 1);
                try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
                    return RancherResponseHandler.handleBoolean(response, "启动应用");
                }
            }
            case STOP: {
                applicationSpecJson.put("replicas", 0);
                try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
                    return RancherResponseHandler.handleBoolean(response, "停止应用");
                }
            }
            case FORCE_STOP: {
                applicationSpecJson.put("replicas", 0);
                try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
                    if (FeignUtils.isSuccess(response)) {
                        boolean delPodSuccess = true;
                        // 获取应用下pod列表
                        List<K8sApplicationPod> podList = getK8sApplicationPodList(k8sApplication);
                        if (podList != null) {
                            for (K8sApplicationPod pod : podList) {
                                // 强制删除Terminating状态pod
                                if (pod.getState().getName().equals("Terminating")) {
                                    // 删除pod失败时返回错误信息
                                    delPodSuccess = delPodSuccess && deletePod(pod.getNamespace(), pod.getName(), true);
                                }
                            }
                        }
                        return delPodSuccess;
                    }
                    return RancherResponseHandler.handleBoolean(response, "强制停止应用");
                }
            }
            case RESTART: {
                if (metadataJson.containsKey("annotations")) {
                    JSONObject annotations = metadataJson.getJSONObject("annotations");
                    Integer oldRevision = annotations.getInteger("deployment.kubernetes.io/revision");
                    if (oldRevision == null) {
                        oldRevision = 1;
                    }
                    annotations.put("deployment.kubernetes.io/revision", String.valueOf(oldRevision + 1));
                    metadataJson.put("annotations", annotations);

                    JSONObject templateJson = applicationSpecJson.getJSONObject("template");
                    if (templateJson == null) {
                        templateJson = new JSONObject();
                    }
                    JSONObject metadataTemplateJson = templateJson.getJSONObject("metadata");
                    if (metadataTemplateJson == null) {
                        metadataTemplateJson = new JSONObject();
                    }
                    JSONObject annotationsTemplateJson = metadataTemplateJson.getJSONObject("annotations");
                    if (annotationsTemplateJson == null) {
                        annotationsTemplateJson = new JSONObject();
                    }

                    annotationsTemplateJson.put("kubectl.kubernetes.io/restartedAt", DateUtils.getNowDate());
                    metadataTemplateJson.put("annotations", annotationsTemplateJson);
                    templateJson.put("metadata", metadataTemplateJson);
                    applicationSpecJson.put("template", templateJson);
                    applicationDetailJson.put("spec", applicationSpecJson);
                    applicationDetailJson.put("metadata", metadataJson);
                    try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
                        return RancherResponseHandler.handleBoolean(response, "重启应用");
                    }
                }

                break;
            }
            case PAUSED: {
                applicationSpecJson.put("paused", true);
                applicationDetailJson.put("spec", applicationSpecJson);
                try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
                    return RancherResponseHandler.handleBoolean(response, "暂停应用");
                }
            }
            case RESUME: {
                applicationSpecJson.put("paused", false);
                applicationDetailJson.put("spec", applicationSpecJson);
                try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
                    return RancherResponseHandler.handleBoolean(response, "恢复应用");
                }
            }
        }
        return false;
    }

    @Override
    public List<ApplicationTypeVo> getApplicationTypeList() {
        List<ApplicationTypeVo> applicationTypeList = new ArrayList<>();
        for (ApplicationType applicationType : ApplicationType.values()) {
            ApplicationTypeVo applicationTypeVo = new ApplicationTypeVo();
            applicationTypeVo.setKey(applicationType.getKey());
            applicationTypeVo.setFullName(applicationType.getFullName());
            applicationTypeVo.setDescription(applicationType.getDescription());
            applicationTypeList.add(applicationTypeVo);
        }
        return applicationTypeList;
    }

    @Override
    public String createApplication(String kind, String yamlContent) {
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        StringBuilder yamlBuilder = new StringBuilder();
        try {
            Yaml yaml = new Yaml();
            Iterable<Object> yamls = yaml.loadAll(yamlContent);
            boolean isContainApplicationKind = false;
            for (Object yamlObject : yamls) {
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(yamlObject));
                String currentKind = jsonObject.getString("kind");
                if (currentKind == null) {
                    jsonObject.put("kind", applicationType.getKey());
                    isContainApplicationKind = true;
                } else if (ApplicationType.isApplicationType(currentKind)) {
                    jsonObject.put("kind", applicationType.getKey());
                    isContainApplicationKind = true;
                }
                JsonNode jsonNode = new ObjectMapper().readTree(jsonObject.toJSONString());
                String resourceYamlStr = new YAMLMapper().writeValueAsString(jsonNode);
                yamlBuilder.append(resourceYamlStr);

            }
            if (!isContainApplicationKind) {
                throw new ServiceException("编排文件格式错误，未包含需要创建的应用");
            }
        } catch (JsonProcessingException exception) {
            throw new ServiceException("编排文件格式错误");
        }

        JSONObject applyK8sYamlJson = new JSONObject();
        applyK8sYamlJson.put("defaultNamespace", "default");
        applyK8sYamlJson.put("yaml", yamlBuilder.toString());

        try (Response response = remoteRancherService.applyK8sYaml(cluster_id, applyK8sYamlJson, SecurityContextHolder.getUserKey())) {
            JSONObject resJson = RancherResponseHandler.handleJsonObject(response, "创建应用");
            StringBuilder applyMsg = new StringBuilder();
            if (resJson != null && resJson.getJSONArray("data") != null) {
                JSONArray dataArray = resJson.getJSONArray("data");
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    String createKind = data.getString("kind");
                    String resourceName = "";
                    String namespace = "";
                    if (data.getJSONObject("metadata") != null) {
                        if (data.getJSONObject("metadata").containsKey("name")) {
                            resourceName = String.format("【%s】", data.getJSONObject("metadata").getString("name"));
                        }
                        if (data.getJSONObject("metadata").containsKey("namespace")) {
                            namespace = String.format("在 %s 命名空间下", data.getJSONObject("metadata").getString("namespace"));
                        }
                    }
                    applyMsg.append(String.format("成功%s创建 %s 类型资源%s;\n", namespace, createKind, resourceName));
                }
            }
            return String.valueOf(applyMsg);
        }
    }

    @Override
    public JSONObject getApplicationYamlFile(String kind, String namespace, String applicationName) {
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        return RancherResponseHandler.handleJsonObject(remoteRancherService.getApplicationYamlFile(applicationType.getName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用yaml文件");
    }

    @Override
    public Boolean editApplication(String kind, String namespace, String applicationName, String yamlContent) {
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        try (Response response = remoteRancherService.editK8sApplication(applicationType.getFullName(), namespace, applicationName, yamlContent, SecurityContextHolder.getUserKey())) {
            return RancherResponseHandler.handleBoolean(response, "编辑应用");
        }
    }

    @Override
    public Boolean deleteApplication(String kind, String namespace, String applicationName) {
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
        if (applicationJson == null) {
            throw new ServiceException("删除失败：【%s】命名空间下【%s】应用不存在", namespace, applicationName);
        }
        RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
        if (rancherApplicationVo.getSpec() != null && rancherApplicationVo.getSpec().getJSONObject("template") != null && rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("metadata") != null && rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("metadata").containsKey("labels")) {
            JSONObject applicationLabelJson = rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("metadata").getJSONObject("labels");
            JSONObject k8sSvcByNamespaceJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sServiceByNamespace(cluster_id, namespace, SecurityContextHolder.getUserKey()), "获取指定命名空间下的K8s服务列表");
            if (k8sSvcByNamespaceJson != null && k8sSvcByNamespaceJson.getJSONArray("data") != null) {
                List<RancherServiceVo> k8sSvcList = k8sSvcByNamespaceJson.getJSONArray("data").toJavaList(RancherServiceVo.class);
                for (RancherServiceVo rancherServiceVo : k8sSvcList) {
                    if (rancherServiceVo.getSpec() != null && rancherServiceVo.getSpec().getSelector() != null) {
                        JSONObject selectorJson = rancherServiceVo.getSpec().getSelector();
                        for (String key : applicationLabelJson.keySet()) {
                            if (selectorJson.containsKey(key) && selectorJson.getString(key).equals(applicationLabelJson.getString(key))) {
                                try (Response response = remoteRancherService.deleteK8sService(rancherServiceVo.getId(), SecurityContextHolder.getUserKey())) {
                                    log.info("删除K8s服务【{}】成功：响应状态码：{}，响应结果：{}", rancherServiceVo.getId(), response.status(), response.reason());
                                } catch (Exception e) {
                                    log.error("删除K8s服务【{}】失败,失败原因：{}", rancherServiceVo, e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }
        try (Response response = remoteRancherService.deleteApplication(applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey())) {
            return RancherResponseHandler.handleBoolean(response, "删除应用");
        }
    }

    @Override
    public List<K8sApplicationEnv> getApplicationEnv(String kind, String namespace, String applicationName) {
        List<K8sApplicationEnv> envList = new ArrayList<>();
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
        if (applicationJson == null) {
            return envList;
        }
        RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
        if (rancherApplicationVo.getSpec() != null && rancherApplicationVo.getSpec().getJSONObject("template") != null && rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("spec") != null) {
            JSONArray containersJson = rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("spec").getJSONArray("containers");
            // TODO: 暂时只考虑第一个容器
            if (containersJson != null && !containersJson.isEmpty()) {
                JSONObject containerJson = containersJson.getJSONObject(0);
                if (containerJson != null) {
                    JSONArray envJsonList = containerJson.getJSONArray("env");
                    if (envJsonList != null && !envJsonList.isEmpty()) {
                        for (int i = 0; i < envJsonList.size(); i++) {
                            JSONObject envJson = envJsonList.getJSONObject(i);
                            K8sApplicationEnv k8sApplicationEnv = K8sApplicationEnv.envJsonObjectToK8sApplicationEnv(envJson);
                            if (k8sApplicationEnv != null) {
                                envList.add(k8sApplicationEnv);
                            }
                        }
                    }
                    JSONArray envFromJsonList = containerJson.getJSONArray("envFrom");
                    if (envFromJsonList != null && !envFromJsonList.isEmpty()) {
                        for (int i = 0; i < envFromJsonList.size(); i++) {
                            JSONObject envFromJson = envFromJsonList.getJSONObject(i);
                            K8sApplicationEnv k8sApplicationEnv = K8sApplicationEnv.envFromJsonObjectToK8sApplicationEnv(envFromJson);
                            if (k8sApplicationEnv != null) {
                                envList.add(k8sApplicationEnv);
                            }

                        }
                    }
                }
            }
        }
        return envList;
    }

    @Override
    public List<K8sApplicationEnvOptionalParameter> getEnvOptionalParameters(String namespace) {
        List<K8sApplicationEnvOptionalParameter> envOptionalParametersList = new ArrayList<>();
        JSONObject configmapJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sConfigmapByNamespace(namespace, SecurityContextHolder.getUserKey()), "获取命名空间下所有ConfigMap");
        if (configmapJson != null && configmapJson.containsKey("data")) {
            JSONArray dataJsonArray = configmapJson.getJSONArray("data");
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject dataJson = dataJsonArray.getJSONObject(i);
                if (dataJson != null && dataJson.containsKey("metadata") && dataJson.containsKey("data")) {
                    JSONObject metadataJson = dataJson.getJSONObject("metadata");
                    if (metadataJson != null && metadataJson.containsKey("name")) {
                        K8sApplicationEnvOptionalParameter k8sApplicationEnvOptionalParameter = new K8sApplicationEnvOptionalParameter();
                        String configmapName = metadataJson.getString("name");
                        if (configmapName != null) {
                            k8sApplicationEnvOptionalParameter.setType(ApplicationEnvType.CONFIGMAP.getKey());
                            k8sApplicationEnvOptionalParameter.setName(configmapName);
                            JSONObject configmapDataJson = dataJson.getJSONObject("data");
                            List<String> keys = new ArrayList<>(configmapDataJson.keySet());
                            k8sApplicationEnvOptionalParameter.setKeys(keys);
                            envOptionalParametersList.add(k8sApplicationEnvOptionalParameter);
                        }
                    }
                }
            }
        }
        JSONObject secretJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sSecretByNamespace(namespace, SecurityContextHolder.getUserKey()), "获取命名空间下所有Secret");
        if (secretJson != null && secretJson.containsKey("data")) {
            JSONArray dataJsonArray = secretJson.getJSONArray("data");
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject dataJson = dataJsonArray.getJSONObject(i);
                if (dataJson != null && dataJson.containsKey("metadata") && dataJson.containsKey("data")) {
                    JSONObject metadataJson = dataJson.getJSONObject("metadata");
                    if (metadataJson != null && metadataJson.containsKey("name")) {
                        K8sApplicationEnvOptionalParameter k8sApplicationEnvOptionalParameter = new K8sApplicationEnvOptionalParameter();
                        String configmapName = metadataJson.getString("name");
                        if (configmapName != null) {
                            k8sApplicationEnvOptionalParameter.setType(ApplicationEnvType.SECRET.getKey());
                            k8sApplicationEnvOptionalParameter.setName(configmapName);
                            JSONObject configmapDataJson = dataJson.getJSONObject("data");
                            List<String> keys = new ArrayList<>(configmapDataJson.keySet());
                            k8sApplicationEnvOptionalParameter.setKeys(keys);
                            envOptionalParametersList.add(k8sApplicationEnvOptionalParameter);
                        }
                    }
                }
            }
        }

        // 设置资源可选参数
        K8sApplicationEnvOptionalParameter k8sApplicationEnvOptionalParameter = new K8sApplicationEnvOptionalParameter();
        k8sApplicationEnvOptionalParameter.setType(ApplicationEnvType.RESOURCE.getKey());
        k8sApplicationEnvOptionalParameter.setName("");
        List<String> resourceKeys = new ArrayList<>();
        resourceKeys.add("limits.cpu");
        resourceKeys.add("limits.ephemeral-storage");
        resourceKeys.add("limits.memory");
        resourceKeys.add("requests.cpu");
        resourceKeys.add("requests.ephemeral-storage");
        resourceKeys.add("requests.memory");
        k8sApplicationEnvOptionalParameter.setKeys(resourceKeys);
        envOptionalParametersList.add(k8sApplicationEnvOptionalParameter);
        return envOptionalParametersList;
    }

    @Override
    public Boolean updateApplicationEnv(String kind, String namespace, String applicationName, List<K8sApplicationEnv> k8sApplicationEnvList) {
        ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
        JSONObject applicationDetailJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
        if (applicationDetailJson == null || !applicationDetailJson.containsKey("spec")) {
            throw new ServiceException("该应用不存在或应用数据异常(应用类型[%s],命名空间[%s],应用名称[%s],)", kind, namespace, applicationName);
        }

        JSONObject specJson = applicationDetailJson.getJSONObject("spec");
        if (specJson.containsKey("template")) {
            JSONObject templateJson = specJson.getJSONObject("template");
            if (templateJson.containsKey("spec")) {
                JSONObject templateSpecJson = templateJson.getJSONObject("spec");
                if (templateSpecJson.containsKey("containers")) {
                    JSONArray containersJson = templateSpecJson.getJSONArray("containers");
                    // TODO: 暂时只考虑第一个容器
                    if (containersJson != null && !containersJson.isEmpty()) {
                        JSONObject containerJson = containersJson.getJSONObject(0);
                        if (containerJson != null) {
                            containersJson.set(0, updateApplicationContainerEnv(k8sApplicationEnvList, containerJson));
                        }
                        templateSpecJson.put("containers", containersJson);
                    }
                    templateJson.put("spec", templateSpecJson);
                }
                specJson.put("template", templateJson);
            }
            applicationDetailJson.put("spec", specJson);
        }


        try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
            return RancherResponseHandler.handleBoolean(response, "更新应用环境变量", "环境变量格式异常");
        }
    }

    @Override
    public List<ApplicationEnvTypeVo> getEnvTypes() {
        List<ApplicationEnvTypeVo> applicationEnvTypeVoList = new ArrayList<>();
        for (ApplicationEnvType applicationEnvType : ApplicationEnvType.values()) {
            ApplicationEnvTypeVo applicationEnvTypeVo = new ApplicationEnvTypeVo();
            applicationEnvTypeVo.setKey(applicationEnvType.getKey());
            applicationEnvTypeVo.setAlias(applicationEnvType.getAlias());
            applicationEnvTypeVoList.add(applicationEnvTypeVo);
        }
        return applicationEnvTypeVoList;
    }

    @Override
    public List<GatewayRouteConfig> getGatewayRouteConfig() {
        List<GatewayRouteConfig> routeConfigList = new ArrayList<>();
        JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
        if (nacosGatewayConfigJson.containsKey("spring")) {
            JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
            if (springJson.containsKey("cloud")) {
                JSONObject cloudJson = springJson.getJSONObject("cloud");
                if (cloudJson.containsKey("gateway")) {
                    JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
                    routeConfigList = gatewayJson.getJSONArray("routes").toJavaList(GatewayRouteConfig.class);
                }
            }
        }
        return routeConfigList;
    }

    @Override
    public Boolean updateGatewayRouteConfig(List<GatewayRouteConfig> gatewayRouteConfigList) {
        JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
        if (nacosGatewayConfigJson.containsKey("spring")) {
            JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
            if (springJson.containsKey("cloud")) {
                JSONObject cloudJson = springJson.getJSONObject("cloud");
                if (cloudJson.containsKey("gateway")) {
                    JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
                    JSONArray routeConfigListJson = JSONArray.parseArray(JSON.toJSONString(gatewayRouteConfigList));
                    gatewayJson.put("routes", routeConfigListJson);
                    cloudJson.put("gateway", gatewayJson);
                }
                springJson.put("cloud", cloudJson);
            }
            nacosGatewayConfigJson.put("spring", springJson);
        }
        return updateNacosGatewayConfig(nacosGatewayConfigJson);
    }

    @Override
    public GatewaySafetyConfig getGatewaySafetyConfig() {
        GatewaySafetyConfig gatewaySafetyConfig = new GatewaySafetyConfig();
        JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
        if (nacosGatewayConfigJson.containsKey("spring")) {
            JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
            if (springJson.containsKey("cloud")) {
                JSONObject cloudJson = springJson.getJSONObject("cloud");
                if (cloudJson.containsKey("gateway")) {
                    JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
                    if (gatewayJson.containsKey("globalcors")) {
                        JSONObject globalcorsJson = gatewayJson.getJSONObject("globalcors");
                        if (globalcorsJson.containsKey("cors-configurations")) {
                            JSONObject corsConfigurationsJson = globalcorsJson.getJSONObject("cors-configurations");
                            if (corsConfigurationsJson.containsKey("[/**]")) {
                                gatewaySafetyConfig = corsConfigurationsJson.getJSONObject("[/**]").toJavaObject(GatewaySafetyConfig.class);
                            }
                        }
                    }
                }
            }
        }
        return gatewaySafetyConfig;
    }

    @Override
    public Boolean updateGatewaySafetyConfig(GatewaySafetyConfig gatewaySafetyConfig) {
        JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
        if (nacosGatewayConfigJson.containsKey("spring")) {
            JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
            if (springJson.containsKey("cloud")) {
                JSONObject cloudJson = springJson.getJSONObject("cloud");
                if (cloudJson.containsKey("gateway")) {
                    JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
                    if (gatewayJson.containsKey("globalcors")) {
                        JSONObject globalcorsJson = gatewayJson.getJSONObject("globalcors");
                        if (globalcorsJson.containsKey("cors-configurations")) {
                            JSONObject corsConfigurationsJson = globalcorsJson.getJSONObject("cors-configurations");
                            if (corsConfigurationsJson.containsKey("[/**]")) {
                                JSONObject corsConfigurationsValueJson = JSONObject.from(gatewaySafetyConfig);
                                corsConfigurationsJson.put("[/**]", corsConfigurationsValueJson);
                                globalcorsJson.put("cors-configurations", corsConfigurationsJson);
                            }
                            gatewayJson.put("globalcors", globalcorsJson);
                        }
                        cloudJson.put("gateway", gatewayJson);
                    }
                    springJson.put("cloud", cloudJson);
                }
                nacosGatewayConfigJson.put("spring", springJson);
            }
            nacosGatewayConfigJson.put("spring", springJson);
        }
        return updateNacosGatewayConfig(nacosGatewayConfigJson);
    }

    @Override
    public GatewayWhitelistConfig getGatewayWhitelistConfig() {
        GatewayWhitelistConfig gatewayWhitelistConfig = new GatewayWhitelistConfig();
        JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
        if (nacosGatewayConfigJson.containsKey("security")) {
            JSONObject securityJson = nacosGatewayConfigJson.getJSONObject("security");
            if (securityJson.containsKey("ignore")) {
                gatewayWhitelistConfig = securityJson.getJSONObject("ignore").toJavaObject(GatewayWhitelistConfig.class);
            }
        }
        return gatewayWhitelistConfig;
    }

    @Override
    public Boolean updateGatewayWhitelistConfig(GatewayWhitelistConfig gatewayWhitelistConfig) {
        JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
        if (nacosGatewayConfigJson.containsKey("security")) {
            JSONObject securityJson = nacosGatewayConfigJson.getJSONObject("security");
            if (securityJson.containsKey("ignore")) {
                JSONObject ignoreJson = JSONObject.from(gatewayWhitelistConfig);
                securityJson.put("ignore", ignoreJson);
                nacosGatewayConfigJson.put("security", securityJson);
            }
            nacosGatewayConfigJson.put("security", securityJson);
        }
        return updateNacosGatewayConfig(nacosGatewayConfigJson);
    }

    @Override
    public List<String> getExceptionHandingDateList() {
        List<String> dateList = new ArrayList<>();
        File gatewayLogPathDir = new File(gatewayLogPath);
        if (gatewayLogPathDir.exists() && gatewayLogPathDir.isDirectory()) {
            File[] listFiles = gatewayLogPathDir.listFiles();
            if (listFiles != null) {
                for (File file : listFiles) {
                    if (!file.isDirectory()) {
                        String fileName = file.getName();
                        if (fileName.endsWith(".log") && fileName.contains("error")) {
                            if (fileName.equalsIgnoreCase("error.log")) {
                                dateList.add("今天");
                            } else {
                                dateList.add(file.getName().replace("error.", "").replace(".log", ""));
                            }
                        }
                    }
                }
            }

        }
        dateList.sort(Comparator.reverseOrder());
        return dateList;
    }

    @Override
    public List<String> getExceptionHandingRecordList(String date) {
        List<String> errLogList = new ArrayList<>();
        String dateLogFile;
        if (StringUtils.isEmpty(date) || date.equals("今天")) {
            dateLogFile = "error.log";
        } else {
            dateLogFile = "error." + date + ".log";
        }
        Path logPath = Paths.get(gatewayLogPath);
        Path dateLogFilePath = logPath.resolve(dateLogFile);
        if (!Files.exists(dateLogFilePath)) {
            throw new ServiceException("该日期网关异常处理记录不存在(日期[%s])", date);
        }
        try {
            try (Stream<String> lines = Files.lines(dateLogFilePath)) {
                lines.forEach(line -> {
                    if (line.contains("异常处理")) {
                        errLogList.add(line);
                    }
                });
            }
        } catch (IOException e) {
            log.error("该日期网关异常处理记录读取失败：{}", e.getMessage());
            throw new ServiceException("该日期网关异常处理记录读取失败(日期[%s])", date);
        }
        errLogList.sort(Comparator.reverseOrder());
        return errLogList;
    }

    @Override
    public List<LinkTrackingApplication> getLinkTrackingList(String applicationName) {
        List<LinkTrackingApplication> linkTrackingApplicationList = new ArrayList<>();
        String search = skywalkingGroup + "::";
        // 查询服务列表
        GraphqlQueryVo gqlQueryVo = SkywalkingGQLConstant.searchServicesByKeyword(search);
        JSONObject skywalkingServices = remoteGatewayService.executeSkywalkingGql(gqlQueryVo);
        if (skywalkingServices != null
                && skywalkingServices.getJSONObject("data") != null
                && skywalkingServices.getJSONObject("data").getJSONArray(gqlQueryVo.getOperationName()) != null) {
            JSONArray skywalkingServicesArray = skywalkingServices.getJSONObject("data").getJSONArray(gqlQueryVo.getOperationName());
            int index = 1;
            for (int i = 0; i < skywalkingServicesArray.size(); i++) {
                JSONObject skywalkingService = skywalkingServicesArray.getJSONObject(i);
                String shortName = skywalkingService.getString("shortName");
                if (StringUtils.isEmpty(applicationName) || shortName.contains(applicationName)) {
                    LinkTrackingApplication linkTrackingApplication = new LinkTrackingApplication();
                    linkTrackingApplication.setIndex(index);
                    linkTrackingApplication.setId(skywalkingService.getString("id"));
                    linkTrackingApplication.setKey(skywalkingService.getString("name"));
                    linkTrackingApplication.setApplicationName(shortName);
                    linkTrackingApplicationList.add(linkTrackingApplication);
                    index++;
                }
            }

            // 查询服务状态列表
            gqlQueryVo = SkywalkingGQLConstant.queryMetricDataList(linkTrackingApplicationList);
            JSONObject skywalkingMetricDataList = remoteGatewayService.executeSkywalkingGql(gqlQueryVo);
            if (skywalkingMetricDataList != null
                    && skywalkingMetricDataList.getJSONObject("data") != null) {
                JSONObject data = skywalkingMetricDataList.getJSONObject("data");
                for (int i = 0; i < linkTrackingApplicationList.size(); i++) {
                    LinkTrackingApplication linkTrackingApplication = linkTrackingApplicationList.get(i);
                    for (SkywalkingMetricType metricType : SkywalkingMetricType.values()) {
                        String functionName = metricType.getFunctionName(linkTrackingApplication.getIndex());
                        JSONObject functionData = data.getJSONObject(functionName);
                        if (functionData != null && functionData.getJSONObject("values") != null && functionData.getJSONObject("values").getJSONArray("values") != null) {
                            JSONArray valuesArray = functionData.getJSONObject("values").getJSONArray("values");
                            float metricValue = 0;
                            for (int j = 0; j < valuesArray.size(); j++) {
                                JSONObject value = valuesArray.getJSONObject(j);
                                metricValue += value.getFloatValue("value");
                            }
                            metricValue = metricValue / valuesArray.size();
                            String valueStr;
                            switch (metricType) {
                                case SERVICE_CPM:
                                    valueStr = String.format("%.2f", metricValue);
                                    linkTrackingApplication.setLoad(Float.parseFloat(valueStr));
                                    break;
                                case SERVICE_SLA:
                                    valueStr = String.format("%.2f", metricValue / 100);
                                    linkTrackingApplication.setSuccessRate(Float.parseFloat(valueStr));
                                    break;
                                case SERVICE_RESP_TIME:
                                    valueStr = String.format("%.2f", metricValue);
                                    linkTrackingApplication.setLatency(Float.parseFloat(valueStr));
                                    break;
                            }
                        }
                    }
                    linkTrackingApplicationList.set(i, linkTrackingApplication);
                }
            }

        }
        return linkTrackingApplicationList;
    }

    @Override
    public JSONObject getGatewayFlowLimitingPara() {
        JSONObject gatewayFlowLimitingPara = new JSONObject();
        JSONArray sentinelAppListArray = dashboardService.getSentinelAppList();
        for (int i = 0; i < sentinelAppListArray.size(); i++) {
            JSONObject sentinelApp = sentinelAppListArray.getJSONObject(i);
            if (sentinelApp.getLongValue("appType") == 11) {
                gatewayFlowLimitingPara.put("app", sentinelApp.getString("app"));
                gatewayFlowLimitingPara.put("appType", sentinelApp.getLongValue("appType"));
                return gatewayFlowLimitingPara;
            }
        }
        return gatewayFlowLimitingPara;
    }

    @Override
    public GenericsTableDataInfo<K8SEvent> getK8SEventList(String eventType, String reason, Date startTime, Date endTime, Boolean isAscOrderByOccurredTime, Integer pageNum, Integer pageSize) {
        JSONObject eventListQueryBody = ESQueryUtils.buildEventListQueryBody(eventType, reason, startTime, endTime, isAscOrderByOccurredTime, pageNum, pageSize);
        JSONObject esQueryRes = remoteGatewayService.executeElasticsearchQuery(esK8sEventIndex, eventListQueryBody);
        return K8SEvent.toK8SEventTable(esQueryRes);
    }

    @Override
    public List<CommonTypeVo> getK8SEventReasonList(String eventType) {
        JSONObject eventReasonListQueryRes = remoteGatewayService.executeElasticsearchQuery(esK8sEventIndex, ESQueryUtils.buildEventReasonListQueryBody(eventType));
        return CommonTypeVo.eventReasonListToCommonTypeVoList(eventReasonListQueryRes);
    }

    @Override
    public List<CommonTypeVo> getResourceObjectList() {
        JSONObject nodeInfoRes = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.NODE_INFO(), SecurityContextHolder.getUserKey());
        if (nodeInfoRes != null) {
            PrometheusResVo prometheusResVo = nodeInfoRes.toJavaObject(PrometheusResVo.class);
            if (prometheusResVo != null && prometheusResVo.isSuccess()) {
                List<PrometheusResultVo> resultList = prometheusResVo.getData().getResult();
                return CommonTypeVo.resourceObjectToCommonTypeVoList(resultList);
            }
        }
        return Collections.emptyList();
    }

    @Override
    public List<K8SResourceUsage> getResourceUsageList(String searchResourceObject, Date startTime, Date endTime) {
        // 默认步长为六小时
        Long step = 60 * 60 * 6L;
        Date[] startAndEndDates = DateTimeNormalizer.normalize(startTime, endTime);
        List<K8SResourceUsage> resourceUsageList = new ArrayList<>();
        JSONObject nodeInfoRes = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.NODE_INFO(), SecurityContextHolder.getUserKey());
        if (nodeInfoRes != null) {
            PrometheusResVo prometheusResVo = nodeInfoRes.toJavaObject(PrometheusResVo.class);
            if (prometheusResVo != null && prometheusResVo.isSuccess()) {
                List<PrometheusResultVo> resultList = prometheusResVo.getData().getResult();
                List<JSONObject> metricList = resultList.stream().map(PrometheusResultVo::getMetric).filter(metric -> {
                    if (StringUtils.isEmpty(searchResourceObject)) {
                        return true;
                    } else if (StringUtils.isNotEmpty(searchResourceObject)) {
                        return searchResourceObject.equals(metric.getString("ip"));
                    } else {
                        return false;
                    }

                }).collect(Collectors.toList());
                resourceUsageList = monCommonAsyncService.getResourceUsageList(metricList, startAndEndDates, step);
            }
        }
        resourceUsageList.sort(Comparator.comparing(K8SResourceUsage::getOccurredTime).reversed());
        return resourceUsageList;
    }

    /**
     * 根据传入的环境变量列表，生成并更新容器对象的 env 与 envFrom 字段。
     *
     * <p>逻辑说明：</p>
     * <ul>
     *   <li>遍历 {@code k8sApplicationEnvList}，按 {@link ApplicationEnvType} 区分 7 种变量来源。</li>
     *   <li>将每种来源转换成符合 Kubernetes 规范的 JSON 结构，分别归入：
     *     <ul>
     *       <li>{@code env}     数组：KEY_VALUE_PAIR、RESOURCE、CONFIG_MAP_KEY、SECRET_KEY、POD_FIELD</li>
     *       <li>{@code envFrom} 数组：SECRET、CONFIGMAP</li>
     *     </ul>
     *   </li>
     *   <li>给 RESOURCE、CONFIG_MAP_KEY、SECRET_KEY、SECRET、CONFIGMAP 统一补全必需字段（divisor / optional 等）。</li>
     *   <li>最后将生成的 {@code env} 与 {@code envFrom} 数组写回 {@code containerJson} 并返回。</li>
     * </ul>
     *
     * @param k8sApplicationEnvList 待写入的环境变量列表
     * @param containerJson         待更新的容器 JSON 对象（K8s container spec）
     * @return 已更新 env & envFrom 的容器 JSON 对象（即入参 containerJson）
     */
    private JSONObject updateApplicationContainerEnv(List<K8sApplicationEnv> k8sApplicationEnvList, JSONObject
            containerJson) {
        JSONArray envJsonArray = new JSONArray();
        JSONArray envFromJsonArray = new JSONArray();
        for (K8sApplicationEnv k8sApplicationEnv : k8sApplicationEnvList) {
            ApplicationEnvType applicationEnvType = ApplicationEnvType.getApplicationEnvTypeByKey(k8sApplicationEnv.getType());
            switch (applicationEnvType) {
                case KEY_VALUE_PAIR: {
                    JSONObject envJson = new JSONObject();
                    envJson.put("name", k8sApplicationEnv.getKey());
                    if (k8sApplicationEnv.getValueObj() != null && k8sApplicationEnv.getValueObj().containsKey("value")) {
                        envJson.put("value", k8sApplicationEnv.getValueObj().getString("value"));
                        envJsonArray.add(envJson);
                    }
                    break;
                }
                case RESOURCE: {
                    JSONObject envJson = new JSONObject();
                    envJson.put("name", k8sApplicationEnv.getKey());
                    JSONObject valueFromJson = new JSONObject();
                    JSONObject resourceFieldRef = new JSONObject();
                    JSONObject valueObj = k8sApplicationEnv.getValueObj();
                    resourceFieldRef.put("divisor", "1");
                    resourceFieldRef.put("containerName", valueObj.getString("name"));
                    resourceFieldRef.put("resource", valueObj.getString("key"));
                    valueFromJson.put("resourceFieldRef", resourceFieldRef);
                    envJson.put("valueFrom", valueFromJson);
                    envJsonArray.add(envJson);
                    break;
                }
                case CONFIG_MAP_KEY: {
                    JSONObject envJson = new JSONObject();
                    envJson.put("name", k8sApplicationEnv.getKey());
                    JSONObject valueFromJson = new JSONObject();
                    JSONObject configMapKeyRef = new JSONObject();
                    JSONObject valueObj = k8sApplicationEnv.getValueObj();
                    configMapKeyRef.put("optional", false);
                    configMapKeyRef.put("name", valueObj.getString("name"));
                    configMapKeyRef.put("key", valueObj.getString("key"));
                    valueFromJson.put("configMapKeyRef", configMapKeyRef);
                    envJson.put("valueFrom", valueFromJson);
                    envJsonArray.add(envJson);
                    break;
                }
                case SECRET_KEY: {
                    JSONObject envJson = new JSONObject();
                    envJson.put("name", k8sApplicationEnv.getKey());
                    JSONObject valueFromJson = new JSONObject();
                    JSONObject secretKeyRef = new JSONObject();
                    JSONObject valueObj = k8sApplicationEnv.getValueObj();
                    secretKeyRef.put("optional", false);
                    secretKeyRef.put("name", valueObj.getString("name"));
                    secretKeyRef.put("key", valueObj.getString("key"));
                    valueFromJson.put("secretKeyRef", secretKeyRef);
                    envJson.put("valueFrom", valueFromJson);
                    envJsonArray.add(envJson);
                    break;
                }
                case POD_FIELD: {
                    JSONObject envJson = new JSONObject();
                    envJson.put("name", k8sApplicationEnv.getKey());
                    JSONObject valueFromJson = new JSONObject();
                    JSONObject fieldRef = new JSONObject();
                    JSONObject valueObj = k8sApplicationEnv.getValueObj();
                    fieldRef.put("apiVersion", "v1");
                    fieldRef.put("fieldPath", valueObj.getString("value"));
                    valueFromJson.put("fieldRef", fieldRef);
                    envJson.put("valueFrom", valueFromJson);
                    envJsonArray.add(envJson);
                    break;
                }
                case SECRET: {
                    JSONObject envJson = new JSONObject();
                    envJson.put("prefix", k8sApplicationEnv.getKey());
                    JSONObject secretRef = new JSONObject();
                    JSONObject valueObj = k8sApplicationEnv.getValueObj();
                    secretRef.put("optional", false);
                    secretRef.put("name", valueObj.getString("name"));
                    envJson.put("secretRef", secretRef);
                    envFromJsonArray.add(envJson);
                    break;
                }
                case CONFIGMAP: {
                    JSONObject envJson = new JSONObject();
                    envJson.put("prefix", k8sApplicationEnv.getKey());
                    JSONObject configMapRef = new JSONObject();
                    JSONObject valueObj = k8sApplicationEnv.getValueObj();
                    configMapRef.put("optional", false);
                    configMapRef.put("name", valueObj.getString("name"));
                    envJson.put("configMapRef", configMapRef);
                    envFromJsonArray.add(envJson);
                    break;
                }
            }
        }
        containerJson.put("env", envJsonArray);
        containerJson.put("envFrom", envFromJsonArray);
        return containerJson;
    }

    private JSONObject getNacosGatewayConfigJson() {
        String nacosGatewayConfigYaml = remoteGatewayService.getNacosConfigDetail(nacosGatewayConfigId, nacosDefaultGroup, SecurityContextHolder.getUserKey());
        Yaml yaml = new Yaml();
        LinkedHashMap<String, Object> yamlMap = yaml.load(nacosGatewayConfigYaml);
        return new JSONObject(yamlMap);
    }

    private Boolean updateNacosGatewayConfig(JSONObject gatewayConfigJson) {
        String jsonString = gatewayConfigJson.toJSONString();
        JsonNode jsonNode;
        try {
            jsonNode = new ObjectMapper().readTree(jsonString);
            String string = new YAMLMapper().writeValueAsString(jsonNode);
            //因为writeValueAsString生成的yaml字符串会带有 ---\n 所以进行替换操作
            String yamlStr = string.replaceAll("---\n", "");

            Map<String, String> nacosMap = new HashMap<>();
            nacosMap.put("dataId", nacosGatewayConfigId);
            nacosMap.put("group", nacosDefaultGroup);
            nacosMap.put("content", yamlStr);
            nacosMap.put("type", "yaml");
            nacosMap.put("modifyTime", String.valueOf(DateUtils.getNowDate().getTime()));
            try (Response response = remoteGatewayService.updateNacosConfig(nacosMap, SecurityContextHolder.getUserKey())) {
                return FeignUtils.isSuccess(response);
            }
        } catch (JsonProcessingException e) {
            throw new ServiceException("更新网关配置文件失败：网关配置内容格式异常");
        }
    }

}
