package post

import (
	"context"

	"bsm/full/module/social/feed/internal/models"
	pb "bsm/full/module/social/feed/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
)

// 推文列表
func Fetch(ctx context.Context, in *pb.FetchRequest) (reply *pb.PostListReply, err error) {
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	if in.GetPageNo() <= 0 {
		in.PageNo = 1
	}
	if in.GetPageSize() <= 0 {
		in.PageSize = 10
	}

	data, cnt, err := models.PostList(in.PageNo, in.PageSize, in.Params["key"])
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	var res = &pb.PostListReply{Cnt: cnt}
	if cnt > 0 {
		res.List = AssembleList(data)
	}
	return res, nil
}

func AssembleList(data []*models.FeedPost) (res []*pb.PostItem) {
	for _, val := range data {
		post := &pb.PostItem{
			Identity:     val.Identity,
			Content:      val.Content,
			FeedIdentity: val.Identity,
			FeedId:       int64(val.ID),
			IsOpen:       val.IsOpen,
			CntUnlike:    val.CntUnlike,
			CntLike:      val.CntLike,
			CntComment:   val.CntComment,
		}
		for _, tag := range val.Tags {
			post.Tags = append(post.Tags, &pb.TagItem{
				Key:     tag.Key,
				Content: tag.Content,
			})
		}
		for _, attachs := range val.Attachs {
			post.Attachs = append(post.Attachs, &pb.AttachItem{
				Identity:   attachs.Identity,
				AttachType: attachs.AttachType,
				Url:        attachs.Url,
			})
		}
		res = append(res, post)
	}
	return
}
