package logic

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

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

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

func (l *GetBadgeConfigTreeLogic) GetBadgeConfigTree(in *plant.IdReq) (*plant.BadgeConfigTreeResp, error) {
	var badges []plantModel.BadgeConfig
	if err := l.svcCtx.DB.Order("dimension, group_id, tier asc").Find(&badges).Error; err != nil {
		return nil, err
	}
	// 按 groupId 分组
	groupMap := make(map[string]*plant.BadgeGroupInfo)
	groupOrder := []string{}
	for _, b := range badges {
		key := b.GroupID
		if key == "" {
			key = b.Dimension
		}
		if _, ok := groupMap[key]; !ok {
			groupMap[key] = &plant.BadgeGroupInfo{GroupId: key, Dimension: b.Dimension}
			groupOrder = append(groupOrder, key)
		}
		groupMap[key].Badges = append(groupMap[key].Badges, &plant.BadgeConfigInfo{
			Id: b.ID, Name: b.Name, Description: b.Description, Dimension: b.Dimension,
			GroupId: b.GroupID, Tier: int32(b.Tier), TargetAction: b.TargetAction,
			Threshold: b.Threshold, RewardSunlight: b.RewardSunlight, IconId: b.IconID, Sort: int32(b.Sort),
		})
	}
	groups := make([]*plant.BadgeGroupInfo, 0, len(groupOrder))
	for _, k := range groupOrder {
		groups = append(groups, groupMap[k])
	}
	return &plant.BadgeConfigTreeResp{Groups: groups}, nil
}
