package models

import (
	"errors"
	"github.com/astaxie/beego/logs"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"k8s-console/utils"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"strings"
)

type ClusterInfoBean struct {
	TenantId           string `json:"tenantId"`
	EnvId              string `json:"envId"`
	HarborAddress      string `json:"harborAddress"`
	HarborPwd          string `json:"harborPwd"`
	AppExtensiveDomain string `json:"appExtensiveDomain"`
	Type               string `json:"type"`
}

/**
  获取租户环境id
*/
func GetTenantEnvIdByKubeConfig() (string, string, error) {
	var tenantId = ""
	var envId = ""
	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		return "", "", errors.New("连接k8s集群失败")
	}
	cm, err := k8sClient.CoreV1().ConfigMaps("default").Get("appclient-configmap", v1.GetOptions{})
	if err != nil {
		return "", "", errors.New("获取租户环境失败")
	}
	dataMap := cm.Data
	if dataMap != nil && len(dataMap) > 0 {
		tenantId = dataMap["tenantId"]
		envId = dataMap["envId"]
	}
	return tenantId, envId, nil
}

/**
  获取harbor密码
*/
func GetHarborPwd(nameSpace string, isEncryptedHarborPwd bool) (string, error) {
	var harborPwd = ""
	var err error = nil
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		err = errors.New("连接k8s集群失败")
	} else {
		secretBean, e := k8sClient.CoreV1().Secrets(nameSpace).Get("harbor-core", v1.GetOptions{})
		if e != nil {
			err = errors.New("获取harbor密码失败")
		} else {
			dataMap := secretBean.Data
			if len(dataMap) > 0 {
				harborPwdBytes := dataMap["HARBOR_ADMIN_PASSWORD"]
				harborPwd = string(harborPwdBytes[:])
			}
		}
	}

	// 如果需要加密 则执行des的CBC加密
	if isEncryptedHarborPwd {
		harborPwd, err = utils.EncryptDES_CBC(harborPwd)
	}
	return harborPwd, err
}

/**
  获取harbor
*/
func GetHarborIngressAndPwd(nameSpace string, isEncryptedHarborPwd bool) (string, string, string, error) {
	var harborAddress = ""
	var harborPwd = ""
	var appExtensiveDomain = ""
	ingressDetailBean, e := GetIngressDetailByName("harbor-ingress", nameSpace)
	if e != nil {
		return harborAddress, harborPwd, appExtensiveDomain, e
	}
	beans := ingressDetailBean.Rules
	if len(beans) >= 1 {
		harborHost := beans[0].Host
		harborAddress = "https://" + harborHost
		appExtensiveDomain = harborHost[7:]
	}
	pwd, e := GetHarborPwd(nameSpace, isEncryptedHarborPwd)
	if e != nil {
		return harborAddress, harborPwd, appExtensiveDomain, e
	}
	harborPwd = pwd
	return harborAddress, harborPwd, appExtensiveDomain, nil
}

func GetClusterConfigInfoData(nameSpace string) (ClusterInfoBean, error) {
	bean := ClusterInfoBean{}
	var err error
	tenantId, envId, e := GetTenantEnvIdByKubeConfig()
	bean.TenantId = tenantId
	bean.EnvId = envId
	if e != nil {
		err = e
	}
	harborAddress, harborPwd, appExtensiveDomain, err := GetHarborIngressAndPwd(nameSpace, true)
	bean.HarborAddress = harborAddress
	bean.HarborPwd = harborPwd
	bean.AppExtensiveDomain = appExtensiveDomain
	if err != nil {
		err = err
	}
	if strings.Contains(appExtensiveDomain, "test") {
		bean.Type = "test"
	} else if strings.Contains(appExtensiveDomain, "dev") {
		bean.Type = "dev"
	} else if strings.Contains(appExtensiveDomain, "k2software") {
		bean.Type = "prod"
	}
	return bean, err
}

func GetKindTemplateInfo(kindType string) (map[interface{}]interface{}, error) {

	data := make(map[interface{}]interface{})
	filePath := utils.GetCurrentPath() + "/file"
	if kindType == "ingress" {
		filePath = filePath + "/ingressTemplate.yaml"
	} else if kindType == "service" {
		filePath = filePath + "/serviceTemplate.yaml"
	} else if kindType == "deploy" {
		filePath = filePath + "/deployTemplate.yaml"
	} else if kindType == "sc" {
		filePath = filePath + "/storageClassTemplate.yaml"
	} else if kindType == "pv" {
		filePath = filePath + "/pvTemplate.yaml"
	} else if kindType == "pvc" {
		filePath = filePath + "/pvcTemplate.yaml"
	}
	bytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		logs.Error("解析模板文件失败", err.Error())
		return nil, err
	}
	err = yaml.Unmarshal(bytes, &data)
	if err != nil {
		logs.Error("解析模板文件转换成map对象失败", err.Error())
		return nil, err
	}
	return data, nil
}
