package core

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 HomeOverviewLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *HomeOverviewLogic) HomeOverview(req *types.HomeOverviewReq) (resp *types.HomeOverviewResp, err error) {
	// todo: add your logic here and delete this line
	resp = &types.HomeOverviewResp{}
	var AdapterSum int     //
	var StorageSum float32 //
	var ClusterSum int     //
	var TaskSum int        //
	//Task
	sqlStrTask := "SELECT COUNT(*) FROM `task`"
	txTask := l.svcCtx.DbEngin.Raw(sqlStrTask).Scan(&TaskSum)
	if txTask.Error != nil {
		logx.Error(err)
		return nil, txTask.Error
	}

	//Storage
	sqlStrStorage := "SELECT SUM(t.storage_space) as storageSum FROM `t_storage_device` t"
	txStorage := l.svcCtx.DbEngin.Raw(sqlStrStorage).Scan(&StorageSum)
	if txTask.Error != nil {
		logx.Error(err)
		return nil, txStorage.Error
	}

	//Cluster
	sqlStrCluster := "SELECT COUNT(*) FROM `t_cluster`"
	txCluster := l.svcCtx.DbEngin.Raw(sqlStrCluster).Scan(&ClusterSum)
	if txTask.Error != nil {
		logx.Error(err)
		return nil, txCluster.Error
	}

	//Adapter
	sqlStrAdapter := "SELECT COUNT(*) FROM `t_adapter`"
	txAdapter := l.svcCtx.DbEngin.Raw(sqlStrAdapter).Scan(&AdapterSum)
	if txTask.Error != nil {
		logx.Error(err)
		return nil, txAdapter.Error
	}

	resp.Data.TaskSum = int64(TaskSum)
	resp.Data.StorageSum = StorageSum
	resp.Data.AdaptSum = int64(AdapterSum)
	resp.Data.ClusterSum = int64(ClusterSum)

	resp.Code = 200
	resp.Message = "Success"
	return resp, nil
}
