package fileManager

import (
	"errors"
	"fmt"
	"github.com/bitly/go-simplejson"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"log-server/global"
	"log-server/model/fileManager"
	"log-server/model/task"
	"log-server/service/system"
	"log-server/utils"
	"strconv"
	"strings"
	"time"
)

type ServiceDownLoadUrl struct {
}

var robotService = new(system.RobotService)

// UpdateGameVersion 定时更新游戏版本号和链接
func (s *ServiceDownLoadUrl) UpdateGameVersion() {
	nowTime := time.Now().Format("2006-01-02 15:04:05")
	taskList, err := s.GetAllTaskByRun()
	if err != nil {
		global.GVA_LOG.Error("定时更新游戏版本号和链接执行失败,查询所有在运行的任务失败:"+nowTime, zap.Error(err))
		return
	}
	content := ""
	var directorName string
	for _, v := range taskList {
		global.GVA_LOG.Info(v.GameIdXmy + v.TaskName)
		if v.GameIdXmy == "" {
			continue
		}
		result, err := s.GetGameDownLoadUrlAndVersion(v.GameIdXmy)
		if err != nil {
			return
		}
		dataJson, _ := simplejson.NewJson(result)
		code, _ := dataJson.Get("code").Int()
		//global.GVA_LOG.Info(strconv.Itoa(code))
		//msg, _ := dataJson.Get("msg").String()
		//global.GVA_LOG.Info(msg)
		if code != 0 {
			continue
		}
		packageUrl, _ := dataJson.Get("data").Get("package").Get("download_url").String()
		//global.GVA_LOG.Info(packageUrl)
		packageVersionCode, _ := dataJson.Get("data").Get("package").Get("version_code").Int()
		//global.GVA_LOG.Info(strconv.Itoa(packageVersionCode))

		appUrl, _ := dataJson.Get("data").Get("app").Get("download_url").String()
		//global.GVA_LOG.Info(appUrl)
		appVersionName, _ := dataJson.Get("data").Get("app").Get("version_name").String()
		//global.GVA_LOG.Info(appVersionName)
		appFlag, _ := dataJson.Get("data").Get("app").Get("flag").Int()
		//global.GVA_LOG.Info(strconv.Itoa(appFlag))

		one := new(fileManager.DownLoadUrl)
		one.PackageUrl = packageUrl
		one.PackageVersionCode = packageVersionCode
		one.AppUrl = appUrl
		one.AppVersionName = appVersionName
		one.AppFlag = appFlag
		one.TaskId = v.TaskId
		one.CreateTime = time.Now().Format("2006-01-02 15:04:05")
		one.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
		//先查询是否存在，存在则对比版本号与链接；不存在则插入
		old := fileManager.DownLoadUrl{}
		var keyWord string
		if !errors.Is(global.GVA_DB.Model(&fileManager.DownLoadUrl{}).Where("task_id = ?", v.TaskId).First(&old).Error, gorm.ErrRecordNotFound) {
			flagPackage := false
			if one.PackageVersionCode > old.PackageVersionCode {
				flagPackage = true
				//global.GVA_LOG.Info("package有新版本")
				if one.PackageUrl != "" {
					keyWord += "在打包平台有新版本: " + one.PackageUrl + ";<font color=\"warning\">更新大概率为强制更新</font>;"
					//keyWord += "在打包平台有新版本: [点击下载](" + one.PackageUrl + ");"
				}
			}
			flagApp := false
			sv1 := s.StrsToSlice(one.AppVersionName)
			sv2 := s.StrsToSlice(old.AppVersionName)
			s1Appended, s2Appended := s.ApeendZreo(sv1, sv2)
			for i := 0; i < len(s1Appended); i++ {
				if s1Appended[i] > s2Appended[i] {
					flagApp = true
					//global.GVA_LOG.Info("app有新版本")
					if one.AppUrl != "" {
						keyWord += "在小绵羊APP有新版本: " + one.AppUrl + ";"
						if one.AppFlag == 1 {
							global.GVA_LOG.Info("游戏有强更")
							keyWord += "<font color=\"warning\">更新可能为强制更新</font>;"
						}
					}
					break
				}
			}
			if flagPackage == true || flagApp == true {
				err = global.GVA_DB.Model(&fileManager.DownLoadUrl{}).Where("task_id = ?", v.TaskId).Updates(one).Error
			}
			if err != nil {
				global.GVA_LOG.Error("定时更新游戏版本号和链接执行失败,执行数据库操作失败:"+nowTime, zap.Error(err))
				return
			}
			//播报内容
			if keyWord != "" {
				if directorName != v.User {
					content += ">#### **" + v.User + "**\n " + strconv.Itoa(v.TaskId) + " " + v.TaskName + keyWord + "\n"
				} else {
					content += strconv.Itoa(v.TaskId) + " " + v.TaskName + keyWord + "\n"
				}
				directorName = v.User
			}
		} else {
			err = global.GVA_DB.Create(&one).Error
		}
		if err != nil {
			global.GVA_LOG.Error("定时更新游戏版本号和链接执行失败,执行数据库操作失败:"+nowTime, zap.Error(err))
			return
		}
	}
	if content != "" {
		content = ">#### **【游戏更新】预警** (" + nowTime + ")：\n" + content
		//global.GVA_LOG.Info(content)
		url := global.GVA_CONFIG.SendUrl.ComputerSendUrl
		_, _ = robotService.PostRobotToEnterpriseWeChatByMarkdown(url, content)
		url2 := global.GVA_CONFIG.SendUrl.KeyWordSendUrl
		_, _ = robotService.PostRobotToEnterpriseWeChatByMarkdown(url2, content)
	}
}

// GetAllTaskByRun 查询所有在运行的任务
func (s *ServiceDownLoadUrl) GetAllTaskByRun() (list []task.GameTask, err error) {
	var taskList []task.GameTask
	db := global.GVA_DB.Model(&task.GameTask{})
	db.Where("status = 1")
	err = db.Order("user").Find(&taskList).Error
	return taskList, err
}

// GetGameDownLoadUrlAndVersion 获取游戏版本和下载链接
func (s *ServiceDownLoadUrl) GetGameDownLoadUrlAndVersion(xmyId string) (result []byte, err error) {
	url := "http://rtd.kfzs.com/get_version.php"
	params := map[string]string{
		"game_id": xmyId,
	}
	result, err = utils.HttpGet(url, params)
	return
}

// ApeendZreo 补全切片
func (s *ServiceDownLoadUrl) ApeendZreo(s1, s2 []string) ([]string, []string) {
	var count int
	if len(s1) > len(s2) {
		count = len(s1) - len(s2)
		for i := 0; i < count; i++ {
			s2 = append(s2, "0")
		}
	}
	if len(s1) < len(s2) {
		count = len(s2) - len(s1)
		for i := 0; i < count; i++ {
			s1 = append(s1, "0")
		}
	}

	return s1, s2
}

func (s *ServiceDownLoadUrl) StrsToSlice(version string) []string {
	return strings.Split(version, ".")
}

func (s *ServiceDownLoadUrl) StrToInt64(str string) int64 {
	res, err := strconv.Atoi(str)
	if err != nil {
		fmt.Println("Invalid Number string")
		return -1
	}
	return int64(res)
}
