package models

import (
	"errors"
	"github.com/astaxie/beego/logs"
	"k8s-console/utils"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"strconv"
)

type ServiceInfo struct {
	ServiceName  string   `json:"serviceName"`
	ServicePorts []string `json:"servicePorts"`
}

func GetServiceConfigInfo(ns string) ([]ServiceInfo, error) {
	var beans []ServiceInfo
	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		return nil, errors.New(utils.GetI18nLang("zh", "createK8sConFail"))
	}
	serviceList, err := k8sClient.CoreV1().Services(ns).List(v1.ListOptions{})
	if err != nil {
		logs.Error("查询service失败：", err.Error())
		return nil, err
	}
	services := serviceList.Items
	if services != nil && len(services) > 0 {
		for _, v := range services {
			if v.Spec.Type == "ClusterIP" {
				bean := ServiceInfo{}
				var ports []string
				bean.ServiceName = v.Name
				for _, p := range v.Spec.Ports {
					servicePort := ""
					if p.Name != "" {
						servicePort = p.Name
						if p.Port != 0 {
							servicePort = servicePort + "(" + strconv.Itoa(int(p.Port)) + ")"
						}
					} else {
						servicePort = strconv.Itoa(int(p.Port))
					}
					ports = append(ports, servicePort)
					//if p.Name != "" {
					//	ports = append(ports, p.Name)
					//} else {
					//	ports = append(ports, strconv.Itoa(int(p.Port)))
					//}
				}
				bean.ServicePorts = ports
				beans = append(beans, bean)
			}
		}
	}
	return beans, nil
}
