package product

import (
	"context"
	"encoding/json"
	"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"
)

// CreateComment 评论
func CommentCreate(ctx context.Context, in *pb.CommentItem) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	RoleValve := &service.ParseOptions{RoleValue: "Mall_Admin"}
	if in.GetIsComment() == true {
		RoleValve = nil
	}
	auth, err := service.ParseMetaCtx(ctx, RoleValve)
	if err != nil {
		return nil, err
	}

	if in.GetComment() == "" || in.GetNickName() == "" || in.GetProductIdentity() == "" || in.GetStoreIdentity() == "" || in.GetSpecIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// 组装model
	data, err := itemToCommentModel(in)
	if err != nil {
		return nil, errcode.ErrInternal
	}
	data.OwnerID = auth.ID
	data.OwnerIdentity = auth.Identity
	data.ProductIdentity = in.ProductIdentity
	data.SpecIdentity = in.SpecIdentity
	data.StoreIdentity = in.StoreIdentity
	data.Identity = utils.UUID()

	err = impl.DBService.Create(data).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

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

}

func itemToCommentModel(in *pb.CommentItem) (*models.MallProductComment, error) {
	var commentProduct = models.MallProductComment{}
	data, err := json.Marshal(in)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(data, &commentProduct)
	if err != nil {
		return nil, err
	}
	return &commentProduct, err
}
