package ingress

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"k8s-console/dto"
	"k8s-console/dto/ingress"
	"k8s-console/models"
	"k8s-console/utils"
	"k8s.io/api/extensions/v1beta1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"log"
	"sigs.k8s.io/yaml"
	"strconv"
	"strings"
	"time"
)

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

type IngressController struct {
	beego.Controller
}

/**
  获取全部ingress
*/
// @router /getIngressList [post]
func (u *IngressController) GetAllIngress() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.GetIngressListRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.GetPageListBaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("查询负载均衡列表请求参数: ", requestDto)

	pageIndex := requestDto.PageIndex
	pageSize := requestDto.PageSize
	if pageIndex < 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexRange")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	if pageSize <= 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageSizeRange")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	nameSpace := requestDto.NameSpace
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println(allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	//查询名称空间下所有负载均衡
	beans, err := models.GetAllIngress(nameSpace, lang)
	if err != nil {
		errorLogger.Printf("查询集群%s空间所有ingress失败: %s", nameSpace, err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	resultList := []models.IngressBean{}
	totalRecords := len(beans)
	totalPages := 0
	if totalRecords > 0 {
		totalPages = totalRecords/pageSize + 1
		if totalRecords%pageSize == 0 {
			totalPages = totalRecords / pageSize
		}
		if totalRecords <= pageIndex*pageSize {
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			u.Data["json"] = errorResponseDto
			u.ServeJSON()
			return
		}
		resultList = beans[pageIndex*pageSize:]
		if len(beans)-pageIndex*pageSize >= pageSize {
			resultList = beans[pageIndex*pageSize : (pageIndex+1)*pageSize]
		}

	} else {
		if totalRecords < pageIndex*pageSize {
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			u.Data["json"] = errorResponseDto
			u.ServeJSON()
			return
		}
	}
	successResponseDto.Result = resultList
	successResponseDto.PageInfo = dto.PageInfoBaseResponseDto{
		TotalRecords: totalRecords,
		TotalPages:   totalPages,
	}
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  删除 ingress
*/
// @router /deleteIngress [post]
func (u *IngressController) DeleteIngressByName() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.GetDeleteIngressRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("删除负载均衡请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	ingressName := requestDto.IngressName
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	if strings.TrimSpace(ingressName) == "" {
		errorLogger.Println("负载均衡名称不能为空")
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println(allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		responseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	err = models.DeleteIngress(ingressName, nameSpace)
	if err != nil {
		responseDto.Message = utils.GetI18nLang(lang, "")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Printf("删除集群%s空间%s service成功", nameSpace, ingressName)

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

/**
  详情 ingress 接口
*/
// @router /getDetailByIngressName [post]
func (u *IngressController) GetIngressByNameDetail() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.GetIngressByNameRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.GetPageListBaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("查询负载均衡详情请求参数: ", requestDto)

	pageIndex := requestDto.PageIndex
	pageSize := requestDto.PageSize
	if pageIndex < 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexRange")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	if pageSize <= 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageSizeRange")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	nameSpace := requestDto.NameSpace
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println(allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	bean, err := models.GetIngressDetailByName(requestDto.IngressName, nameSpace)
	if err != nil {
		errorLogger.Println("获取集群ingress详情失败")
		errorResponseDto.Message = err.Error()
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	rules := bean.Rules
	resultList := []models.HostBean{}
	totalRecords := len(rules)
	totalPages := 0
	if totalRecords > 0 {
		totalPages = totalRecords/pageSize + 1
		if totalRecords%pageSize == 0 {
			totalPages = totalRecords / pageSize
		}
		if totalRecords <= pageIndex*pageSize {
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			u.Data["json"] = errorResponseDto
			u.ServeJSON()
			return
		}
		resultList = rules[pageIndex*pageSize:]
		if len(rules)-pageIndex*pageSize >= pageSize {
			resultList = rules[pageIndex*pageSize : (pageIndex+1)*pageSize]
		}

	} else {
		if totalRecords < pageIndex*pageSize {
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			u.Data["json"] = errorResponseDto
			u.ServeJSON()
			return
		}
	}
	bean.Rules = resultList
	successResponseDto.Result = bean
	successResponseDto.PageInfo = dto.PageInfoBaseResponseDto{
		TotalRecords: totalRecords,
		TotalPages:   totalPages,
	}
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  编辑ingress接口
*/
// @router /editIngressByName [post]
func (u *IngressController) EditIngressByName() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.EditIngressByNameRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("查询负载均衡详情请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println(allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	ingressMap, err := models.EditIngressByName(requestDto.IngressName, requestDto.NameSpace)
	if err != nil {
		log.Printf("编辑负载均衡接口失败：%s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	//转换yaml格式
	yamlBytes, err := yaml.Marshal(ingressMap)
	if err != nil {
		errorLogger.Printf("转换yaml失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("\n" + string(yamlBytes))

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

/**
  校验 ingress 接口
*/
// @router /checkIngressContent [post]
func (u *IngressController) CheckIngress() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.CheckIngressContentRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("校验负载均衡内容请求参数: ", requestDto)
	ingressOptions := v1beta1.Ingress{}
	// 复制字段
	utils.StructCopy(&ingressOptions, &requestDto)
	ingressOptions.CreationTimestamp.Time = time.Now()
	infoLogger.Println("执行校验服务内容")

	err := models.CheckIngressContent(lang, requestDto.NameSpace, requestDto.OperateType, ingressOptions)
	if err != nil {
		errorLogger.Printf("校验负载均衡内容请求参数失败: %s", err.Error())
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("校验负载均衡服务内容成功")
	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	u.Data["json"] = responseDto
	u.ServeJSON()
}

/**
  保存接口
*/
// @router /saveAndupdateIngressContent [post]
func (u *IngressController) SaveAndupdateIngress() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.SaveAndupdateIngressContentRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("保存或更新负载均衡请求参数: ", requestDto)

	nameSpace := requestDto.NameSpace
	operateType := requestDto.OperateType
	ingressOptions := v1beta1.Ingress{}
	// 复制字段
	utils.StructCopy(&ingressOptions, &requestDto)
	ingressOptions.CreationTimestamp.Time = time.Now()

	infoLogger.Println("执行校验保存或更新负载均衡请求参数")
	// 校验请求参数
	if err := models.CheckIngressContent(lang, nameSpace, operateType, ingressOptions); err != nil {
		errorLogger.Printf("校验保存或更新负载均衡请求参数失败: %s", err.Error())
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("校验保存或更新负载均衡请求参数成功")
	err := models.SaveAndupdateIngress(lang, nameSpace, operateType, ingressOptions)
	if err != nil {
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	u.Data["json"] = responseDto
	u.ServeJSON()
}

/**
  获取 serviceName 及对应的 ports
*/
// @router /getServiceNamePorts [get]
func (u *IngressController) GetServiceNamePorts() {
	ns := u.GetString("namespace")
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang("zh", "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	bean, err := models.GetServiceNamePortsConfigInfo(ns)
	if err != nil {
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	successResponseDto.Result = bean
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  通过图形界面创建 ingress
*/
// @router /createIngressByGui [post]
func (u *IngressController) CreateIngressByGui() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.AddIngressByGuiRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("图形化负载均衡请求参数: ", requestDto)
	saveBean := ingress.SaveAndupdateIngressContentRequestDto{}
	saveBean.Name = requestDto.Name
	saveBean.NameSpace = requestDto.Namespace
	saveBean.OperateType = "create"
	saveBean.Annotations = requestDto.Annotations
	saveBean.Namespace = requestDto.Namespace
	saveBean.Kind = "Ingress"
	saveBean.APIVersion = "extensions/v1beta1"
	len := len(requestDto.Rules)
	//var ruls [len]v1beta1.IngressRule
	saveBean.Spec.Rules = make([]v1beta1.IngressRule, len)
	// tls
	tlsHttps := []string{}
	//saveBean.Spec.Rules
	for i := 0; i < len; i++ {
		tlsHttps = append(tlsHttps, requestDto.Rules[i].Host)
		saveBean.Spec.Rules[i].Host = requestDto.Rules[i].Host
		if saveBean.Spec.Rules[i].HTTP == nil {
			saveBean.Spec.Rules[i].HTTP = &v1beta1.HTTPIngressRuleValue{}
		}
		if saveBean.Spec.Rules[i].HTTP.Paths == nil {
			saveBean.Spec.Rules[i].HTTP.Paths = make([]v1beta1.HTTPIngressPath, 1)
		}
		saveBean.Spec.Rules[i].HTTP.Paths[0].Path = requestDto.Rules[i].Path
		saveBean.Spec.Rules[i].HTTP.Paths[0].Backend.ServiceName = requestDto.Rules[i].ServiceName
		servicePort := intstr.IntOrString{}
		if strings.Contains(requestDto.Rules[i].ServicePort, "(") {
			// 格式为：http(8080)  存在name值，不用port值
			index := strings.Index(requestDto.Rules[i].ServicePort, "(")
			str := requestDto.Rules[i].ServicePort[0:index]
			logs.Info("servicePort:", str)
			servicePort.Type = intstr.String
			servicePort.StrVal = str
		} else {
			if utils.IsNumber(requestDto.Rules[i].ServicePort) {
				port, _ := strconv.Atoi(requestDto.Rules[i].ServicePort)
				logs.Info("servicePort:", port)
				servicePort.Type = intstr.Int
				servicePort.IntVal = int32(port)
			} else {
				responseDto.Message = utils.GetI18nLang(lang, "fail")
				u.Data["json"] = responseDto
				u.ServeJSON()
				return
			}
		}
		saveBean.Spec.Rules[i].HTTP.Paths[0].Backend.ServicePort = servicePort
	}
	if requestDto.IsHttps {
		//支持https
		if saveBean.Spec.TLS == nil {
			saveBean.Spec.TLS = make([]v1beta1.IngressTLS, 1)
		}
		saveBean.Spec.TLS[0].Hosts = tlsHttps[0:1]
		saveBean.Spec.TLS[0].SecretName = requestDto.SecretName
	}
	logs.Info(utils.TStructToJson(saveBean))
	nameSpace := saveBean.NameSpace
	operateType := saveBean.OperateType
	ingressOptions := v1beta1.Ingress{}
	// 复制字段
	utils.StructCopy(&ingressOptions, &saveBean)
	ingressOptions.CreationTimestamp.Time = time.Now()

	infoLogger.Println("执行校验保存或更新负载均衡请求参数")
	// 校验请求参数
	if err := models.CheckIngressContent(lang, nameSpace, operateType, ingressOptions); err != nil {
		errorLogger.Printf("校验保存或更新负载均衡请求参数失败: %s", err.Error())
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("校验保存或更新负载均衡请求参数成功")
	err := models.SaveAndupdateIngress(lang, nameSpace, operateType, ingressOptions)
	if err != nil {
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	u.Data["json"] = responseDto
	u.ServeJSON()
}

/**
  七层负载 -- 根据ingressName 编辑接口
*/
// @router /getIngressDetailToGui [post]
func (u *IngressController) GetIngressDetailToGui() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.EditIngressByNameRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("编辑负载均衡请求参数: ", requestDto)
	ingressDetailByGui, e := models.GetIngressDetailToGui(requestDto.IngressName, requestDto.NameSpace)
	if e != nil {
		errorResponseDto.Message = e.Error()
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	successResponseDto.Result = ingressDetailByGui
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  七层负载 -- 根据ingressName修改
*/
// @router /upgradeIngressToGui [post]
func (u *IngressController) UpgradeIngressToGui() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.AddIngressByGuiRequestDto
	var responseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	// 查询 ingress 是否存在
	_, err := models.GetIngressDetailByName(requestDto.Name, requestDto.Namespace)
	if err != nil {
		errorLogger.Println(err.Error())
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("图形化修改负载均衡请求参数: ", requestDto)
	saveBean := ingress.SaveAndupdateIngressContentRequestDto{}
	saveBean.Name = requestDto.Name
	saveBean.NameSpace = requestDto.Namespace
	saveBean.OperateType = "update"
	saveBean.Annotations = requestDto.Annotations
	saveBean.Namespace = requestDto.Namespace
	saveBean.Kind = "Ingress"
	saveBean.APIVersion = "extensions/v1beta1"
	len := len(requestDto.Rules)
	//var ruls [len]v1beta1.IngressRule
	saveBean.Spec.Rules = make([]v1beta1.IngressRule, len)
	// tls
	tlsHttps := []string{}
	//saveBean.Spec.Rules
	for i := 0; i < len; i++ {
		tlsHttps = append(tlsHttps, requestDto.Rules[i].Host)
		saveBean.Spec.Rules[i].Host = requestDto.Rules[i].Host
		if saveBean.Spec.Rules[i].HTTP == nil {
			saveBean.Spec.Rules[i].HTTP = &v1beta1.HTTPIngressRuleValue{}
		}
		if saveBean.Spec.Rules[i].HTTP.Paths == nil {
			saveBean.Spec.Rules[i].HTTP.Paths = make([]v1beta1.HTTPIngressPath, 1)
		}
		saveBean.Spec.Rules[i].HTTP.Paths[0].Path = requestDto.Rules[i].Path
		saveBean.Spec.Rules[i].HTTP.Paths[0].Backend.ServiceName = requestDto.Rules[i].ServiceName
		servicePort := intstr.IntOrString{}
		if strings.Contains(requestDto.Rules[i].ServicePort, "(") {
			// 格式为：http(8080)  存在name值，不用port值
			index := strings.Index(requestDto.Rules[i].ServicePort, "(")
			str := requestDto.Rules[i].ServicePort[0:index]
			logs.Info("servicePort:", str)
			servicePort.Type = intstr.String
			servicePort.StrVal = str
		} else {
			if utils.IsNumber(requestDto.Rules[i].ServicePort) {
				port, _ := strconv.Atoi(requestDto.Rules[i].ServicePort)
				logs.Info("servicePort:", port)
				servicePort.Type = intstr.Int
				servicePort.IntVal = int32(port)
			} else {
				responseDto.Message = utils.GetI18nLang(lang, "fail")
				u.Data["json"] = responseDto
				u.ServeJSON()
				return
			}
		}
		saveBean.Spec.Rules[i].HTTP.Paths[0].Backend.ServicePort = servicePort
	}
	if requestDto.IsHttps {
		//支持https
		if saveBean.Spec.TLS == nil {
			saveBean.Spec.TLS = make([]v1beta1.IngressTLS, 1)
		}
		saveBean.Spec.TLS[0].Hosts = tlsHttps[0:1]
		saveBean.Spec.TLS[0].SecretName = requestDto.SecretName
	}
	logs.Info(utils.TStructToJson(saveBean))
	nameSpace := saveBean.NameSpace
	operateType := saveBean.OperateType
	ingressOptions := v1beta1.Ingress{}
	// 复制字段
	utils.StructCopy(&ingressOptions, &saveBean)
	ingressOptions.CreationTimestamp.Time = time.Now()

	infoLogger.Println("执行校验保存或更新负载均衡请求参数")
	// 校验请求参数
	if err := models.CheckIngressContent(lang, nameSpace, operateType, ingressOptions); err != nil {
		errorLogger.Printf("校验保存或更新负载均衡请求参数失败: %s", err.Error())
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("校验保存或更新负载均衡请求参数成功")
	err = models.SaveAndupdateIngress(lang, nameSpace, operateType, ingressOptions)
	if err != nil {
		responseDto.Message = err.Error()
		u.Data["json"] = responseDto
		u.ServeJSON()
		return
	}
	responseDto.Status = 200
	responseDto.Message = utils.GetI18nLang(lang, "success")
	u.Data["json"] = responseDto
	u.ServeJSON()
}

/**
  四层负载： 获取tcp/udp负载 列表
*/
// @router /getTUdpIngressList [post]
func (u *IngressController) GetTUdpIngressList() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.GetTUdpIngressListRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.GetPageListBaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("查询四层负载均衡详情请求参数: ", requestDto)

	pageIndex := requestDto.PageIndex
	pageSize := requestDto.PageSize
	if pageIndex < 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexRange")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	if pageSize <= 0 {
		errorResponseDto.Message = utils.GetI18nLang(lang, "pageSizeRange")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}

	beans, err := models.GetTUdpIngressList(requestDto.ProtocalType, requestDto.Sort)
	if err != nil {
		errorLogger.Printf("查询集群四层负载ingress失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	resultList := []models.TUdpIngressBean{}
	totalRecords := len(beans)
	totalPages := 0
	if totalRecords > 0 {
		totalPages = totalRecords/pageSize + 1
		if totalRecords%pageSize == 0 {
			totalPages = totalRecords / pageSize
		}
		if totalRecords <= pageIndex*pageSize {
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			u.Data["json"] = errorResponseDto
			u.ServeJSON()
			return
		}
		resultList = beans[pageIndex*pageSize:]
		if len(beans)-pageIndex*pageSize >= pageSize {
			resultList = beans[pageIndex*pageSize : (pageIndex+1)*pageSize]
		}

	} else {
		if totalRecords < pageIndex*pageSize {
			errorResponseDto.Message = utils.GetI18nLang(lang, "pageIndexOutRange")
			u.Data["json"] = errorResponseDto
			u.ServeJSON()
			return
		}
	}
	successResponseDto.Result = resultList
	successResponseDto.PageInfo = dto.PageInfoBaseResponseDto{
		TotalRecords: totalRecords,
		TotalPages:   totalPages,
	}
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  四层负载： 获取tcp/udp负载详情
*/
// @router /getTUdpIngressDetail [post]
func (u *IngressController) GetTUdpIngressDetail() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.GetTUdpIngressDetailRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("查询四层负载请求参数: ", requestDto)
	bean, e := models.GetTUdpDetail(requestDto.ExposurePort, requestDto.ProtocalType)
	if e != nil {
		errorResponseDto.Message = e.Error()
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	successResponseDto.Result = bean
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  四层负载： 创建tcp/udp负载接口
*/
// @router /createTUdpIngress [post]
func (u *IngressController) AddTUdpIngressDetail() {
	lang := u.GetString("lang")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.AddTUdpIngressRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("创建四层负载请求参数: ", requestDto)
	err := models.AddTUdpIngress(lang, requestDto)
	if err != nil {
		errorResponseDto.Status = 300
		errorResponseDto.Message = err.Error()
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	successResponseDto.Status = 200
	successResponseDto.Message = utils.GetI18nLang(lang, "success")
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  四层负载： 修改tcp/udp负载接口
*/
// @router /updateTUdpIngress [post]
func (u *IngressController) UpdateTUdpIngress() {
	lang := u.GetString("lang", "zh")
	origExport := u.GetString("origExport")
	origProtocalType := u.GetString("origProtocalType")
	infoLogger.Println("语言: ", lang, "原暴露端口:", origExport, "原协议：", origProtocalType)
	var requestDto ingress.AddTUdpIngressRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("修改四层负载请求参数: ", requestDto)
	err := models.UpdateTUdpIngress(lang, origExport, origProtocalType, requestDto)
	if err != nil {
		errorResponseDto.Status = 300
		errorResponseDto.Message = utils.GetI18nLang(lang, "fail")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	successResponseDto.Status = 200
	successResponseDto.Message = utils.GetI18nLang(lang, "success")
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  四层负载： 删除tcp/udp负载接口
*/
// @router /deleteTUdpIngress [post]
func (u *IngressController) DeleteTUdpIngress() {
	lang := u.GetString("lang", "zh")
	infoLogger.Println("语言: ", lang)
	var requestDto ingress.GetTUdpIngressDetailRequestDto
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResponseDto{}
	successResponseDto.Status = 200
	if err := json.Unmarshal(u.Ctx.Input.RequestBody, &requestDto); err != nil {
		errorLogger.Println(err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	infoLogger.Println("删除四层负载请求参数: ", requestDto)
	err := models.DeleteTUdpIngress(lang, requestDto.ExposurePort, requestDto.ProtocalType)
	if err != nil {
		errorResponseDto.Status = 300
		errorResponseDto.Message = utils.GetI18nLang(lang, "fail")
		u.Data["json"] = errorResponseDto
		u.ServeJSON()
		return
	}
	successResponseDto.Status = 200
	successResponseDto.Message = utils.GetI18nLang(lang, "success")
	u.Data["json"] = successResponseDto
	u.ServeJSON()
}

/**
  获取tls 名称列表
*/
// @router /getTlsNames [get]
func (u *IngressController) GetTlsNames() {
	ns := u.GetString("namespace")
	infoLogger.Println("名称空间: ", ns)
	var respResult = dto.BaseResultResponseDto{300, utils.GetI18nLang("zh", "sysError")}
	infoLogger.Println("查询tls名称列表 请求参数: ", ns)

	tlsNames, e := models.GetTlsNames(ns)
	if e != nil {
		respResult.Status = 300
		respResult.Result = tlsNames
		u.Data["json"] = respResult
		u.ServeJSON()
		return
	}
	respResult.Status = 200
	respResult.Result = tlsNames
	u.Data["json"] = respResult
	u.ServeJSON()
}
