package service

import (
	"fmt"
	"sync"
	"testing"
	"time"

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

func TestInfo(t *testing.T) {
	s := MonitorInfo{}
	s.Load(5 * time.Second) // 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(duration time.Duration) {
	var wg sync.WaitGroup
	wg.Add(3)
	go func() {
		defer wg.Done()
		m.MonitorBase = loadCPUMem(duration)
	}()
	go func() {
		defer wg.Done()
		m.MonitorIO = loadDiskIO(duration)
	}()
	go func() {
		defer wg.Done()
		m.MonitorNetwork = loadNetIO(duration)
	}()
	wg.Wait()
}

// 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       uint64 `json:"read"`       // 读取 Bytes
	Write      uint64 `json:"write"`      // 写入 Bytes
	Count      uint64 `json:"count"`      // 次数
	Time       uint64 `json:"time"`       // 耗时
}

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

// loadCPUMem CPU内存使用率，interval表示采集的平均值（分钟）
func loadCPUMem(duration time.Duration) MonitorBase {
	var itemBase MonitorBase
	itemBase.CreateTime = time.Now().UnixMilli()

	loadInfo, _ := load.Avg()
	itemBase.CPULoad1 = loadInfo.Load1
	itemBase.CPULoad5 = loadInfo.Load5
	itemBase.CPULoad15 = loadInfo.Load15
	totalPercent, _ := cpu.Percent(duration, false)
	if len(totalPercent) > 0 {
		itemBase.CPU = totalPercent[0]
	}
	if cpuCount, _ := cpu.Counts(false); cpuCount > 0 {
		itemBase.LoadUsage = loadInfo.Load1 / float64(cpuCount)
	} else {
		itemBase.LoadUsage = 0
	}

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

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

	time.Sleep(duration)

	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 = io2.ReadBytes - io1.ReadBytes
				}
				if io2.WriteBytes != 0 && io1.WriteBytes != 0 && io2.WriteBytes > io1.WriteBytes {
					itemIO.Write = io2.WriteBytes - io1.WriteBytes
				}

				if io2.ReadCount != 0 && io1.ReadCount != 0 && io2.ReadCount > io1.ReadCount {
					itemIO.Count = io2.ReadCount - io1.ReadCount
				}
				if io2.WriteCount != 0 && io1.WriteCount != 0 && io2.WriteCount > io1.WriteCount {
					itemIO.Count += io2.WriteCount - io1.WriteCount
				}

				if io2.ReadTime != 0 && io1.ReadTime != 0 && io2.ReadTime > io1.ReadTime {
					itemIO.Time = io2.ReadTime - io1.ReadTime
				}
				if io2.WriteTime != 0 && io1.WriteTime != 0 && io2.WriteTime > io1.WriteTime {
					itemIO.Time += io2.WriteTime - io1.WriteTime
				}
				ioList = append(ioList, itemIO)
				break
			}
		}
	}
	return ioList
}

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

	time.Sleep(duration)

	// 获取结束时刻
	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 = net2.BytesSent - net1.BytesSent
				}
				if net2.BytesRecv != 0 && net1.BytesRecv != 0 && net2.BytesRecv > net1.BytesRecv {
					itemNet.Down = net2.BytesRecv - net1.BytesRecv
				}
				netList = append(netList, itemNet)
				break
			}
		}
	}

	return netList
}
