package dictionary

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

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

func (l *ListDictLogic) ListDict(req *types.DictReq) (resp *types.PageResult, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	resp = &types.PageResult{}
	var dictList []types.DictInfo
	db := l.svcCtx.DbEngin.Model(&types.DictInfo{}).Table("t_dict")

	if req.DictName != "" {
		db = db.Where("dict_name LIKE ?", "%"+req.DictName+"%")
	}
	if req.DictCode != "" {
		db = db.Where("dict_code LIKE ?", "%"+req.DictCode+"%")
	}
	if req.Type != "" {
		db = db.Where("type = ?", req.Type)
	}
	if req.Status != "" {
		db = db.Where("status = ?", req.Status)
	}
	var total int64
	err = db.Count(&total).Error

	if err != nil {
		return resp, err
	}
	db = db.Limit(limit).Offset(offset)
	err = db.Order("create_time desc").Find(&dictList).Error

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

	return resp, nil
}
