package category

import (
	"context"
	"fmt"

	"bsm/full/module/base/cms/internal/impl"
	"bsm/full/module/base/cms/internal/models"
	pb "bsm/full/module/base/cms/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
)

// 分类列表
func Fetch(ctx context.Context, in *pb.IdentRequest) (reply *pb.CategoryListReply, err error) {
	// list, cnt, err := logic.CategoryList()
	var (
		cnt  int64 = 0
		list []models.CmsCategory
	)
	tx := impl.DBService.Debug().Model(&models.CmsCategory{})
	fmt.Println("in = ", in)
	if in.GetId() != 0 {
		tx = tx.Where("parent_id = ?", in.GetId())
	} else {
		tx = tx.Where("parent_id = 0")
	}
	err = tx.Order("created_at desc").Preload("Children").Count(&cnt).Find(&list).Error
	if err != nil {
		return nil, errcode.ErrDB
	}

	out := &pb.CategoryListReply{
		Count: cnt,
		Data:  fetchCategory(list),
	}
	return out, nil
}

func fetchCategory(list []models.CmsCategory) (in []*pb.CategoryItem) {
	for _, v := range list {
		item := &pb.CategoryItem{
			Id:          int64(v.ID),
			Identity:    v.Identity,
			ParentId:    int64(v.ParentId),
			CategoryKey: v.CategoryKey,
			Title:       v.Title,
			CoverPath:   v.CoverPath,
			Intro:       v.Intro,
			CreatedAt:   v.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:   v.UpdatedAt.Format("2006-01-02 15:04:05"),
			Child:       make([]*pb.CategoryItem, 0, len(v.Children)),
		}
		if len(v.Children) > 0 {
			item.Child = fetchCategory(v.Children)
		}
		in = append(in, item)
	}
	return in
}
