package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/gorilla/websocket"
	"k8s-console/dto"
	"k8s-console/models"
	"k8s-console/utils"
	"log"
	"net/http"
	"strconv"
	"strings"
)

var WebSocketClientMap = make(map[string]*websocket.Conn)

type DashBoardController struct {
	beego.Controller
}

var upgrader = websocket.Upgrader{
	// 解决跨域问题
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func (c *DashBoardController) GetBoardAllData() {
	browserId := c.Ctx.Input.Param(":browserId")
	ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		logs.Info(err.Error())
	}

	//保存客户端标识
	WebSocketClientMap[browserId] = ws
	log.Println("仪表盘页面 websocket 连接成功...")
	log.Println("websocket的个数：" + strconv.Itoa(len(WebSocketClientMap)))
	defer ws.Close()
	for {
		_, message, err := ws.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		if len(message) > 0 {
			var requestMsg dto.DashBoardRequestDto
			if err := json.Unmarshal(message, &requestMsg); err != nil {
				panic("解析仪表盘请求参数失败！")
			}
			log.Println("仪表盘请求参数:", string(message))

			if 1 == requestMsg.Type {
				requestMsg.BrowserId = browserId
				//处理应用安装信息
				go OprBoardFun(requestMsg)
				//log.Println("页面websocket通讯信息：" + utils.TStructToJson(requestMsg))
			} else if 2 == requestMsg.Type {
				var pingResutlt = dto.BaseResultResponseDto{}
				pingResutlt.Status = 100
				pingResutlt.Result = "ping"
				WebSocketClientMap[browserId].WriteJSON(pingResutlt)
			}
		}
	}
}

func OprBoardFun(requestDto dto.DashBoardRequestDto) {
	var lang = "zh"
	var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
	var successResponseDto = dto.BaseResultResponseDto{}
	successResponseDto.Status = 200
	logs.Info("仪表盘请求接口参数：", utils.TStructToJson(requestDto))
	nameSpace := requestDto.NameSpace
	if strings.TrimSpace(nameSpace) == "" {
		errorLogger.Println("命名空间不能为空")
		errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
		WebSocketClientMap[requestDto.BrowserId].WriteJSON(errorResponseDto)
		return
	}
	//查询集群所有命名空间信息
	allNameSpaceList, err := utils.GetClusterAllNameSpaces(lang)
	infoLogger.Println(allNameSpaceList)
	if err != nil {
		errorLogger.Printf("查询集群所有命名空间失败: %s", err.Error())
		errorResponseDto.Message = utils.GetI18nLang(lang, "getClusterAllNamespacesFail")
		WebSocketClientMap[requestDto.BrowserId].WriteJSON(errorResponseDto)
		return
	}
	if len(allNameSpaceList) > 0 && !utils.IsContains(allNameSpaceList, nameSpace) {
		errorLogger.Println("集群不存在此命名空间")
		errorResponseDto.Message = utils.GetI18nLang(lang, "theNameSpaceNotExistInCluster")
		WebSocketClientMap[requestDto.BrowserId].WriteJSON(errorResponseDto)
		return
	}
	detailData, err := models.GetBoardDetailData(requestDto)
	if err != nil {
		log.Print("仪表盘失败原因：", err.Error())
		if detailData == nil {
			boardDetailBean := models.BoardDetailBean{}
			boardDetailBean.NaturalSurvey = models.NaturalSurvey{}
			boardDetailBean.AppSurvey = models.AppSurvey{}
			successResponseDto.Result = boardDetailBean
			WebSocketClientMap[requestDto.BrowserId].WriteJSON(successResponseDto)
			return
		}
	}
	successResponseDto.Result = detailData
	WebSocketClientMap[requestDto.BrowserId].WriteJSON(successResponseDto)

	//开启watch机制
	//modelIngress.WatchIngressLinster(nameSpace)

}
