package hpc

import (
	"context"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResourceLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewResourceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResourceLogic {
	return &ResourceLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ResourceLogic) Resource(req *types.HpcResourceReq) (resp *types.HpcResourceResp, err error) {

	type hpcResourceOV struct {
		CpuAvail  float64 `json:"cpu_avail"`
		CpuTotal  float64 `json:"cpu_total"`
		MemAvail  float64 `json:"mem_avail"`
		MemTotal  float64 `json:"mem_total"`
		DiskAvail float64 `json:"disk_avail"`
		DiskTotal float64 `json:"disk_total"`
		GpuAvail  float64 `json:"gpu_avail"`
		GpuTotal  float64 `json:"gpu_total"`
	}
	var hrov hpcResourceOV
	l.svcCtx.DbEngin.Raw("SELECT sum(cpu_avail) as cpu_avail,sum(cpu_total) as cpu_total,sum(mem_avail) as mem_avail,sum(mem_total) as mem_total,sum(disk_avail) as disk_avail,sum(disk_total) as disk_total,sum(gpu_avail) as gpu_avail,sum(gpu_total) as gpu_total FROM t_cluster_resource where cluster_type = 2").Scan(&hrov)

	hpcResource := types.HPCResource{
		GPUCardsTotal: hrov.GpuTotal,
		CPUCoresTotal: hrov.CpuTotal,
		RAMTotal:      hrov.MemTotal,
		GPUCardsUsed:  hrov.GpuTotal - hrov.GpuAvail,
		CPUCoresUsed:  hrov.CpuTotal - hrov.CpuAvail,
		RAMUsed:       hrov.MemTotal - hrov.MemAvail,
		GPURate:       (hrov.GpuTotal - hrov.GpuAvail) / hrov.GpuTotal,
		CPURate:       (hrov.CpuTotal - hrov.CpuAvail) / hrov.CpuTotal,
		RAMRate:       (hrov.MemTotal - hrov.MemAvail) / hrov.MemTotal,
	}

	resp = &types.HpcResourceResp{
		Code: 200,
		Msg:  "success",
		Data: hpcResource,
	}
	return resp, nil
}
