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

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

func (l *GetRoleListLogic) GetRoleList(in *system.RoleListReq) (*system.RoleListResp, error) {
	var list []sysModel.SundynixRole
	var total int64
	db := l.svcCtx.DB.Model(&sysModel.SundynixRole{})
	if in.Name != "" {
		db = db.Where("name LIKE ?", "%"+in.Name+"%")
	}
	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.RoleInfo
	for _, r := range list {
		items = append(items, &system.RoleInfo{
			Id:        r.ID,
			Name:      r.Name,
			Code:      r.Code,
			Sort:      int32(r.Sort),
			CreatedAt: r.CreatedAt.Unix(),
		})
	}
	return &system.RoleListResp{List: items, Total: total}, nil
}
