package c_nacos

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

var (
	nacosPrivateIp = "10.14.85.228"
	nacosPublicIp  = "36.110.106.142"
	nacosPort      = 8848
	namespaceId    = "45e828a5-1a1d-4c46-a746-d4dfa3ca8f5f"
	username       = "cicv"
	password       = "cicv"
	serviceIp      = "36.110.106.142"
)

func InitService(private bool, serviceName string, servicePort uint64, metadata map[string]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),
	)

	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  clientConfig,
			ServerConfigs: serverConfig,
		},
	)
	if err != nil {
		c_log.GlobalLogger.Error("程序崩溃，nacos 连接失败：", err)
		os.Exit(-1)
	}
	if err = registerServiceInstance(namingClient, vo.RegisterInstanceParam{
		Ip:          serviceIp,
		Port:        servicePort,
		ServiceName: serviceName,
		//GroupName:   "group-a",
		//ClusterName: "cluster-a",
		Weight:    10,
		Enable:    true,
		Healthy:   true,
		Ephemeral: true,
		Metadata:  metadata,
	}); err != nil {
		c_log.GlobalLogger.Error("程序崩溃，服务注册连接失败：", err)
		os.Exit(-1)
	}

}

// registerServiceInstance 服务注册
func registerServiceInstance(client naming_client.INamingClient, param vo.RegisterInstanceParam) error {
	success, err := client.RegisterInstance(param)
	if err != nil {
		return err
	}
	if !success {
		return errors.New("注册失败")
	}
	return nil
}
