package dictionary

import (
	"context"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *ListDictItemLogic) ListDictItem(req *types.DictItemReq) (resp *types.PageResult, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	resp = &types.PageResult{}
	var dictList []types.DictItemInfo
	db := l.svcCtx.DbEngin.Model(&types.DictItemInfo{}).Table("t_dict_item")

	if req.ItemText != "" {
		db = db.Where("item_text LIKE ?", "%"+req.ItemText+"%")
	}
	if req.ItemValue != "" {
		db = db.Where("item_value LIKE ?", "%"+req.ItemValue+"%")
	}
	if req.Type != "" {
		db = db.Where("type = ?", req.Type)
	}
	if req.ParentId != "" {
		db = db.Where("parent_id = ?", req.ParentId)
	}
	if req.Status != "" {
		db = db.Where("status = ?", req.Status)
	}
	if req.DictId != "" {
		db = db.Where("dict_id = ?", req.DictId)
	}
	var total int64
	err = db.Count(&total).Error

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

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

	return resp, nil
}
