package hpc

import (
	"context"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"

	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
)

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

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

func (l *ListInstanceCenterLogic) ListInstanceCenter(req *types.HpcInstanceCenterReq) (resp *types.PageResult, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	resp = &types.PageResult{}
	var list *[]models.HpcInstanceCenter
	db := l.svcCtx.DbEngin.Model(&models.HpcInstanceCenter{}).Table("hpc_instance_center")

	if req.InstanceName != "" {
		db = db.Where("instance_name like ?", "%"+req.InstanceName+"%")
	}

	if req.InstanceType != 0 {
		db = db.Where("instance_type = ?", req.InstanceType)
	}

	if req.InstanceClass != "" {
		db = db.Where("instance_class = ?", req.InstanceClass)
	}
	var total int64
	err = db.Count(&total).Error

	if err != nil {
		return resp, err
	}
	db = db.Where("deleted_at is null").Limit(limit).Offset(offset)
	err = db.Order("created_at desc").Find(&list).Error
	if err != nil {
		return nil, err
	}
	resp.List = list
	resp.PageSize = req.PageSize
	resp.PageNum = req.PageNum
	resp.Total = total
	return
}
