package product

import (
	"context"
	"time"

	"bsm/full/module/ec/mall/internal/impl"
	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"
)

// ModifySpec 修改产品规格
func SpecModify(ctx context.Context, in *pb.SpecItem) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

	// 检测参数
	err = checkParamSpecModify(in)
	if err != nil {
		return nil, err

	}

	// 数据组装
	data, err := requestToModelSpec(in)
	if err != nil {
		return nil, err
	}
	err = impl.DBService.Where("identity=?", data.Identity).Updates(data).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

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

}

func checkParamSpecModify(in *pb.SpecItem) error {
	if in.GetIdentity() == "" {
		return errcode.ErrInvalidArgument
	}
	// if in.GetProductIdentity() == "" {
	// 	return errcode.ErrInvalidArgument
	// }
	if in.GetTitle() == "" {
		return errcode.ErrInvalidArgument
	}
	if in.GetImg() == "" {
		return errcode.ErrInvalidArgument
	}
	if in.GetStock() == 0 {
		return errcode.ErrInvalidArgument
	}
	if in.GetPrice() == 0 {
		return errcode.ErrInvalidArgument
	}
	if in.GetPurchasingPrice() == 0 {
		return errcode.ErrInvalidArgument
	}

	return nil
}
