package system

import (
	"encoding/json"
	"fmt"
	"log-server/global"
	"log-server/service/log"
	"log-server/service/task"
	"log-server/utils"
	"strconv"
	"time"
)

type RobotService struct{}

type SendMsg struct {
	MsgType  string `json:"msgtype"`
	Markdown struct {
		Content string `json:"content"`
	} `json:"markdown"`
}

func (robotService *RobotService) PostRobotToEnterpriseWeChatByMarkdown(url string, content string) (result []byte, err error) {
	var sendMsg SendMsg
	sendMsg.MsgType = "markdown"
	sendMsg.Markdown.Content = content
	result, err = utils.HttpPost(url, sendMsg)
	return
}

// SyncJfDevicesMessage 定时同步机房设备信息
func (robotService *RobotService) SyncJfDevicesMessage() {
	//机房现在就开了第15架和第16架设备
	//rackArr := []int{15, 16}
	rackArr := map[int]float64{
		//设备架号：该架正常率标准值
		15: 0.6,
		16: 0.6,
	}
	content := ">#### **机房设备预警** (" + time.Now().Format("2006-01-02 15:04:05") + ")：\n"
	var keyWord string
	for rack, abnormalRate := range rackArr {
		result, err := robotService.RequestJfDevicesState(rack)
		if err != nil {
			global.GVA_LOG.Error("获取机房设备信息失败，设备可能断电，请注意排查！！！")
			keyWord = "获取机房设备信息失败，设备可能断电，请注意排查！！！,错误信息：" + err.Error()
			break
		}
		if string(result) != "null" {
			var data [][]int
			err := json.Unmarshal(result, &data)
			if err != nil {
				return
			}
			NumTotal := len(data)
			NumGood := 0
			for _, v := range data {
				if v[2] == 3 {
					NumGood += 1
				}
			}
			//global.GVA_LOG.Info(strconv.Itoa(NumTotal))
			//global.GVA_LOG.Info(strconv.Itoa(NumGood))numIntoGame * numStartGame / 1e6
			rate := float64(NumGood) / float64(NumTotal)

			if rate < abnormalRate {
				keyWord += "\n 机房第" + strconv.Itoa(rack) + "架设备正常率为：" + strconv.FormatFloat(rate, 'f', 2, 64) + ",设备正常率低，建议维护重启 \n"
			}
			//global.GVA_LOG.Info(keyWord)
		}
	}
	if keyWord != "" {
		content += keyWord
		url := global.GVA_CONFIG.SendUrl.KeyWordSendUrl
		_, _ = robotService.PostRobotToEnterpriseWeChatByMarkdown(url, content)
	}
	return
}

// SyncJfXmyNewAccount 定时获取机房小绵羊新号剩余
func (robotService *RobotService) SyncJfXmyNewAccount() {
	content := ">#### **【账号提醒】预警**  (" + time.Now().Format("2006-01-02 15:04:05") + ")：\n"
	var keyWord string
	result, err := robotService.RequestJfXmyNewAccount()
	if err != nil {
		global.GVA_LOG.Error("定时获取机房小绵羊新号剩余失败！！！")
		keyWord = "定时获取机房小绵羊新号剩余失败！！！,错误信息：" + err.Error()
		return
	}
	//global.GVA_LOG.Info(string(result))
	accountNum, err := strconv.ParseInt(string(result), 10, 64)
	if err != nil {
		global.GVA_LOG.Error("定时获取机房小绵羊新号剩余失败2！！！")
		keyWord = "定时获取机房小绵羊新号剩余失败2！！！,错误信息：" + err.Error()
		return
	}
	if string(result) != "null" && string(result) != "" {
		if accountNum <= 1000 {
			keyWord += "机房小绵羊新号不足,请及时添加,当前剩余:" + string(result) + " \n"
			//keyWord += "机房小绵羊新号当前剩余:" + string(result) + " \n"
		}
	}
	if keyWord != "" {
		content += keyWord
		url := global.GVA_CONFIG.SendUrl.KeyWordSendUrl
		_, _ = robotService.PostRobotToEnterpriseWeChatByMarkdown(url, content)
	}
	return
}

// RequestJfDevicesState 获取机房设备信息
func (robotService *RobotService) RequestJfDevicesState(rack int) (result []byte, err error) {
	jfUrl := "http://182.150.53.148:6007/v1/manage/chart"
	jfParams := map[string]string{
		"Rack": strconv.Itoa(rack),
	}
	result, err = utils.HttpGet(jfUrl, jfParams)
	return
}

// RequestJfXmyNewAccount 获取机房小绵羊新号剩余
func (robotService *RobotService) RequestJfXmyNewAccount() (result []byte, err error) {
	jfUrl := "http://xjf.lianyou.fun:8099/v1/account/get_left_smallsheep_account"
	jfParams := map[string]string{}
	result, err = utils.HttpGet(jfUrl, jfParams)
	return
}

// SyncIPMessage 定时判断ip
func (robotService *RobotService) SyncIPMessage() {

	//if keyWord != "" {
	//	content += keyWord
	//	url := global.GVA_CONFIG.SendUrl.KeyWordSendUrl
	//	_, _ = robotService.PostRobotToEnterpriseWeChatByMarkdown(url, content)
	//}
	fmt.Println("ip定时任务")
	msg := "# IP异常播报 \n "
	personMsg := "# IP异常播报 \n "
	var syncData task.SyncData
	var ipService log.ServiceIpLog
	abnormalIpList, _ := ipService.GetAbnormalIp()
	if len(abnormalIpList) == 0 {
		return
	}
	var mobile []string
	mpsPerson, _ := syncData.Person.GetUserInfoData()
	personMsgData := make(map[string]string, len(mpsPerson))
	//fmt.Println(mpsPerson)
	for k, _ := range abnormalIpList {
		mobile = append(mobile, mpsPerson[k].MobilePhoneNumber)
		msg += "# " + k + " " + "\n"
		msg += fmt.Sprintf("<font color=\"warning\">%s</font>", abnormalIpList[k]) + "\n"
		personMsgData[k] += fmt.Sprintf("<font color=\"warning\">%s</font>", abnormalIpList[k]) + "\n"
	}
	url := global.GVA_CONFIG.SendUrl.ComputerSendUrl
	var sendData SendMsg
	sendData.MsgType = "markdown"
	sendData.Markdown.Content = msg
	syncData.SendMsgData(url, sendData)

	if len(mobile) != 0 {
		var sendTextData task.SendTextMsg
		sendTextData.MsgType = "text"
		sendTextData.Text.MentionedMobileList = mobile
		//fmt.Println(mobile)
		//b ,_ := json.Marshal(sendTextData)
		//global.GVA_LOG.Warn(string(b))
		syncData.SendMsgData(url, sendTextData)
	}
	for person, personData := range personMsgData {
		var sendPersonData SendMsg
		sendPersonMsg := personMsg + personData
		sendPersonData.MsgType = "markdown"
		sendPersonData.Markdown.Content = sendPersonMsg
		syncData.SendMsgData(mpsPerson[person].Url, sendPersonData)
	}
	return
}
