package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"
)

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

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

func (l *GetDictListLogic) GetDictList(in *system.DictListReq) (*system.DictListResp, error) {
	var list []sysModel.SundynixDict
	var total int64
	db := l.svcCtx.DB.Model(&sysModel.SundynixDict{})
	if in.Type != "" {
		db = db.Where("type = ?", in.Type)
	}
	db.Count(&total)
	current, pageSize := int(in.Current), int(in.PageSize)
	if current <= 0 {
		current = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}
	if err := db.Offset((current - 1) * pageSize).Limit(pageSize).Order("sort ASC").Find(&list).Error; err != nil {
		return nil, fmt.Errorf("查询字典列表失败")
	}
	var items []*system.DictInfo
	for _, d := range list {
		items = append(items, &system.DictInfo{Id: d.ID, Type: d.Type, Label: d.Label, Value: d.Value, Sort: int32(d.Sort), Desc: d.Desc})
	}
	return &system.DictListResp{List: items, Total: total}, nil
}
