package api

import (
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"main/database"
	"main/model"
	"main/utils"
	"strconv"
	"strings"
)

func getSystem(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	date := ctx.URLParam("date")
	//username := "admin"
	db := database.GetInstance().GetMysqlDb()
	var systemList []resSystem
	var ids []int
	if err := db.Model(&model.SysInfo{}).Select("max(id)").Where("date = ? and username = ?", date, username.Username).Group("ip").Scan(&ids).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if err := db.Model(&model.SysInfo{}).Where("id in (?)", ids).Find(&systemList).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", systemList))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 获取当前系统信息
func getSysInfo(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	//username := "admin"
	date := ctx.URLParam("date")
	ip := ctx.URLParam("ip")
	db := database.GetInstance().GetMysqlDb()
	var sysInfoList []model.SysInfo
	var res []resSysInfo
	if err := db.Where("username = ? and date = ? and ip = ?", username.Username, date, ip).Find(&sysInfoList).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	for _, sysInfo := range sysInfoList {
		var diskList []resDisk
		diskLists := strings.Split(sysInfo.DiskPoint, ",")
		for i, disk := range diskLists {
			if strings.Contains(disk, "docker") {
				continue
			}
			diskPer, err := strconv.ParseFloat(strings.Split(sysInfo.DiskPer, ",")[i], 64)
			if utils.ErrHandle(ctx, err) {
				return
			}
			diskList = append(diskList, resDisk{
				Point: disk,
				Total: strings.Split(sysInfo.DiskTotal, ",")[i],
				Used:  strings.Split(sysInfo.DiskUsed, ",")[i],
				Per:   utils.Round(diskPer, 2),
			})
		}
		res = append(res, resSysInfo{
			Datetime: sysInfo.Datetime,
			CpuPer:   utils.Round(sysInfo.CpuPer, 2),
			Mem: resMem{
				MemPer:   utils.Round(sysInfo.MemPer, 2),
				MemUsed:  sysInfo.MemUsed,
				MemTotal: sysInfo.MemTotal,
			},
			Disk: diskList,
			Net: resNet{
				Sent: sysInfo.SentSpeed,
				Rec:  sysInfo.RecSpeed,
			},
		})
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

//func updateSysInfo(ctx iris.Context) {
//	date := ctx.URLParam("date")
//	crontab.UpdateSysInfo(date)
//	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", fmt.Sprintf("%s 日期数据同步完成", date)))
//	if utils.ErrHandle(ctx, err) {
//		return
//	}
//}
