package product

import (
	"context"

	"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 PhotoList(ctx context.Context, in *pb.PhotoItem) (reply *pb.PhotoReply, err error) {
	if in.GetProductIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var cnt int64 = 0
	data := make([]*models.MallProductPhotos, 0)

	err = impl.DBService.Where("product_identity = ?", in.ProductIdentity).Order("created_at desc").Find(&data).Count(&cnt).Error

	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	return &pb.PhotoReply{Count: cnt, Data: ModelToReplyPhotoList(data)}, nil
}

func ModelToReplyPhotoList(data []*models.MallProductPhotos) []*pb.PhotoItem {
	var list = make([]*pb.PhotoItem, 0)
	for _, v := range data {
		low := &pb.PhotoItem{
			Name:            v.Name,
			Identity:        v.Identity,
			ProductIdentity: v.ProductIdentity,
			Url:             v.Url,
		}
		list = append(list, low)
	}
	return list
}
