package main

import (
	"fmt"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/process"
	"sort"
	"time"
)

type ProcessInfo struct {
	Pid      int32   `json:"pid"`
	Name     string  `json:"name"`
	CpuUsage float64 `json:"cpuUsage"`
	MemUsage float32 `json:"memUsage"`
}

// GetCpuPercent cpu总占用率
func GetCpuPercent() float64 {
	percent, _ := cpu.Percent(time.Second, false)
	return percent[0]
}

// GetMemoryPercent 内存总占用率
func GetMemoryPercent() float64 {
	memory, _ := mem.VirtualMemory()
	return memory.UsedPercent
}

// GetDiskPercent 磁盘总占用率
func GetDiskPercent() float64 {
	parts, _ := disk.Partitions(true)
	diskInfo, _ := disk.Usage(parts[0].Mountpoint)
	return diskInfo.UsedPercent
}

func GetTop10CpuAndMem() ([]ProcessInfo, []ProcessInfo) {
	// 获取所有进程的CPU占用率
	processes, err := process.Processes()
	if err != nil {
		//fmt.Println("Error:", err)
		return nil, nil
	}

	// 创建一个用于存储进程CPU占用率的映射
	cpuPercent := make(map[int32]float64)
	memPercent := make(map[int32]float32)

	// 获取每个进程的CPU占用率
	for _, p := range processes {
		pid := p.Pid
		cpuPercent[pid], err = p.CPUPercent()
		memPercent[pid], err = p.MemoryPercent()
	}

	// 根据CPU占用率对进程进行排序
	sortedPidsCpu := make([]int32, 0, len(cpuPercent))
	sortedPidsMem := make([]int32, 0, len(cpuPercent))
	for pid := range cpuPercent {
		sortedPidsCpu = append(sortedPidsCpu, pid)
	}

	sort.Slice(sortedPidsCpu, func(i, j int) bool {
		return cpuPercent[sortedPidsCpu[i]] > cpuPercent[sortedPidsCpu[j]]
	})

	// 输出前10个CPU占用率最高的进程名称
	var top10Cpu []ProcessInfo

	for i, pid := range sortedPidsCpu {
		if i >= 10 {
			break
		}
		p, err := process.NewProcess(pid)
		if err != nil {
			continue
		}
		name, _ := p.Name()
		top10Cpu = append(top10Cpu, ProcessInfo{
			Pid:      pid,
			Name:     name,
			CpuUsage: cpuPercent[pid],
			MemUsage: memPercent[pid],
		})
	}

	// --------------------- 内存
	var top10Mem []ProcessInfo

	for pid := range memPercent {
		sortedPidsMem = append(sortedPidsMem, pid)
	}

	sort.Slice(sortedPidsMem, func(i, j int) bool {
		return memPercent[sortedPidsMem[i]] > memPercent[sortedPidsMem[j]]
	})

	for i, pid := range sortedPidsMem {
		if i >= 10 {
			break
		}
		p, err := process.NewProcess(pid)
		if err != nil {
			continue
		}
		name, _ := p.Name()
		top10Mem = append(top10Mem, ProcessInfo{
			Pid:      pid,
			Name:     name,
			CpuUsage: cpuPercent[pid],
			MemUsage: memPercent[pid],
		})
	}
	return top10Cpu, top10Mem
}

func main() {
	fmt.Println("cpu总占用率为:", GetCpuPercent())
	fmt.Println("内存总占用率为:", GetMemoryPercent())
	fmt.Println("磁盘总占用率为:", GetDiskPercent())
	top10cpu, top10mem := GetTop10CpuAndMem()
	fmt.Println("top10cpu为:", top10cpu)
	fmt.Println("top10mem为:", top10mem)
}