package adapters

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

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

func (l *ClusterListLogic) ClusterList(req *types.ClusterReq) (resp *types.PageResult, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	resp = &types.PageResult{}
	var list []types.ClusterInfo
	db := l.svcCtx.DbEngin.Model(&types.AdapterInfo{}).Table("t_cluster")

	db = db.Joins("left join t_adapter on t_adapter.id = t_cluster.adapter_id").
		Where("t_cluster.deleted_at is null")
	if req.Name != "" {
		db = db.Where("t_cluster.name LIKE ?", "%"+req.Name+"%")
	}
	if req.AdapterId != "" {
		db = db.Where("t_cluster.adapter_id = ?", req.AdapterId)
	}
	if req.Nickname != "" {
		db = db.Where("t_cluster.nickname LIKE ?", "%"+req.Nickname+"%")
	}
	if req.Label != "" {
		db = db.Where("t_cluster.label = ?", req.Label)
	}
	if req.Version != "" {
		db = db.Where("t_cluster.version = ?", req.Version)
	}
	if req.ProducerDict != "" {
		db = db.Where("t_cluster.producer_dict = ?", req.ProducerDict)
	}
	if req.RegionDict != "" {
		db = db.Where("t_cluster.region_dict = ?", req.RegionDict)
	}
	if req.Type != "" {
		db = db.Where("t_adapter.type = ?", req.Type)
	}
	if req.ResourceType != "" {
		db = db.Where("t_adapter.resource_type = ?", req.ResourceType)
	}
	if req.StorageSchedule != "" {
		db = db.Where("t_cluster.storage_schedule = ?", req.StorageSchedule)
	}

	//count total
	var total int64
	err = db.Select("*").Count(&total).Error
	if err != nil {
		return resp, err
	}

	db = db.Limit(limit).Offset(offset)
	err = db.Select("t_cluster.*").Order("t_cluster.create_time desc").Scan(&list).Error
	if err != nil {
		return resp, err
	}
	resp.List = list
	resp.PageSize = req.PageSize
	resp.PageNum = req.PageNum
	resp.Total = total

	return resp, nil
}
