package product

import (
	"context"
	"time"

	"bsm/full/module/ec/mall/internal/impl"
	"bsm/full/module/ec/mall/internal/models"
	pb "bsm/full/module/ec/mall/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
)

// 产品的评论列表
func CommentFetch(ctx context.Context, in *pb.FetchRequest) (reply *pb.CommentListReply, err error) {
	// valildate request id,identity.
	if in.GetStoreIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var (
		cnt      int64 = 0
		pageNo   int64 = in.GetPageNo()
		pageSize int64 = in.GetPageSize()
		offset   int64 = (pageNo - 1) * pageSize
		params         = map[string]string{
			"store_identity": in.GetStoreIdentity(),
		}
		data = make([]models.MallProductComment, 0)
		res  = make([]*pb.CommentItemRep, 0)
	)

	// vlidate request page_no,page_size.
	if pageNo < 1 {
		pageNo = 1
		offset = 0
	}
	if pageSize < 50 {
		pageSize = 50
		offset = (pageNo - 1) * pageSize
	}

	if err := impl.DBService.Model(&models.MallProductComment{}).Preload("List").Where(params).
		Order("created_at desc").Count(&cnt).Offset(int(offset)).Limit(int(pageSize)).Find(&data).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	for _, val := range data {
		line := &pb.CommentItemRep{
			Id:              int64(val.ID),
			Identity:        val.Identity,
			CreatedAt:       val.CreatedAt.Format(time.DateTime),
			NickName:        val.Nickname,
			Score:           int32(val.Score),
			Comment:         val.Comment,
			Reply:           val.Reply,
			ProductIdentity: val.ProductIdentity,
			StoreIdentity:   val.StoreIdentity,
			SpecIdentity:    val.SpecIdentity,
			CommentIdentity: val.CommentIdentity,
			Product:         val.Product.Title,
			ProductSpec:     val.ProductSpec.Title,
		}
		if len(val.List) > 0 {
			for _, v := range val.List {
				line.List = append(line.List, &pb.CommentItem{
					Id:              int64(v.ID),
					Identity:        v.Identity,
					CreatedAt:       v.CreatedAt.Format(time.DateTime),
					NickName:        v.Nickname,
					Score:           int32(v.Score),
					Comment:         v.Comment,
					Reply:           v.Reply,
					ProductIdentity: v.ProductIdentity,
					StoreIdentity:   v.StoreIdentity,
					SpecIdentity:    v.SpecIdentity,
					CommentIdentity: v.CommentIdentity,
					Product:         v.Product.Title,
					ProductSpec:     v.ProductSpec.Title,
				})
			}
		}

		res = append(res, line)
	}
	return &pb.CommentListReply{
		Data:  res,
		Count: cnt,
	}, nil
}
