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

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

func (l *AdaptersListLogic) AdaptersList(req *types.AdapterQueryReq) (resp *types.PageResult, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	resp = &types.PageResult{}
	var list []types.AdapterInfo
	db := l.svcCtx.DbEngin.Model(&types.AdapterInfo{}).Table("t_adapter")

	if req.Name != "" {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Nickname != "" {
		db = db.Where("nickname LIKE ?", "%"+req.Nickname+"%")
	}
	if req.Type != "" {
		db = db.Where("type = ?", req.Type)
	}
	if req.Version != "" {
		db = db.Where("version = ?", req.Version)
	}
	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("create_time desc").Find(&list).Error

	resp.List = list
	resp.PageSize = req.PageSize
	resp.PageNum = req.PageNum
	resp.Total = total

	return resp, nil
}
