package pods

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

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

// PodController operations for Pod
type PodController struct {
	beego.Controller
}

// URLMapping ...
func (c *PodController) URLMapping() {
	c.Mapping("getPodList", c.GetPodList)
	c.Mapping("deletePod", c.DeletePod)
	c.Mapping("getPodOriginalInfo", c.GetPodOriginalInfo)
	c.Mapping("getAllPodRunningContainer", c.GetAllPodRunningContainer)
	c.Mapping("checkPodContent", c.CheckPodContent)
	c.Mapping("savePodResource", c.SavePodResource)
}

// Post ...
// @Title GetPodList
// @Description get PodList
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	pods.GetPodListRequestDto	 true	""
// @Success 200 {object} dto.GetPageListBaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getPodList [post]
func (c *PodController) GetPodList() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto pods.GetPodListRequestDto
	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
	}

	//查询命名空间下所有pod信息
	podList, err := k8sClient.CoreV1().Pods(nameSpace).List(metav1.ListOptions{})
	if err != nil {
		errorLogger.Printf("查询集群%s空间所有pod失败: %s", nameSpace, err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getPodList_getTheNameSpacePodsFail")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	itemList := podList.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 := []pods.GetPodListResultDataResponseDto{}
	for i, item := range resultList {
		infoLogger.Printf("-----------第%d个pod----------------", i+1)
		infoLogger.Println("pod name:", item.Name)
		//所有容器个数
		allContainer := len(item.Spec.Containers)
		infoLogger.Println("containers:", allContainer)
		containerStatuses := item.Status.ContainerStatuses

		//就绪运行的所有容器个数
		readyContainer := 0
		var restartCount int32 = 0
		reason := ""
		if strings.TrimSpace(item.Status.Reason) != "" {
			reason = item.Status.Reason
		}
		hasRunning := false
		for _, cs := range containerStatuses {
			infoLogger.Println("restartCount:", cs.RestartCount)
			if cs.State.Terminated != nil && cs.State.Terminated.Reason != "" {
				infoLogger.Println("terminated reason:", cs.State.Terminated.Reason)
				reason = cs.State.Terminated.Reason
			}
			if cs.State.Waiting != nil && cs.State.Waiting.Reason != "" {
				infoLogger.Println("waiting reason:", cs.State.Waiting.Reason)
				reason = cs.State.Waiting.Reason
			}
			restartCount += cs.RestartCount
			if cs.Ready {
				readyContainer += 1
			}
			if cs.Ready && cs.State.Running != nil {
				hasRunning = true
			}
		}
		if reason == "Completed" && hasRunning {
			reason = "Running"
		}
		// NodeLost(取自 node.NodeUnreachablePodReason) is the reason on a pod when
		// its state cannot be confirmed as kubelet is unresponsive
		// on the node it is (was) running.
		if item.DeletionTimestamp != nil && item.Status.Reason == "NodeLost" {
			reason = "Unknown"
		} else if item.DeletionTimestamp != nil {
			reason = "Terminating"
		}
		infoLogger.Println("reason:", reason)

		readyStr := strconv.Itoa(readyContainer) + "/" + strconv.Itoa(allContainer)
		infoLogger.Println("ready:", readyStr)
		creationTimestamp := utils.GetDurationToString(lang, item.CreationTimestamp.Time, true)
		infoLogger.Println("creationTimestamp:", item.CreationTimestamp.Time, " ", creationTimestamp)
		infoLogger.Println("podIP:", item.Status.PodIP)
		infoLogger.Println("hostIP:", item.Status.HostIP)

		phase := string(item.Status.Phase)
		infoLogger.Println("phase:", phase)
		if strings.TrimSpace(reason) != "" {
			phase = reason
		}
		o := pods.GetPodListResultDataResponseDto{
			item.Name,
			readyStr,
			phase,
			restartCount,
			creationTimestamp,
			item.Status.PodIP,
			item.Status.HostIP,
		}
		result = append(result, o)
	}

	//resultList := []pods.GetPodListResultDataResponseDto{}
	//if totalRecords > 0 {
	//	totalPages = totalRecords/pageSize + 1
	//	if totalRecords%pageSize == 0 {
	//		totalPages = totalRecords / pageSize
	//	}
	//	if totalRecords <= pageIndex*pageSize {
	//		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
	//		c.Data["json"] = errorResponseDto
	//		c.ServeJSON()
	//		return
	//	}
	//	resultList = result[pageIndex*pageSize:]
	//	if len(result)-pageIndex*pageSize >= pageSize {
	//		resultList = result[pageIndex*pageSize : (pageIndex+1)*pageSize]
	//	}
	//
	//} else {
	//	if totalRecords < pageIndex*pageSize {
	//		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
	//		c.Data["json"] = errorResponseDto
	//		c.ServeJSON()
	//		return
	//	}
	//}

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

// Post ...
// @Title DeletePod
// @Description remove Pod
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	pods.DeletePodRequestDto	 true	""
// @Success 200 {object} dto.BaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /deletePod [post]
func (c *PodController) DeletePod() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto pods.DeletePodRequestDto
	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
	podName := requestDto.PodName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = responseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(podName) == "" {
		errorLogger.Println("pod名称不能为空")
		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
	}

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

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

// Post ...
// @Title GetPodOriginalInfo
// @Description get podOriginalInfo
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	pods.GetPodOriginalInfoRequestDto	 true	""
// @Success 200 {object} dto.BaseResultResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getPodOriginalInfo [post]
func (c *PodController) GetPodOriginalInfo() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto pods.GetPodOriginalInfoRequestDto
	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
	podName := requestDto.PodName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(podName) == "" {
		errorLogger.Println("pod名称不能为空")
		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
	}

	podInfo, err := k8sClient.CoreV1().Pods(nameSpace).Get(podName, metav1.GetOptions{})
	if err != nil {
		errStr := err.Error()
		errorLogger.Printf("查询%s空间pod:%s详情失败:%s", nameSpace, podName, err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getPodOriginalInfo_getPodInfoFail")
		if strings.Contains(errStr, "not found") {
			errorResponseDto.Message = utils.GetI18nLang(lang, "removePod_podNotFound")
		}
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	podInfo.APIVersion = "v1"
	podInfo.Kind = "Pod"
	//var podMap map[string]interface{}
	//if podByte, err := json.Marshal(podInfo); err != nil {
	//	errorLogger.Printf("转换byte失败: %s", err.Error())
	//} else {
	//	if err := json.Unmarshal(podByte, &podMap); err != nil {
	//		errorLogger.Printf("转换map失败: %s", err.Error())
	//	}
	//}
	//
	//successResponseDto.Result = podInfo
	//if podMap != nil {
	//	metadataMap := podMap["metadata"].(map[string]interface{})
	//	specMap := podMap["spec"].(map[string]interface{})
	//	// 删除不需要展示的字段
	//	//delete(metadataMap, "selfLink")
	//	//delete(metadataMap, "uid")
	//	delete(metadataMap, "creationTimestamp")
	//	delete(metadataMap, "generateName")
	//	delete(metadataMap, "ownerReferences")
	//
	//	delete(specMap, "nodeName")
	//
	//	delete(podMap, "status")
	//	successResponseDto.Result = podMap
	//}

	// 转换yaml格式
	yamlBytes, err := yaml.Marshal(podInfo)
	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 GetAllPodRunningContainer
// @Description get getAllPodRunningContainer
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	pods.GetAllPodRunningContainerRequestDto	 true	""
// @Success 200 {object} dto.BaseResultResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getAllPodRunningContainer [post]
func (c *PodController) GetAllPodRunningContainer() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto pods.GetAllPodRunningContainerRequestDto
	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
	podName := requestDto.PodName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	if strings.TrimSpace(podName) == "" {
		errorLogger.Println("pod名称不能为空")
		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
	}

	podInfo, err := k8sClient.CoreV1().Pods(nameSpace).Get(podName, metav1.GetOptions{})
	if err != nil {
		errStr := err.Error()
		errorLogger.Printf("查询%s空间pod:%s详情失败:%s", nameSpace, podName, errStr)
		errorResponseDto.Message = utils.GetI18nLang(lang, "getPodOriginalInfo_getPodInfoFail")
		if strings.Contains(errStr, "not found") {
			errorResponseDto.Message = utils.GetI18nLang(lang, "removePod_podNotFound")
		}
		c.Data["json"] = errorResponseDto
		c.ServeJSON()
		return
	}
	containers := podInfo.Spec.Containers
	containerStatuses := podInfo.Status.ContainerStatuses

	//就绪运行的所有容器
	allContainers := []string{}
	for _, c := range containers {
		infoLogger.Println("container name:", c.Name)
		for _, v := range containerStatuses {
			if c.Name == v.Name {
				infoLogger.Println(v.Name, "ready:", v.Ready)
				//就绪运行的所有容器
				//if v.Ready {
				//	readyContainers = append(readyContainers, c.Name)
				//}
				//break
				allContainers = append(allContainers, c.Name)
			}
		}
	}
	infoLogger.Println("allContainers:", allContainers)

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

// Post ...
// @Title CheckPodContent
// @Description check podContent
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	pods.CheckPodContentRequestDto	true	""
// @Success 200 {object} dto.BaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /checkPodContent [post]
func (c *PodController) CheckPodContent() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto pods.CheckPodContentRequestDto
	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)

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

	infoLogger.Println("执行校验容器组内容")
	// 校验请求参数
	if err := checkPodParams(lang, requestDto.NameSpace, requestDto.OperateType, podOptions); 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 SavePodResource
// @Description save PodResource
// @Param	lang		query 	string	true	"api result language type"
// @Param	body		body 	pods.SavePodResourceRequestDto	true	""
// @Success 200 {object} dto.BaseResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /savePodResource [post]
func (c *PodController) SavePodResource() {
	lang := c.GetString("lang")
	infoLogger.Println("语言: ", lang)
	body := c.Ctx.Input.RequestBody
	infoLogger.Println("保存容器组请求参数: \n", body)
	var requestDto pods.SavePodResourceRequestDto
	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
	podOptions := v1.Pod{}
	// 复制字段
	utils.StructCopy(&podOptions, &requestDto)

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

	podName := podOptions.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" {
		//更新pod
		if _, err := k8sClient.CoreV1().Pods(nameSpace).Update(&podOptions); err != nil {
			errStr := err.Error()
			errorLogger.Printf("更新集群%s空间pod: %s 失败: %s", nameSpace, podName, errStr)
			responseDto.Message = utils.GetI18nLang(lang, "savePodResource_updatePodFail")
			if m, _ := regexp.MatchString(".*([iI]nvalid).*", errStr); m {
				responseDto.Message = utils.GetI18nLang(lang, "checkPodParams_invalidPodFormat")
			}
			c.Data["json"] = responseDto
			c.ServeJSON()
			return
		}
		infoLogger.Printf("更新集群%s空间pod: %s 成功", nameSpace, podName)
	} else if operateType == "create" {
		////查询pod是否存在
		//_, err := k8sClient.CoreV1().Pods(nameSpace).Get(podName, metav1.GetOptions{})
		//if err == nil {
		//	errorLogger.Printf("集群%s空间pod: %s已存在", nameSpace, podName)
		//	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空间pod: %s 详情失败: %s", nameSpace, podName, errStr)
		//	responseDto.Message = utils.GetI18nLang(lang, "getPodOriginalInfo_getPodInfoFail")
		//	c.Data["json"] = responseDto
		//	c.ServeJSON()
		//	return
		//}
		////创建pod
		//if _, err = k8sClient.CoreV1().Pods(nameSpace).Create(&podOptions); err != nil {
		//	errStr := err.Error()
		//	errorLogger.Printf("创建集群%s空间pod: %s 失败: %s", nameSpace, podName, errStr)
		//	responseDto.Message = utils.GetI18nLang(lang, "")
		//	c.Data["json"] = responseDto
		//	c.ServeJSON()
		//	return
		//}
		//infoLogger.Printf("创建集群%s空间pod: %s 成功", nameSpace, podName)
	}

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

// 校验操作(更新、新增)服务的请求参数
func checkPodParams(lang string, nameSpace string, operateType string, podOptions v1.Pod) 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"}, operateType) {
		errorLogger.Println("operateType 只能为update")
		return errors.New(utils.GetI18nLang(lang, "requestParamIncorrectFormat"))
	}

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

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

	//podName := podOptions.ObjectMeta.Name
	//if strings.TrimSpace(podName) == "" {
	//	errorLogger.Println("pod名称不能为空")
	//	return errors.New(utils.GetI18nLang(lang, "checkPodParams_invalidPodFormat"))
	//}
	//podNameSpace := podOptions.ObjectMeta.Namespace
	//if strings.TrimSpace(podNameSpace) != "" && podNameSpace != nameSpace {
	//	errorLogger.Println("命名空间必须与当前命名空间一致")
	//	return errors.New(utils.GetI18nLang(lang, "checkPodParams_invalidPodFormat"))
	//}

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

	if operateType == "update" {
		err = k8sClient.CoreV1().RESTClient().Put().
			SetHeader("Accept", "application/json; dry-run").
			SetHeader("Content-Type", "application/json; verify").
			Namespace(nameSpace).
			Resource("pods").
			Name(podOptions.ObjectMeta.Name).
			Body(&podOptions).
			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" {
		//err = k8sClient.CoreV1().RESTClient().Post().
		//	SetHeader("Accept", "application/json; dry-run").
		//	SetHeader("Content-Type", "application/json; verify").
		//	Namespace(nameSpace).
		//	Resource("services").
		//	Body(&podOptions).
		//	Param("dryRun", "All").
		//	Do().Error()
		//if err != nil {
		//	errorLogger.Printf("校验运行失败: %s", err.Error())
		//	return errors.New(utils.GetI18nLang(lang, "checkPodParams_invalidPodFormat"))
		//}
	}

	return nil
}
