package c_nacos

import (
	"cicv-data-closedloop/common/config/c_log"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"os"
)

var Config string

func InitConfig(private bool, dataId string, group string) {
	nacosIp := nacosPublicIp
	if private {
		nacosIp = nacosPrivateIp
	}

	serverConfig := []constant.ServerConfig{*constant.NewServerConfig(nacosIp, uint64(nacosPort), constant.WithContextPath("/nacos"))}
	clientConfig := constant.NewClientConfig(
		constant.WithNamespaceId(namespaceId),
		constant.WithNotLoadCacheAtStart(true),
		constant.WithUsername(username),
		constant.WithPassword(password),
	)

	// ------- 配置刷新 -------
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ServerConfigs: serverConfig,
			ClientConfig:  clientConfig,
		},
	)
	if err != nil {
		c_log.GlobalLogger.Error("程序崩溃，nacos 连接失败：", err)
		os.Exit(-1)
	}
	if err = configClient.ListenConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group,
		OnChange: func(namespace, group, dataId, data string) {
			Config = data // 更新配置
		},
	}); err != nil {
		c_log.GlobalLogger.Error("程序崩溃，配置监听连接失败：", err)
		os.Exit(-1)
	}
}
