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"
)

// CreateSpec 添加产品规格
func SpecCreate(ctx context.Context, in *pb.SpecItem) (reply *pb.IdentityStatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

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

	// 数据组装
	data, err := requestToModelSpec(in)
	if err != nil {
		return nil, err
	}
	data.Identity = utils.UUID()
	tx := impl.DBService.Create(data)
	cnt, err := tx.RowsAffected, tx.Error
	if cnt == 0 || err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

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

}

func checkParamSpecCreate(in *pb.SpecItem) error {
	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.GetSpecNo() == "" {
		return errcode.ErrInvalidArgument
	}
	// if in.GetKeyword() == "" {
	// 	return errcode.ErrInvalidArgument
	// }
	if in.GetPurchasingPrice() == 0 {
		return errcode.ErrInvalidArgument
	}
	// if in.GetSupplyId() == 0 {
	// 	return errcode.ErrInvalidArgument
	// }
	return nil
}
func requestToModelSpec(in *pb.SpecItem) (*models.MallProductSpec, error) {
	var specification = &models.MallProductSpec{
		SupplyId:        in.SupplyId,
		StoreIdentity:   in.StoreIdentity,
		Title:           in.Title,
		StockType:       2,
		Stock:           in.Stock,
		Price:           in.Price,
		DirectSales:     in.DirectSales,
		TpType:          2,
		DsTpType:        2,
		Img:             in.Img,
		SpecNo:          in.SpecNo,
		Keyword:         in.Keyword,
		PurchasingPrice: in.PurchasingPrice,
		Wholesale:       in.Wholesale,
	}
	if in.StockType != 2 {
		specification.Stock = int64(in.StockType)
	}
	if in.TpType != 2 {
		specification.TpType = in.TpType
	}
	if in.DsTpType != 2 {
		specification.DsTpType = in.DsTpType
	}
	if in.Identity != "" {
		specification.Identity = in.Identity
	}
	return specification, nil
}
