package post

import (
	"context"
	"fmt"
	"time"

	"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"
	"git.apinb.com/bsm-sdk/core/printer"
)

// 评论列表
func CommentList(ctx context.Context, in *pb.CommentListRequest) (*pb.CommentListResponse, error) {
	var (
		page               = in.GetPage()
		size               = in.GetSize()
		postIdentity       = in.GetPostIdentity()
		list               = make([]models.CmsComment, 0)
		cnt          int64 = 0
	)
	// _, err := service.ParseMetaCtx(ctx, nil)
	// if err != nil {
	// 	return nil, err
	// }

	if in.GetPostIdentity() == "" {
		fmt.Println("err = ", in.GetPostIdentity())
		return nil, errcode.ErrInvalidArgument
	}

	if in.GetPage() < 1 {
		in.Page = 1
	}
	if in.GetSize() < 10 {
		in.Size = 10
	}
	if in.GetSize() > 50 {
		in.Size = 50
	}
	// list, cnt, err := logic.CommentList(in.Page, in.Size, in.PostIdentity)
	if err := impl.DBService.Model(&models.CmsComment{}).Debug().Where("post_identity = ?", postIdentity).
		Order("created_at desc").Preload("Children").Count(&cnt).
		Limit(int(size)).Offset(int((page - 1) * size)).Find(&list).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	return &pb.CommentListResponse{
		List:  GetCommentList(list),
		Count: cnt,
	}, nil
}
func GetCommentList(list []models.CmsComment) (res []*pb.CommentItem) {
	for _, val := range list {
		var comment = &pb.CommentItem{
			Identity:      val.Identity,
			PostIdentity:  val.PostIdentity,
			OwnerName:     val.OwnerName,
			OwnerIdentity: val.OwnerIdentity,
			Role:          val.Role,
			ParentId:      int64(val.ParentId),
			Cms:           val.Cms,
			ReplyIdentity: val.ReplyIdentity,
			CreatedAt:     val.CreatedAt.Format(time.DateTime),
			UpdatedAt:     val.UpdatedAt.Format(time.DateTime),
			LikeHits:      val.LikeHits,
			UnlikeHits:    val.UnlikeHits,
			CommentHits:   val.CommentHits,
		}

		if len(val.Children) != 0 {
			comment.List = GetCommentList(val.Children)
		}
		res = append(res, comment)

	}
	return res
}
