package models

import (
	"crypto/tls"
	"errors"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
	"k8s-console/dto"
	"k8s-console/utils"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"time"
)

type BoardDetailBean struct {
	NaturalSurvey interface{} `json:"naturalSurvey"`
	AppSurvey     interface{} `json:"appSurvey"`
}

type NaturalSurvey struct {
	DeployNum  int `json:"deployNum"`
	PodNum     int `json:"podNum"`
	ServiceNum int `json:"serviceNum"`
	IngressNum int `ingressNum`
}
type AppSurvey struct {
	AllappNum            int `json:"allAppNum"`
	InstallAppNum        int `json:"installAppNum"`
	AvailbeUpgradeAppNum int `json:"availbeUpgradeAppNum"`
	AvailbeInstallAppNum int `json:"availbeInstallAppNum"`
}

func GetBoardDetailData(requestDto dto.DashBoardRequestDto) (*BoardDetailBean, error) {
	nameSpace := requestDto.NameSpace
	boardDetail := BoardDetailBean{}
	naturalSurvey := NaturalSurvey{}
	appSurvey := AppSurvey{}
	// 获取k8s客户端
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		return nil, errors.New("连接k8s集群失败")
	}

	//查询命名空间下所有deployment信息
	deploymentList, err := k8sClient.ExtensionsV1beta1().Deployments(nameSpace).List(v1.ListOptions{})
	if err != nil {
		return nil, errors.New("deploy dash 失败！")
	}
	if len(deploymentList.Items) >= 0 {
		naturalSurvey.DeployNum = len(deploymentList.Items)
	}

	podList, err := k8sClient.CoreV1().Pods(nameSpace).List(v1.ListOptions{})
	if err != nil {
		return nil, errors.New("pod dash 失败")
	}
	if len(podList.Items) >= 0 {
		naturalSurvey.PodNum = len(podList.Items)
	}

	serviceList, err := k8sClient.CoreV1().Services(nameSpace).List(v1.ListOptions{})
	if err != nil {
		return nil, errors.New("service dash 失败")
	}
	if len(serviceList.Items) >= 0 {
		naturalSurvey.ServiceNum = len(serviceList.Items)
	}

	ingressList, err := k8sClient.ExtensionsV1beta1().Ingresses(nameSpace).List(v1.ListOptions{})
	if err != nil {
		return nil, errors.New("ingress dash 失败")
	}
	if len(ingressList.Items) >= 0 {
		naturalSurvey.IngressNum = len(ingressList.Items)
	}
	appstore_url := beego.AppConfig.String("appstore-server-url")
	//logs.Info("应用商店服务器端地址：",appstore_url+"/api/store/getAppStatusNumber")
	request := httplib.Post(appstore_url + "/api/store/getAppStatusNumber")
	request.Header("Accept", "application/json")
	request.Header("Content-Type", "application/json")

	request.JSONBody(&requestDto)

	request.SetTimeout(5*time.Minute, 5*time.Minute)
	request.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})

	err = request.ToJSON(&appSurvey)
	if err != nil {
		return nil, errors.New("请求应用商店服务端失败:" + err.Error())
	}
	logs.Info(utils.TStructToJson(appSurvey))
	boardDetail.NaturalSurvey = naturalSurvey
	boardDetail.AppSurvey = appSurvey

	return &boardDetail, nil
}
