package service

import (
	"fmt"
	"testing"
	"time"

	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/load"
	"github.com/shirou/gopsutil/v3/mem"
	"github.com/shirou/gopsutil/v3/net"
)

func init() {

}

func TestInfo(t *testing.T) {
	s := MonitorInfo{}
	s.load(0.5) // 0.5 半分钟

	fmt.Println(s)
	select {}
}

// MonitorInfo 机器资源信息
type MonitorInfo struct {
	MonitorBase    MonitorBase      `json:"base"`    // 监控_基本信息
	MonitorIO      []MonitorIO      `json:"io"`      // 监控_磁盘IO
	MonitorNetwork []MonitorNetwork `json:"network"` // 监控_网络IO
}

// load 执行资源获取
func (m *MonitorInfo) load(interval float64) {
	var itemBase MonitorBase
	itemBase.CreateTime = time.Now().UnixMilli()

	totalPercent, _ := cpu.Percent(3*time.Second, false)
	if len(totalPercent) == 1 {
		itemBase.CPU = totalPercent[0]
	}
	cpuCount, _ := cpu.Counts(false)

	loadInfo, _ := load.Avg()
	itemBase.CPULoad1 = loadInfo.Load1
	itemBase.CPULoad5 = loadInfo.Load5
	itemBase.CPULoad15 = loadInfo.Load15
	itemBase.LoadUsage = loadInfo.Load1 / (float64(cpuCount*2) * 0.75) * 100

	memoryInfo, _ := mem.VirtualMemory()
	itemBase.Memory = memoryInfo.UsedPercent

	m.MonitorBase = itemBase

	// 求平均
	m.MonitorIO = loadDiskIO(interval)
	m.MonitorNetwork = loadNetIO(interval)
}

// MonitorBase 监控_基本信息 monitor_base
type MonitorBase struct {
	CreateTime int64   `json:"createTime"` // 创建时间
	CPU        float64 `json:"cpu"`        // cpu使用率
	LoadUsage  float64 `json:"loadUsage"`  // cpu平均使用率
	CPULoad1   float64 `json:"cpuLoad1"`   // cpu使用1分钟
	CPULoad5   float64 `json:"cpuLoad5"`   // cpu使用5分钟
	CPULoad15  float64 `json:"cpuLoad15"`  // cpu使用15分钟
	Memory     float64 `json:"memory"`     // 内存使用率
}

// MonitorIO 监控_磁盘IO monitor_io
type MonitorIO struct {
	CreateTime int64  `json:"createTime"` // 创建时间
	Name       string `json:"name"`       // 磁盘名
	Read       int64  `json:"read"`       // 读取K
	Write      int64  `json:"write"`      // 写入K
	Count      int64  `json:"count"`      // 次数
	Time       int64  `json:"time"`       // 耗时
}

// MonitorNetwork 监控_网络IO monitor_network
type MonitorNetwork struct {
	CreateTime int64   `json:"createTime"` // 创建时间
	Name       string  `json:"name"`       // 网卡名
	Up         float64 `json:"up"`         // 上行
	Down       float64 `json:"down"`       // 下行
}

// loadDiskIO 磁盘读写，interval表示采集的平均值（分钟）
func loadDiskIO(interval float64) []MonitorIO {
	ioStat, _ := disk.IOCounters()

	time.Sleep(time.Duration(interval) * time.Minute)

	ioStat2, _ := disk.IOCounters()
	var ioList []MonitorIO
	timeMilli := time.Now().UnixMilli()
	for _, io2 := range ioStat2 {
		for _, io1 := range ioStat {
			if io2.Name == io1.Name {
				var itemIO MonitorIO
				itemIO.CreateTime = timeMilli
				itemIO.Name = io1.Name

				if io2.ReadBytes != 0 && io1.ReadBytes != 0 && io2.ReadBytes > io1.ReadBytes {
					itemIO.Read = int64(float64(io2.ReadBytes-io1.ReadBytes) / interval / 60)
				}
				if io2.WriteBytes != 0 && io1.WriteBytes != 0 && io2.WriteBytes > io1.WriteBytes {
					itemIO.Write = int64(float64(io2.WriteBytes-io1.WriteBytes) / interval / 60)
				}

				if io2.ReadCount != 0 && io1.ReadCount != 0 && io2.ReadCount > io1.ReadCount {
					itemIO.Count = int64(float64(io2.ReadCount-io1.ReadCount) / interval / 60)
				}
				writeCount := int64(0)
				if io2.WriteCount != 0 && io1.WriteCount != 0 && io2.WriteCount > io1.WriteCount {
					writeCount = int64(float64(io2.WriteCount-io1.WriteCount) / interval * 60)
				}
				if writeCount > itemIO.Count {
					itemIO.Count = writeCount
				}

				if io2.ReadTime != 0 && io1.ReadTime != 0 && io2.ReadTime > io1.ReadTime {
					itemIO.Time = int64(float64(io2.ReadTime-io1.ReadTime) / interval / 60)
				}
				writeTime := int64(0)
				if io2.WriteTime != 0 && io1.WriteTime != 0 && io2.WriteTime > io1.WriteTime {
					writeTime = int64(float64(io2.WriteTime-io1.WriteTime) / interval / 60)
				}
				if writeTime > itemIO.Time {
					itemIO.Time = writeTime
				}
				ioList = append(ioList, itemIO)
				break
			}
		}
	}
	return ioList
}

// loadNetIO 网络接口（包括虚拟接口），interval表示采集的平均值（分钟）
func loadNetIO(interval float64) []MonitorNetwork {
	// 获取当前时刻
	netStat, _ := net.IOCounters(true)
	netStatAll, _ := net.IOCounters(false)
	var netStatList []net.IOCountersStat
	netStatList = append(netStatList, netStat...)
	netStatList = append(netStatList, netStatAll...)

	time.Sleep(time.Duration(interval) * time.Minute)

	// 获取结束时刻
	netStat2, _ := net.IOCounters(true)
	netStat2All, _ := net.IOCounters(false)
	var netStat2List []net.IOCountersStat
	netStat2List = append(netStat2List, netStat2...)
	netStat2List = append(netStat2List, netStat2All...)

	var netList []MonitorNetwork
	timeMilli := time.Now().UnixMilli()
	for _, net2 := range netStat2List {
		for _, net1 := range netStatList {
			if net2.Name == net1.Name {
				var itemNet MonitorNetwork
				itemNet.CreateTime = timeMilli
				itemNet.Name = net1.Name

				// 如果结束时刻发送字节数和当前时刻发送字节数都不为零，并且结束时刻发送字节数大于当前时刻发送字节数
				if net2.BytesSent != 0 && net1.BytesSent != 0 && net2.BytesSent > net1.BytesSent {
					itemNet.Up = float64(net2.BytesSent-net1.BytesSent) / 1024 / interval / 60
				}
				if net2.BytesRecv != 0 && net1.BytesRecv != 0 && net2.BytesRecv > net1.BytesRecv {
					itemNet.Down = float64(net2.BytesRecv-net1.BytesRecv) / 1024 / interval / 60
				}
				netList = append(netList, itemNet)
				break
			}
		}
	}

	return netList
}
