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

// 添加产品图片
func PhotoCreate(ctx context.Context, in *pb.PhotoItem) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

	// 参数检测
	if in.GetUrl() == "" || in.GetProductIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}
	// 数据组装
	var photo = models.MallProductPhotos{
		Name:            in.Name,
		ProductIdentity: in.ProductIdentity,
		Url:             in.Url,
	}
	photo.Identity = utils.UUID()
	tx := impl.DBService.Create(&photo)
	cnt, err := tx.RowsAffected, tx.Error
	if cnt == 0 || err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Code:    0,
		Message: "OK",
		Timeseq: time.Now().UnixNano(),
	}, nil

}
