package services

import (
	"encoding/json"
	"errors"
	"github.com/astaxie/beego"
	"k8s-console/dto"
	"k8s-console/dto/services"
	"k8s-console/utils"
	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/client-go/kubernetes/scheme"
	"regexp"
	"sigs.k8s.io/yaml"
	"strconv"
	"strings"
)

var (
	infoLogger  = utils.InfoLogger
	errorLogger = utils.ErrorLogger
)

// ServiceController operations for Service
type ServiceController struct {
	beego.Controller
}

// URLMapping ...
func (c *ServiceController) URLMapping() {
	c.Mapping("getServicesList", c.GetServicesList)
	c.Mapping("deleteService", c.DeleteService)
	c.Mapping("getServiceInfo", c.GetServiceInfo)
	c.Mapping("getServicePortList", c.GetServicePortList)
	c.Mapping("getServiceEndPointList", c.GetServiceEndPointList)
	c.Mapping("getServiceOriginalInfo", c.GetServiceOriginalInfo)
	c.Mapping("checkServiceContent", c.CheckServiceContent)
	c.Mapping("saveServiceResource", c.SaveServiceResource)
	c.Mapping("getServiceRelatedResourceInfo", c.GetServiceRelatedResourceInfo)
	c.Mapping("getControllerPortList", c.GetControllerPortList)
	c.Mapping("saveGuiServiceResource", c.SaveGuiServiceResource)
}

// Post ...
// @Title GetServicesList
// @Description get ServicesList
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.GetServicesListRequestDto	true	""
// @Success 200
// @Failure 300 {object} dto.BaseResponseDto
// @router /getServicesList [post]
func (c *ServiceController) GetServicesList() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.GetServicesListRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.GetPageListBaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("查询所有服务请求参数: ", requestDto)

	pageIndex := requestDto.PageIndex
	pageSize := requestDto.PageSize
	if pageIndex < 0 {
		errorLogger.Println("页码必须大于等于0")
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexRange")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if pageSize <= 0 {
		errorLogger.Println("页大小必须大于0")
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageSizeRange")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	nameSpace := requestDto.NameSpace
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		errorResponseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	//查询命名空间下所有service信息
	serviceList, err := k8sClient.CoreV1().Services(nameSpace).List(metav1.ListOptions{})
	if err != nil {
		errorLogger.Printf("查询集群%s空间所有service失败: %s", nameSpace, err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getServicesList_getTheNameSpaceServicesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	itemList := serviceList.Items
	totalRecords := len(itemList)
	infoLogger.Println("totalRecords:", totalRecords)
	totalPages := 0
	if totalRecords > 0 {
		if totalRecords <= pageIndex*pageSize {
			errorLogger.Println("页码超出最大页范围")
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			c.Data["json"] = errorResponseDto
			c.ServeJSON()
			return
		}
		totalPages = totalRecords/pageSize + 1
		if totalRecords%pageSize == 0 {
			totalPages = totalRecords / pageSize
		}
	} else {
		if totalRecords < pageIndex*pageSize {
			errorLogger.Println("页码超出最大页范围")
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			c.Data["json"] = errorResponseDto
			c.ServeJSON()
			return
		}
	}

	//默认截取到最后
	resultList := itemList[pageIndex*pageSize:]
	//最后部分大于页大小则截取最后部分的开头部分
	if totalRecords-pageIndex*pageSize >= pageSize {
		resultList = itemList[pageIndex*pageSize : (pageIndex+1)*pageSize]
	}
	result := []services.GetServicesListResultDataResponseDto{}
	for i, item := range resultList {
		infoLogger.Printf("-----------第%d个service---------------", i+1)
		infoLogger.Println("name:", item.Name)
		serviceType := item.Spec.Type
		infoLogger.Println("type:", serviceType)
		infoLogger.Println(item.Spec.ClusterIP)
		externalIPs := item.Spec.ExternalIPs
		infoLogger.Println("externalIPs:", externalIPs)
		if len(externalIPs) == 0 {
			externalIPs = []string{"<none>"}
		}
		creationTimestamp := utils.GetDurationToString(lang, item.CreationTimestamp.Time, true)
		infoLogger.Println("creationTimestamp:", item.CreationTimestamp.Time, " ", creationTimestamp)
		portsList := item.Spec.Ports
		infoLogger.Println("ports:", portsList)
		servicePort := []string{}
		targetPort := []string{}
		for _, port := range portsList {
			infoLogger.Println("name:", port.Name)
			infoLogger.Println("nodePort:", port.NodePort)
			infoLogger.Println("port:", port.Port)
			infoLogger.Println("protocol:", port.Protocol)
			infoLogger.Println("targetPort:", port.TargetPort)
			servicePort = append(servicePort, strconv.Itoa(int(port.Port))+"/"+string(port.Protocol))
			//switch serviceType {
			//case "ClusterIP":
			//	if port.TargetPort.IntVal != 0 {
			//		targetPort = append(targetPort, strconv.Itoa(int(port.TargetPort.IntVal))+"/"+string(port.Protocol))
			//	} else {
			//		targetPort = append(targetPort, port.TargetPort.StrVal+"/"+string(port.Protocol))
			//	}
			//case "NodePort":
			//	targetPort = append(targetPort, strconv.Itoa(int(port.NodePort))+"/"+string(port.Protocol))
			//}

			if port.TargetPort.IntVal != 0 {
				targetPort = append(targetPort, strconv.Itoa(int(port.TargetPort.IntVal))+"/"+string(port.Protocol))
			} else {
				targetPort = append(targetPort, port.TargetPort.StrVal+"/"+string(port.Protocol))
			}

		}

		o := services.GetServicesListResultDataResponseDto{
			item.Name,
			string(serviceType),
			item.Spec.ClusterIP,
			externalIPs,
			servicePort,
			targetPort,
			creationTimestamp,
		}
		result = append(result, o)
	}

	successResponseDto.Result = result
	successResponseDto.PageInfo = dto.PageInfoBaseResponseDto{
		TotalRecords: totalRecords,
		TotalPages:   totalPages,
	}
	c.Data["json"] = successResponseDto
	c.ServeJSON()
}

// Post ...
// @Title DeleteService
// @Description delete service
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.DeleteServiceRequestDto	true	""
// @Success 200 {object} dto.BaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /deleteService [post]
func (c *ServiceController) DeleteService() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.DeleteServiceRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("删除服务请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	serviceName := requestDto.ServiceName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(serviceName) == "" {
		errorLogger.Println("服务名称不能为空")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		responseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		responseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}

	//删除service
	if err := k8sClient.CoreV1().Services(nameSpace).Delete(serviceName, &metav1.DeleteOptions{}); err != nil {
		errStr := err.Error()
		errorLogger.Printf("删除集群%s空间%s service失败: %s", nameSpace, serviceName, err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "removeService_removeServiceFail")
		if strings.Contains(errStr, "not found") {
			responseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
		}
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Printf("删除集群%s空间%s service成功", nameSpace, serviceName)

	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	c.Data["json"] = responseDto
	c.ServeJSON()

}

// Post ...
// @Title GetServiceInfo
// @Description get serviceInfo
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.GetServiceInfoRequestDto	true	""
// @Success 200 {object} dto.BaseResultResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getServiceInfo [post]
func (c *ServiceController) GetServiceInfo() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.GetServiceInfoRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("获取服务详情请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	serviceName := requestDto.ServiceName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(serviceName) == "" {
		errorLogger.Println("服务名称不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		errorResponseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	//查询service详情
	serviceInfo, err := k8sClient.CoreV1().Services(nameSpace).Get(serviceName, metav1.GetOptions{})
	if err != nil {
		errStr := err.Error()
		errorLogger.Printf("查询集群%s空间%s service详情失败: %s", nameSpace, serviceName, errStr)
		errorResponseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
		if strings.Contains(errStr, "not found") {
			errorResponseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
		}
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("name:", serviceInfo.Name)
	infoLogger.Println("namespace:", serviceInfo.Namespace)
	infoLogger.Println("clusterIP:", serviceInfo.Spec.ClusterIP)
	infoLogger.Println("sessionAffinity:", serviceInfo.Spec.SessionAffinity)

	serviceLabels := serviceInfo.Labels
	serviceAnnotations := serviceInfo.Annotations
	serviceSelector := serviceInfo.Spec.Selector
	serviceType := serviceInfo.Spec.Type
	externalIPs := serviceInfo.Spec.ExternalIPs
	creationTimestamp := serviceInfo.ObjectMeta.CreationTimestamp

	infoLogger.Println("labels:", serviceLabels)
	infoLogger.Println("annotations:", serviceAnnotations)
	infoLogger.Println("Selector:", serviceSelector)
	infoLogger.Println("type:", serviceType)
	infoLogger.Println("externalIPs:", externalIPs)

	createTime := utils.ParseK8sDateTime(creationTimestamp, true)
	infoLogger.Println("creationTimestamp:", creationTimestamp, " ", createTime)

	if len(serviceLabels) == 0 {
		serviceLabels = map[string]string{}
	}
	annotations := []string{}
	for k, v := range serviceAnnotations {
		annotations = append(annotations, k+":"+v)
	}
	if len(annotations) == 0 {
		annotations = []string{"<none>"}
	}
	if len(serviceSelector) == 0 {
		serviceSelector = map[string]string{}
	}
	if len(externalIPs) == 0 {
		externalIPs = []string{"<none>"}
	}

	o := services.GetServiceInfoResultDataResponseDto{
		serviceInfo.Name,
		serviceInfo.Namespace,
		serviceLabels,
		annotations,
		serviceSelector,
		string(serviceType),
		serviceInfo.Spec.ClusterIP,
		string(serviceInfo.Spec.SessionAffinity),
		externalIPs,
		createTime,
	}
	successResponseDto.Result = o
	c.Data["json"] = successResponseDto
	c.ServeJSON()
}

// Post ...
// @Title GetServicePortList
// @Description get servicePortList
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.GetServicePortListRequestDto	true	""
// @Success 200 {object} dto.GetPageListBaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getServicePortList [post]
func (c *ServiceController) GetServicePortList() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.GetServicePortListRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.GetPageListBaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("获取服务端口列表请求参数: ", requestDto)

	pageIndex := requestDto.PageIndex
	pageSize := requestDto.PageSize
	if pageIndex < 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexRange")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if pageSize <= 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageSizeRange")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	nameSpace := requestDto.NameSpace
	serviceName := requestDto.ServiceName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(serviceName) == "" {
		errorLogger.Println("服务名称不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		errorResponseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	//查询service详情
	serviceInfo, err := k8sClient.CoreV1().Services(nameSpace).Get(serviceName, metav1.GetOptions{})
	if err != nil {
		errStr := err.Error()
		errorLogger.Printf("查询集群%s空间%s service详情失败: %s", nameSpace, serviceName, errStr)
		errorResponseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
		if strings.Contains(errStr, "not found") {
			errorResponseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
		}
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	serviceType := serviceInfo.Spec.Type
	infoLogger.Println("type:", serviceType)

	portsList := serviceInfo.Spec.Ports
	totalRecords := len(portsList)
	infoLogger.Println("totalRecords:", totalRecords)
	totalPages := 0
	if totalRecords > 0 {
		if totalRecords <= pageIndex*pageSize {
			errorLogger.Println("页码超出最大页范围")
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			c.Data["json"] = errorResponseDto
			c.ServeJSON()
			return
		}
		totalPages = totalRecords/pageSize + 1
		if totalRecords%pageSize == 0 {
			totalPages = totalRecords / pageSize
		}
	} else {
		if totalRecords < pageIndex*pageSize {
			errorLogger.Println("页码超出最大页范围")
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			c.Data["json"] = errorResponseDto
			c.ServeJSON()
			return
		}
	}

	//默认截取到最后
	resultList := portsList[pageIndex*pageSize:]
	//最后部分大于页大小则截取最后部分的开头部分
	if totalRecords-pageIndex*pageSize >= pageSize {
		resultList = portsList[pageIndex*pageSize : (pageIndex+1)*pageSize]
	}
	result := []services.GetServicePortListResultDataResponseDto{}
	for i, port := range resultList {
		infoLogger.Printf("-----------第%d个端口----------------", i+1)
		targetPort := ""
		// 暴露端口 只有nodePort类型的时候才有值
		nodePort := ""
		infoLogger.Println("name:", port.Name)
		infoLogger.Println("nodePort:", port.NodePort)
		infoLogger.Println("port:", port.Port)
		infoLogger.Println("protocol:", port.Protocol)
		infoLogger.Println("targetPort:", port.TargetPort)
		if port.NodePort > 0 {
			nodePort = strconv.Itoa(int(port.Port))
		}

		//switch serviceType {
		//case "ClusterIP":
		//	if port.TargetPort.IntVal != 0 {
		//		targetPort = strconv.Itoa(int(port.TargetPort.IntVal))
		//	} else {
		//		targetPort = port.TargetPort.StrVal
		//	}
		//case "NodePort":
		//	targetPort = port.TargetPort.StrVal
		//}

		if port.TargetPort.IntVal != 0 {
			targetPort = strconv.Itoa(int(port.TargetPort.IntVal))
		} else {
			targetPort = port.TargetPort.StrVal
		}

		s := services.GetServicePortListResultDataResponseDto{
			port.Name,
			port.Port,
			targetPort,
			nodePort,
			string(port.Protocol),
		}
		infoLogger.Println("GetServicePortListResultDataResponseDto:", s)
		result = append(result, s)
	}

	successResponseDto.Result = result
	successResponseDto.PageInfo = dto.PageInfoBaseResponseDto{
		TotalRecords: totalRecords,
		TotalPages:   totalPages,
	}
	c.Data["json"] = successResponseDto
	c.ServeJSON()
}

// Post ...
// @Title GetServiceEndPointList
// @Description get serviceEndPointList
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.GetServiceEndPointListRequestDto	true	""
// @Success 200 {object} dto.GetPageListBaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getServiceEndPointList [post]
func (c *ServiceController) GetServiceEndPointList() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.GetServiceEndPointListRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.GetPageListBaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("获取服务端点列表请求参数: ", requestDto)

	pageIndex := requestDto.PageIndex
	pageSize := requestDto.PageSize
	if pageIndex < 0 {
		errorLogger.Println("页码必须大于等于0")
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexRange")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if pageSize <= 0 {
		errorLogger.Println("页大小必须大于0")
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageSizeRange")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	nameSpace := requestDto.NameSpace
	serviceName := requestDto.ServiceName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(serviceName) == "" {
		errorLogger.Println("服务名称不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		errorResponseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	//查询service详情
	endPointInfo, err := k8sClient.CoreV1().Endpoints(nameSpace).Get(serviceName, metav1.GetOptions{})
	if err != nil {
		errorLogger.Printf("查询集群%s空间%s endPoint详情失败: %s", nameSpace, serviceName, err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheEndPointInfoFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	creationTimestamp := utils.GetDurationToString(lang, endPointInfo.CreationTimestamp.Time, true)
	infoLogger.Println("creationTimestamp:", endPointInfo.CreationTimestamp, " ", creationTimestamp)

	addresses := []v1.EndpointAddress{}
	if len(endPointInfo.Subsets) > 0 {
		addresses = endPointInfo.Subsets[0].Addresses
	}
	infoLogger.Println("EndpointAddress:", addresses)
	portList := []v1.EndpointPort{}
	if len(endPointInfo.Subsets) > 0 {
		portList = endPointInfo.Subsets[0].Ports
	}
	infoLogger.Println("EndpointPort:", portList)

	totalRecords := len(portList)
	infoLogger.Println("totalRecords:", totalRecords)
	totalPages := 0
	if totalRecords > 0 {
		if totalRecords <= pageIndex*pageSize {
			errorLogger.Println("页码超出最大页范围")
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			c.Data["json"] = errorResponseDto
			c.ServeJSON()
			return
		}
		totalPages = totalRecords/pageSize + 1
		if totalRecords%pageSize == 0 {
			totalPages = totalRecords / pageSize
		}
	} else {
		if totalRecords < pageIndex*pageSize {
			errorLogger.Println("页码超出最大页范围")
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			c.Data["json"] = errorResponseDto
			c.ServeJSON()
			return
		}
	}

	//默认截取到最后
	resultList := portList[pageIndex*pageSize:]
	//最后部分大于页大小则截取最后部分的开头部分
	if totalRecords-pageIndex*pageSize >= pageSize {
		resultList = portList[pageIndex*pageSize : (pageIndex+1)*pageSize]
	}
	result := []services.GetServiceEndPointListResultDataResponseDto{}
	for i, p := range resultList {
		infoLogger.Printf("-----------第%d个端点端口----------------", i+1)
		infoLogger.Println("name:", p.Name)
		infoLogger.Println("port", p.Port)
		infoLogger.Println("protocol", p.Protocol)
		endPointList := []string{}
		for _, a := range addresses {
			infoLogger.Println("ip:", a.IP)
			endPointList = append(endPointList, a.IP+":"+utils.Int32ToString(p.Port))
		}
		if len(endPointList) == 0 {
			endPointList = []string{"<none>"}
		}
		infoLogger.Println("endPointList:", endPointList)
		s := services.GetServiceEndPointListResultDataResponseDto{
			p.Name,
			endPointList,
			creationTimestamp,
			string(p.Protocol),
		}
		infoLogger.Println("GetServiceEndPointListResultDataResponseDto:", s)
		result = append(result, s)
	}

	successResponseDto.Result = result
	successResponseDto.PageInfo = dto.PageInfoBaseResponseDto{
		TotalRecords: totalRecords,
		TotalPages:   totalPages,
	}
	c.Data["json"] = successResponseDto
	c.ServeJSON()
}

// Post ...
// @Title GetServiceOriginalInfo
// @Description get serviceOriginalInfo
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.GetServiceInfoRequestDto	true	""
// @Success 200 {object} dto.BaseResultResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getServiceOriginalInfo [post]
func (c *ServiceController) GetServiceOriginalInfo() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.GetServiceInfoRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("获取服务原始数据详情请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	serviceName := requestDto.ServiceName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(serviceName) == "" {
		errorLogger.Println("服务名称不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		errorResponseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	//查询service详情
	serviceInfo, err := k8sClient.CoreV1().Services(nameSpace).Get(serviceName, metav1.GetOptions{})
	if err != nil {
		errStr := err.Error()
		errorLogger.Printf("查询集群%s空间%s service详情失败: %s", nameSpace, serviceName, errStr)
		errorResponseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
		if strings.Contains(errStr, "not found") {
			errorResponseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
		}
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	serviceInfo.APIVersion = "v1"
	serviceInfo.Kind = "Service"
	//var serviceMap map[string]interface{}
	//if serviceByte, err := json.Marshal(serviceInfo); err != nil {
	//	errorLogger.Printf("转换byte失败: %s", err.Error())
	//} else {
	//	if err := json.Unmarshal(serviceByte, &serviceMap); err != nil {
	//		errorLogger.Printf("转换map失败: %s", err.Error())
	//	}
	//}

	//if serviceMap != nil {
	//	metadataMap := serviceMap["metadata"].(map[string]interface{})
	//	//specMap := serviceMap["spec"].(map[string]interface{})
	//	// 删除不需要展示的字段
	//	//delete(metadataMap, "selfLink")
	//	//delete(metadataMap, "uid")
	//	delete(metadataMap, "creationTimestamp")
	//	//delete(specMap, "clusterIP")
	//	successResponseDto.Result = serviceMap
	//}

	// 转换yaml格式
	yamlBytes, err := yaml.Marshal(serviceInfo)
	if err != nil {
		errorLogger.Printf("转换yaml失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("\n" + string(yamlBytes))

	successResponseDto.Result = string(yamlBytes)
	c.Data["json"] = successResponseDto
	c.ServeJSON()
}

// Post ...
// @Title CheckServiceContent
// @Description check serviceContent
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.CheckServiceContentRequestDto	true	""
// @Success 200 {object} dto.BaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /checkServiceContent [post]
func (c *ServiceController) CheckServiceContent() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.CheckServiceContentRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("校验服务内容请求参数: ", requestDto)

	serviceOptions := v1.Service{}
	// 复制字段
	utils.StructCopy(&serviceOptions, &requestDto)

	infoLogger.Println("执行校验服务内容")
	// 校验请求参数
	if err := checkServiceParams(lang, requestDto.NameSpace, requestDto.OperateType, requestDto.ServiceName,
		serviceOptions); err != nil {
		errorLogger.Printf("校验服务内容请求参数失败: %s", err.Error())
		responseDto.Message = err.Error()
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("校验保存服务内容成功")

	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	c.Data["json"] = responseDto
	c.ServeJSON()
}

// Post ...
// @Title SaveServiceResource
// @Description save serviceResource
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.SaveServiceResourceRequestDto	true	""
// @Success 200 {object} dto.BaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /saveServiceResource [post]
func (c *ServiceController) SaveServiceResource() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.SaveServiceResourceRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("保存服务请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	operateType := requestDto.OperateType
	oldServiceName := requestDto.ServiceName
	serviceOptions := v1.Service{}
	// 复制字段
	utils.StructCopy(&serviceOptions, &requestDto)

	infoLogger.Println("执行校验保存服务请求参数")
	// 校验请求参数
	if err := checkServiceParams(lang, nameSpace, operateType, oldServiceName, serviceOptions); err != nil {
		errorLogger.Printf("校验保存服务请求参数失败: %s", err.Error())
		responseDto.Message = err.Error()
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("校验保存服务请求参数成功")

	serviceName := serviceOptions.ObjectMeta.Name
	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		responseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}

	if operateType == "update" {
		//更新service
		if _, err := k8sClient.CoreV1().Services(nameSpace).Update(&serviceOptions); err != nil {
			errStr := err.Error()
			errorLogger.Printf("更新集群%s空间%s service失败: %s", nameSpace, serviceName, errStr)
			if strings.Contains(errStr, "not found") {
				responseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
			} else {
				responseDto.Message = utils.GetI18nLang(lang, "saveServiceResource_updateServiceFail")
				if m, _ := regexp.MatchString(".*([iI]nvalid).*", errStr); m {
					responseDto.Message = utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat")
				}
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
		}
		infoLogger.Printf("更新集群%s空间%s service成功", nameSpace, serviceName)
	} else if operateType == "create" {
		//查询service是否存在
		_, err := k8sClient.CoreV1().Services(nameSpace).Get(serviceName, metav1.GetOptions{})
		if err == nil {
			errorLogger.Printf("集群%s空间%s service已存在", nameSpace, serviceName)
			responseDto.Message = utils.GetI18nLang(lang, "saveServiceResource_serviceAlreadyExists")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		errStr := err.Error()
		if !strings.Contains(errStr, "not found") {
			errorLogger.Printf("查询集群%s空间%s service详情失败: %s", nameSpace, serviceName, errStr)
			responseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		infoLogger.Printf("查询集群%s空间%s service详情返回结果: %s", nameSpace, serviceName, errStr)

		//创建service
		if _, err = k8sClient.CoreV1().Services(nameSpace).Create(&serviceOptions); err != nil {
			errStr := err.Error()
			errorLogger.Printf("创建集群%s空间%s service失败: %s", nameSpace, serviceName, errStr)
			m, _ := regexp.MatchString(".*([iI]nvalid).*", errStr)
			switch {
			case strings.Contains(errStr, "resourceVersion should not be set on objects to be created"):
				responseDto.Message = utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat")
			case m:
				responseDto.Message = utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat")
			default:
				responseDto.Message = utils.GetI18nLang(lang, "saveServiceResource_createServiceFail")
			}
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		infoLogger.Printf("创建集群%s空间%s service成功", nameSpace, serviceName)
	}

	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	c.Data["json"] = responseDto
	c.ServeJSON()
}

// Post ...
// @Title GetServiceRelatedResourceInfo
// @Description get ServiceRelatedResourceInfo
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.GetServiceRelatedResourceInfoRequestDto	true	""
// @Success 200 {object} dto.BaseResultResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getServiceRelatedResourceInfo [post]
func (c *ServiceController) GetServiceRelatedResourceInfo() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.GetServiceRelatedResourceInfoRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("获取服务及关联deploy资源详情请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	serviceName := requestDto.ServiceName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(serviceName) == "" {
		errorLogger.Println("服务名称不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		errorResponseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	//查询service详情
	serviceInfo, err := k8sClient.CoreV1().Services(nameSpace).Get(serviceName, metav1.GetOptions{})
	if err != nil {
		errStr := err.Error()
		errorLogger.Printf("查询集群%s空间%s service详情失败: %s", nameSpace, serviceName, errStr)
		errorResponseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
		if strings.Contains(errStr, "not found") {
			errorResponseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
		}
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	// 返回
	result := services.GetServiceRelatedResourceInfoResultDataResponseDto{}
	result.NameSpace = nameSpace
	result.ServiceName = serviceName
	serviceType := serviceInfo.Spec.Type
	infoLogger.Println("type:", serviceType)
	clusterIP := serviceInfo.Spec.ClusterIP
	infoLogger.Println("clusterIP:", clusterIP)

	result.ServiceType = string(serviceType)
	if clusterIP == "None" {
		result.ServiceType = "Headless"
	}
	ports := serviceInfo.Spec.Ports
	portlist := []services.SaveGuiServiceResourceServicePortRequestDto{}
	for _, port := range ports {
		targetPort := port.TargetPort.String()
		p := services.SaveGuiServiceResourceServicePortRequestDto{
			port.Name,
			port.Port,
			targetPort,
			string(port.Protocol),
			port.NodePort,
			false,
		}
		portlist = append(portlist, p)
	}
	infoLogger.Println("port:", portlist)
	result.Ports = portlist

	selector := serviceInfo.Spec.Selector
	infoLogger.Println("selector:", selector)
	selectorList := []string{}
	for k, v := range selector {
		selectorList = append(selectorList, k+"="+v)
	}
	infoLogger.Println("selectorList:", selectorList)

	controllerNameList := []string{}
	// 如果没有selector 则不查询关联的deploy 或 StatefulSet
	if len(selectorList) > 0 {
		// 非Headless类型查询绑定的deploy
		if result.ServiceType != "Headless" {
			deployList, err := k8sClient.AppsV1().Deployments(nameSpace).List(metav1.ListOptions{})
			if err != nil {
				errorLogger.Printf("查询集群%s空间所有与service:%s关联的deploy失败: %s", nameSpace,
					serviceName, err.Error())
				errorResponseDto.Message = utils.GetI18nLang(lang,
					"getServiceRelatedResourceInfo_getServiceRelatedDeployFail")
				c.Data["json"] = errorResponseDto
				c.ServeJSON()
				return
			}
			for _, v := range deployList.Items {
				infoLogger.Println("deploy name:", v.Name)
				// 取pod的labels
				labels := v.Spec.Template.ObjectMeta.Labels
				infoLogger.Println("deploy pod labels:", labels)
				for k, l := range labels {
					// 只要有一个label相同 就能匹配到
					if utils.IsContains(selectorList, k+"="+l) {
						if !utils.IsContains(controllerNameList, v.Name) {
							controllerNameList = append(controllerNameList, v.Name)
						}
					}
				}
			}
			infoLogger.Printf("根据selector匹配的所有deploy:%v", controllerNameList)
		} else { // Headless类型查询绑定的StatefulSet
			stateFulSetList, err := k8sClient.AppsV1().StatefulSets(nameSpace).List(metav1.ListOptions{})
			if err != nil {
				errorLogger.Printf("查询集群%s空间所有与service:%s关联的StatefulSet失败: %s", nameSpace,
					serviceName, err.Error())
				errorResponseDto.Message = utils.GetI18nLang(lang,
					"getServiceRelatedResourceInfo_getServiceRelatedStatefulSetFail")
				c.Data["json"] = errorResponseDto
				c.ServeJSON()
				return
			}
			for _, v := range stateFulSetList.Items {
				infoLogger.Println("StatefulSet name:", v.Name)
				// 取StatefulSet 的ServiceName字段
				stateFulSetServiceName := v.Spec.ServiceName
				infoLogger.Println("StatefulSet ServiceName:", stateFulSetServiceName)
				if stateFulSetServiceName == serviceName {
					controllerNameList = append(controllerNameList, v.Name)
				}
			}
			infoLogger.Printf("根据ServiceName查找匹配的所有StatefulSet:%v", controllerNameList)
		}
	}
	result.ControllerNameList = controllerNameList

	successResponseDto.Result = result
	c.Data["json"] = successResponseDto
	c.ServeJSON()
}

// Post ...
// @Title GetControllerPortList
// @Description get ControllerPortList
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.GetControllerPortListRequestDto	true	""
// @Success 200 {object} dto.BaseResultResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getControllerPortList [post]
func (c *ServiceController) GetControllerPortList() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto services.GetControllerPortListRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("获取控制器所有端口请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	controllerTypeName := requestDto.ControllerTypeName
	controllerNameList := requestDto.ControllerNameList
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(controllerTypeName) == "" || !utils.IsContains([]string{"deploy", "sts"}, controllerTypeName) {
		errorLogger.Println("控制器名称必须为deploy或sts")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(controllerNameList) == 0 {
		errorLogger.Println("控制器名称不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println(allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		errorResponseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}

	controllerPorts := []string{}
	for _, v := range controllerNameList {
		if controllerTypeName == "deploy" {
			infoLogger.Println("deploy name:", v)
			//查询deployment详情
			deployInfo, err := k8sClient.AppsV1().Deployments(nameSpace).Get(v, metav1.GetOptions{})
			if err != nil {
				errorLogger.Printf("查询集群%s空间%s的deployment详情失败: %s", nameSpace, v, err.Error())
				errorResponseDto.Message = utils.GetI18nLang(lang, "getDeploymentInfo_getTheDeploymentInfoFail")
				c.Data["json"] = errorResponseDto
				c.ServeJSON()
				return
			}
			containers := deployInfo.Spec.Template.Spec.Containers
			for _, c := range containers {
				for _, p := range c.Ports {
					infoLogger.Printf("端口名称:%s", p.Name)
					infoLogger.Printf("端口号:%d", p.ContainerPort)
					if strings.TrimSpace(p.Name) != "" {
						controllerPorts = append(controllerPorts, p.Name)
					}
					if p.ContainerPort > 0 {
						controllerPorts = append(controllerPorts, utils.Int32ToString(p.ContainerPort))
					}
				}
			}
		} else if controllerTypeName == "sts" {
			infoLogger.Println("StatefulSet name:", v)
			//查询StatefulSet详情
			statefulSetInfo, err := k8sClient.AppsV1().StatefulSets(nameSpace).Get(v, metav1.GetOptions{})
			if err != nil {
				errorLogger.Printf("查询集群%s空间%s的StatefulSet详情失败: %s", nameSpace, v, err.Error())
				errorResponseDto.Message = utils.GetI18nLang(lang, "getControllerPortList_getStatefulSetInfoFail")
				c.Data["json"] = errorResponseDto
				c.ServeJSON()
				return
			}
			containers := statefulSetInfo.Spec.Template.Spec.Containers
			for _, c := range containers {
				for _, p := range c.Ports {
					infoLogger.Printf("端口名称:%s", p.Name)
					infoLogger.Printf("端口号:%d", p.ContainerPort)
					if strings.TrimSpace(p.Name) != "" {
						controllerPorts = append(controllerPorts, p.Name)
					}
					if p.ContainerPort > 0 {
						controllerPorts = append(controllerPorts, utils.Int32ToString(p.ContainerPort))
					}
				}
			}
		}
	}
	infoLogger.Printf("去重前: %v", controllerPorts)
	//去重
	result := utils.RemoveSliceDuplicate(controllerPorts)
	infoLogger.Printf("去重后: %v", result)

	successResponseDto.Result = result
	c.Data["json"] = successResponseDto
	c.ServeJSON()
}

// Post ...
// @Title SaveGuiServiceResource
// @Description save GuiServiceResource
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	services.SaveGuiServiceResourceRequestDto	true	""
// @Success 200 {object} dto.BaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /saveGuiServiceResource [post]
func (c *ServiceController) SaveGuiServiceResource() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	body := c.Ctx.Input.RequestBody
	infoLogger.Println("通过图形界面保存服务请求参数: \n", string(body))
	var requestDto services.SaveGuiServiceResourceRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(body, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("通过图形界面保存服务请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	operateType := requestDto.OperateType
	serviceName := requestDto.ServiceName
	serviceType := requestDto.ServiceType
	controllerNameList := requestDto.ControllerNameList
	ports := requestDto.Ports

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		responseDto.Message = utils.GetI18nLang(lang, "createK8sConFail")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}

	if !utils.IsContains([]string{"update", "create"}, operateType) {
		errorLogger.Println("operateType 只能为update或create")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	if operateType == "create" {
		// 排除部分命名空间
		if !utils.IsContains([]string{"default", "kube-system", "harbor", "monitor",
			beego.AppConfig.String("nameSpace")}, nameSpace) {

			resourceLimitData, err := utils.GetResourceQuotaResourceLimitData(nameSpace, lang)
			if err != nil && !strings.Contains(err.Error(), "not found") {
				errorLogger.Println("获取ResourceQuota定义的资源限制数据失败")
				responseDto.Message = utils.GetI18nLang(lang, "getResourceQuotaResourceLimitDataFail_queryResourceQuotaFail")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
			//查询service是否存在
			serviceList, err := k8sClient.CoreV1().Services(nameSpace).List(metav1.ListOptions{})
			if err != nil {
				errorLogger.Printf("查询%s空间所有服务失败:%s", nameSpace, err.Error())
				responseDto.Message = utils.GetI18nLang(lang, "getServicesList_getTheNameSpaceServicesFail")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}

			availableServiceNum := resourceLimitData.AvailableService
			infoLogger.Printf("已有服务数量:%d 可用服务数量上限:%d", len(serviceList.Items), availableServiceNum)
			if availableServiceNum > 0 && availableServiceNum <= len(serviceList.Items) {
				errorLogger.Println("服务数量不能超过可用服务数量上限")
				responseDto.Message = utils.GetI18nLang(lang, "saveGuiServiceResource_cannotExceedAvailableServiceNumber")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
		}
	}

	if !utils.IsContains([]string{"ClusterIP", "NodePort", "Headless"}, serviceType) {
		errorLogger.Println("服务类型仅支持ClusterIP、NodePort、Headless")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	// Headless类型不需要校验服务名称
	if serviceType != "Headless" {
		if len(serviceName) < 2 || len(serviceName) > 63 {
			errorLogger.Println("服务名称长度必须在2-63之间")
			responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		if len(controllerNameList) == 0 {
			errorLogger.Println("后端部署名称不能为空")
			responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
	} else {
		if len(controllerNameList) == 0 {
			errorLogger.Println("后端状态集名称不能为空")
			responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		// 后端状态集只能添加一个
		if len(controllerNameList) > 1 {
			errorLogger.Println("后端状态集只能添加一个")
			responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
	}

	if len(ports) == 0 {
		errorLogger.Println("端口不能为空")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	if len(ports) > 10 {
		errorLogger.Println("端口最多只能添加10个")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}

	serviceOptions := v1.Service{}

	statefulSetName := ""
	// Headless类型需要校验StatefulSet里面的服务名称是否与请求参数中的服务名称一致
	if serviceType == "Headless" {
		statefulSetName = controllerNameList[0]
		//查询service是否存在
		statefulSetInfo, err := k8sClient.AppsV1().StatefulSets(nameSpace).Get(statefulSetName, metav1.GetOptions{})
		if err != nil {
			errorLogger.Printf("查询集群%s空间StatefulSet:%s是否存在失败: %s", nameSpace, statefulSetName, err.Error())
			responseDto.Message = utils.GetI18nLang(lang, "getControllerPortList_getStatefulSetInfoFail")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		// 取StatefulSet的ServiceName字段
		stateFulSetServiceName := statefulSetInfo.Spec.ServiceName
		infoLogger.Println("StatefulSet ServiceName:", stateFulSetServiceName)
		if stateFulSetServiceName != serviceName {
			errorLogger.Println("StatefulSet 的ServiceName 与请求参数中的服务名称不一致")
			responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		// 使用StatefulSet的ServiceName字段值
		serviceName = stateFulSetServiceName
	}

	//查询service是否存在
	serviceInfo, err := k8sClient.CoreV1().Services(nameSpace).Get(serviceName, metav1.GetOptions{})
	if err == nil {
		if operateType == "create" {
			errorLogger.Printf("集群%s空间%s service已存在", nameSpace, serviceName)
			responseDto.Message = utils.GetI18nLang(lang, "saveServiceResource_serviceAlreadyExists")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		serviceOptions = *serviceInfo
	} else {
		errStr := err.Error()
		if operateType == "create" {
			if !strings.Contains(errStr, "not found") {
				errorLogger.Printf("查询集群%s空间%s service详情失败: %s", nameSpace, serviceName, errStr)
				responseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
		} else if operateType == "update" {
			errorLogger.Printf("查询集群%s空间%s service详情失败: %s", nameSpace, serviceName, errStr)
			responseDto.Message = utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
			if strings.Contains(errStr, "not found") {
				errorLogger.Printf("集群%s空间%s service不存在", nameSpace, serviceName)
				responseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
			}
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
	}

	//编辑时不能修改服务类型
	if operateType == "update" {
		if serviceInfo.Spec.ClusterIP == "None" {
			if serviceType != "Headless" {
				errorLogger.Println("服务类型不能修改")
				responseDto.Message = utils.GetI18nLang(lang, "saveGuiServiceResource_serviceTypeCannotUpdate")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
		} else {
			if serviceInfo.Spec.Type != v1.ServiceType(serviceType) {
				errorLogger.Println("服务类型不能修改")
				responseDto.Message = utils.GetI18nLang(lang, "saveGuiServiceResource_serviceTypeCannotUpdate")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
		}
	}
	serviceOptions.TypeMeta.APIVersion = "v1"
	serviceOptions.TypeMeta.Kind = "Service"
	serviceOptions.ObjectMeta.Name = serviceName
	serviceOptions.Spec.Type = v1.ServiceType(serviceType)
	if serviceType == "Headless" {
		serviceOptions.Spec.Type = "ClusterIP"
		serviceOptions.Spec.ClusterIP = "None"
	}

	deployPorts := []string{}
	labelsMap := map[string]string{}
	for _, v := range controllerNameList {
		// 非Headless类型 绑定deploy
		if serviceType != "Headless" {
			infoLogger.Println("deploy name:", v)
			//查询deploy是否存在
			deployInfo, err := k8sClient.AppsV1().Deployments(nameSpace).Get(v, metav1.GetOptions{})
			if err != nil {
				errStr := err.Error()
				errorLogger.Printf("查询集群%s空间%s deploy是否存在失败: %s", nameSpace, v, errStr)
				responseDto.Message = utils.GetI18nLang(lang, "getDeploymentInfo_getTheDeploymentInfoFail")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
			// 取pod的labels
			labels := deployInfo.Spec.Template.ObjectMeta.Labels
			infoLogger.Println("labels:", labels)
			for k, val := range labels {
				if _, ok := labelsMap[k]; !ok {
					labelsMap[k] = val
				}
			}

			containers := deployInfo.Spec.Template.Spec.Containers
			for _, c := range containers {
				for _, p := range c.Ports {
					deployPorts = append(deployPorts, utils.Int32ToString(p.ContainerPort), p.Name)
				}
			}
		} else { // 非Headless类型 绑定StatefulSet
			infoLogger.Println("StatefulSet name:", v)
			//查询StatefulSet是否存在
			statefulSetInfo, err := k8sClient.AppsV1().StatefulSets(nameSpace).Get(v, metav1.GetOptions{})
			if err != nil {
				errStr := err.Error()
				errorLogger.Printf("查询集群%s空间%s StatefulSet是否存在失败: %s", nameSpace, v, errStr)
				responseDto.Message = utils.GetI18nLang(lang, "getControllerPortList_getStatefulSetInfoFail")
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
			// 取pod的labels
			labels := statefulSetInfo.Spec.Template.ObjectMeta.Labels
			infoLogger.Println("labels:", labels)
			for k, val := range labels {
				if _, ok := labelsMap[k]; !ok {
					labelsMap[k] = val
				}
			}

			containers := statefulSetInfo.Spec.Template.Spec.Containers
			for _, c := range containers {
				for _, p := range c.Ports {
					deployPorts = append(deployPorts, utils.Int32ToString(p.ContainerPort), p.Name)
				}
			}
		}
	}

	infoLogger.Printf("端口:%v", deployPorts)
	infoLogger.Println("labels:", labelsMap)
	// 绑定selector
	serviceOptions.Spec.Selector = labelsMap

	// 目标端口在控制器所定义的端口中的目标端口个数
	targetPortInController := 0
	servicePort := []v1.ServicePort{}
	//保存所有的暴露端口
	nodePortList := []int32{}
	for _, p := range ports {
		if len(p.PortName) < 2 || len(p.PortName) > 63 {
			errorLogger.Println("端口名称长度必须在2-63之间")
			responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}

		targetPort := p.TargetPort
		if utils.IsContains(deployPorts, targetPort) {
			targetPortInController += 1
		}

		var nodePort int32 = 0
		if operateType == "create" {
			// 如果服务类型是NodePort 并且没有选择自动分配 则使用暴露端口参数值
			if serviceType == "NodePort" && !p.AutomaticAllocation {
				if p.NodePort < 1 || p.NodePort > 65535 {
					errorLogger.Println("暴露端口号不能为空，并且只能在1-65535之间")
					responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
					c.Data["json"] = responseDto
					c.ServeJSON()
					return
				}

				if utils.IsContains(nodePortList, nodePort) {
					errorLogger.Println("暴露端口号不能重复")
					responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
					c.Data["json"] = responseDto
					c.ServeJSON()
					return
				}
				nodePortList = append(nodePortList, p.NodePort)
				nodePort = p.NodePort
			}
		} else if operateType == "update" {
			// 如果服务类型是NodePort 则使用暴露端口参数值
			if serviceType == "NodePort" {
				if p.NodePort < 1 || p.NodePort > 65535 {
					errorLogger.Println("暴露端口号不能为空，并且只能在1-65535之间")
					responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
					c.Data["json"] = responseDto
					c.ServeJSON()
					return
				}
				if utils.IsContains(nodePortList, nodePort) {
					errorLogger.Println("暴露端口号不能重复")
					responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
					c.Data["json"] = responseDto
					c.ServeJSON()
					return
				}
				nodePortList = append(nodePortList, p.NodePort)
				nodePort = p.NodePort
			}
		}

		s := v1.ServicePort{
			p.PortName,
			v1.Protocol(p.Protocol),
			p.Port,
			intstr.Parse(targetPort),
			nodePort,
		}
		servicePort = append(servicePort, s)
	}

	// 校验目标端口是否在后端部署或后端状态集的端口中
	if len(ports) != targetPortInController {
		errorLogger.Println("目标端口不在后端部署或后端状态集定义的容器端口中")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}

	serviceOptions.Spec.Ports = servicePort

	infoLogger.Println("执行校验通过图形界面保存服务请求参数")
	// 校验请求参数
	if err := checkServiceParams(lang, nameSpace, operateType, serviceName, serviceOptions); err != nil {
		errorLogger.Printf("校验通过图形界面创建或编辑保存服务请求参数失败: %s", err.Error())
		responseDto.Message = err.Error()
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	infoLogger.Println("校验通过图形界面保存服务请求参数成功")

	infoLogger.Println("执行通过图形界面保存服务...")
	if operateType == "create" {
		//查询service是否存在
		_, err := k8sClient.CoreV1().Services(nameSpace).Get(serviceName, metav1.GetOptions{})
		if err == nil {
			errorLogger.Printf("集群%s空间%s service已存在", nameSpace, serviceName)
			responseDto.Message = utils.GetI18nLang(lang, "saveServiceResource_serviceAlreadyExists")
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		//创建service
		if _, err := k8sClient.CoreV1().Services(nameSpace).Create(&serviceOptions); err != nil {
			errStr := err.Error()
			errorLogger.Printf("创建集群%s空间%s service失败: %s", nameSpace, serviceName, errStr)
			m, _ := regexp.MatchString(".*([iI]nvalid).*", errStr)
			switch {
			case strings.Contains(errStr, "resourceVersion should not be set on objects to be created"):
				responseDto.Message = utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat")
			case m:
				responseDto.Message = utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat")
			default:
				responseDto.Message = utils.GetI18nLang(lang, "saveServiceResource_createServiceFail")
			}
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		infoLogger.Printf("创建集群%s空间%s service成功", nameSpace, serviceName)
	} else if operateType == "update" {
		//更新service
		if _, err := k8sClient.CoreV1().Services(nameSpace).Update(&serviceOptions); err != nil {
			errStr := err.Error()
			errorLogger.Printf("更新集群%s空间%s service失败: %s", nameSpace, serviceName, errStr)
			if strings.Contains(errStr, "not found") {
				responseDto.Message = utils.GetI18nLang(lang, "removeService_serviceNotFound")
			} else {
				responseDto.Message = utils.GetI18nLang(lang, "saveServiceResource_updateServiceFail")
				if m, _ := regexp.MatchString(".*([iI]nvalid).*", errStr); m {
					responseDto.Message = utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat")
				}
				c.Data["json"] = responseDto
				c.ServeJSON()
				return
			}
		}
		infoLogger.Printf("更新集群%s空间%s service成功", nameSpace, serviceName)
	}

	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	c.Data["json"] = responseDto
	c.ServeJSON()
}

// 校验操作(更新、新增)服务的请求参数
func checkServiceParams(lang string, nameSpace string, operateType string, oldServiceName string,
	serviceOptions v1.Service) error {

	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		return errors.New(utils.GetI18nLang(lang, "createK8sConFail"))
	}
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		return errors.New(utils.GetI18nLang(lang, "requestParamIncorrectFormat"))
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println("allNameSpaceList:", allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		return errors.New(utils.GetI18nLang(lang, "getClusterAllNamespacesFail"))
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		return errors.New(utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster"))
	}
	if !utils.IsContains([]string{"update", "create"}, operateType) {
		errorLogger.Println("operateType 只能为update或create")
		return errors.New(utils.GetI18nLang(lang, "requestParamIncorrectFormat"))
	}

	if serviceOptions.TypeMeta.APIVersion != "v1" {
		errorLogger.Println("apiVersion只能是v1")
		return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
	}
	if serviceOptions.TypeMeta.Kind != "Service" {
		errorLogger.Println("kind只能是Service")
		return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
	}

	// 转换yaml格式
	yamlBytes, err := yaml.Marshal(serviceOptions)
	if err != nil {
		errorLogger.Printf("转换yaml失败: %s", err.Error())
		return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
	}
	infoLogger.Println("\n" + string(yamlBytes))

	//serviceNameSpace := serviceOptions.ObjectMeta.Namespace
	//if strings.TrimSpace(serviceNameSpace) != "" && serviceNameSpace != nameSpace {
	//	errorLogger.Println("命名空间必须与当前命名空间一致")
	//	return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
	//}
	//serviceType := string(serviceOptions.Spec.Type)
	//if strings.TrimSpace(serviceType) == "" {
	//	errorLogger.Println("服务类型不能为空")
	//	return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
	//}
	//serviceTypeList := []string{"ClusterIP", "ExternalName", "LoadBalancer", "NodePort"}
	//if !utils.IsContains(serviceTypeList, serviceType) {
	//	errorLogger.Println("服务类型只能为: ClusterIP、ExternalName、LoadBalancer、NodePort")
	//	return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
	//}

	decode := scheme.Codecs.UniversalDeserializer()
	if _, _, err = decode.Decode(yamlBytes, nil, nil); err != nil {
		errorLogger.Printf("转换yaml文件失败: %s", err.Error())
		return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
	}

	if operateType == "update" {
		//查询service详情
		if _, err := k8sClient.CoreV1().Services(nameSpace).Get(oldServiceName, metav1.GetOptions{}); err != nil {
			errStr := err.Error()
			errorLogger.Printf("查询集群%s空间原服务%s是否存在失败: %s", nameSpace, oldServiceName, errStr)
			text := utils.GetI18nLang(lang, "getServiceInfo_getTheServiceInfoFail")
			if strings.Contains(errStr, "not found") {
				errorLogger.Println("原服务不存在")
				text = utils.GetI18nLang(lang, "removeService_serviceNotFound")
			}
			return errors.New(text)
		}
		newServiceName := serviceOptions.ObjectMeta.Name
		if newServiceName != oldServiceName {
			errorLogger.Println("服务名称不允许修改")
			return errors.New(utils.GetI18nLang(lang, "checkServiceParams_serviceNameNotAllowedUpdate"))
		}

		err = k8sClient.CoreV1().RESTClient().Put().
			SetHeader("Accept", "application/json; dry-run").
			SetHeader("Content-Type", "application/json; verify").
			Namespace(nameSpace).
			Resource("services").
			Name(oldServiceName).
			Body(&serviceOptions).
			Param("dryRun", "All").
			Do().Error()
		if err != nil {
			errStr := err.Error()
			errorLogger.Printf("校验运行失败: %s", errStr)
			errorLogger.Println(strings.Split(errStr, "\n")[0])
			return errors.New(strings.Split(errStr, "\n")[0])
		}
	} else if operateType == "create" {
		if strings.TrimSpace(serviceOptions.ObjectMeta.ResourceVersion) != "" {
			errorLogger.Println("创建service时resourceVersion必须为空")
			return errors.New(utils.GetI18nLang(lang, "checkServiceParams_invalidServiceFormat"))
		}

		err = k8sClient.CoreV1().RESTClient().Post().
			SetHeader("Accept", "application/json; dry-run").
			SetHeader("Content-Type", "application/json; verify").
			Namespace(nameSpace).
			Resource("services").
			Body(&serviceOptions).
			Param("dryRun", "All").
			Do().Error()
		if err != nil {
			errStr := err.Error()
			errorLogger.Printf("校验运行失败: %s", errStr)
			text := strings.Split(errStr, "\n")[0]
			if strings.Contains(errStr, "already exists") {
				text = utils.GetI18nLang(lang, "saveServiceResource_serviceAlreadyExists")
			}
			return errors.New(text)
		}
	}

	return nil
}
