package product

import (
	"context"
	"time"

	"bsm/full/module/ec/mall/internal/models"
	pb "bsm/full/module/ec/mall/pb"
	"git.apinb.com/bsm-sdk/core/crypto/token"
	"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/types"
	"git.apinb.com/bsm-sdk/core/utils"
)

// ItemCreate 创建或更新产品
func ItemCreate(ctx context.Context, in *pb.ProductItem) (reply *pb.StatusReply, err error) {
	// 解析授权信息
	auth, err := service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

	// 参数校验
	err = checkParam(in)
	if err != nil {
		return nil, err
	}

	// 数据转换和组装
	data, specId, photo, categoryId, err := transitionData(in, auth)
	if err != nil {
		return nil, err
	}

	// 根据是否有Identity判断是创建还是更新
	if in.Identity == "" {
		// 新建产品 - 创建产品及其关联数据
		err = models.CreateProduct(data, specId, photo, categoryId)
	} else {
		// 更新产品 - 修改现有产品信息
		err = models.ModifyProduct(data, specId, photo, categoryId)
	}

	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

}

// checkParam 参数校验
func checkParam(in *pb.ProductItem) error {
	// 保存为草稿状态时，可以跳过部分参数验证
	if in.GetStatus() == 4 {
		return nil
	}

	// 必填字段校验
	if len(in.GetCategoryId()) == 0 {
		return errcode.ErrInvalidArgument
	}
	if in.GetTitle() == "" {
		return errcode.ErrInvalidArgument
	}
	if in.GetCoverImage() == "" {
		return errcode.ErrInvalidArgument
	}
	if in.GetMeasuringName() == "" {
		return errcode.ErrInvalidArgument
	}
	if in.GetContent() == "" {
		return errcode.ErrInvalidArgument
	}

	// 数值范围校验
	if in.GetSellMin() < 0 || in.GetSellMax() < 0 {
		return errcode.ErrInvalidArgument
	}
	if in.GetSellMin() > in.GetSellMax() {
		return errcode.ErrInvalidArgument
	}

	return nil
}

// transitionData 数据转换和组装
func transitionData(in *pb.ProductItem, auth *token.Claims) (*models.MallProduct, []*models.ProductSpec, []*models.MallProductPhotos, []*models.ProductCategory, error) {
	// 转换产品基本信息
	data, err := itemToModel(in)
	if err != nil {
		return nil, nil, nil, nil, errcode.ErrInternal
	}

	// 新建产品时设置默认值
	if data.Identity == "" {
		data.Identity = utils.UUID()
		owner := auth.Owner.(map[string]any)
		data.Store_ID = uint(owner["store_id"].(float64))
		data.Store_Identity = owner["store_identity"].(string)
	}

	// 组装分类关联数据
	categoryId := make([]*models.ProductCategory, 0, len(in.CategoryId))
	for _, v := range in.CategoryId {

		categoryId = append(categoryId, &models.ProductCategory{
			Std_IICUDS: types.Std_IICUDS{Identity: utils.UUID()},
			CategoryId: v,
		})
	}

	// 组装规格关联数据
	specId := make([]*models.ProductSpec, 0, len(in.SpecId))
	for _, v := range in.SpecId {
		specId = append(specId, &models.ProductSpec{
			Std_IICUDS: types.Std_IICUDS{Identity: utils.UUID()},
			SpecId:     v,
		})
	}

	// 转换产品图片数据
	photo := itemToModelPhoto(data.Identity, in.Images)
	return data, specId, photo, categoryId, nil
}

// itemToModel 将请求数据转换为模型数据
func itemToModel(in *pb.ProductItem) (*models.MallProduct, error) {
	mallProduct := models.MallProduct{
		SerialId:       in.SerialId,
		SupplyId:       in.SupplyId,
		Title:          in.Title,
		MeasuringName:  in.MeasuringName,
		SellMax:        int32(in.SellMax),
		SellMin:        int32(in.SellMin),
		Wastage:        int32(in.Wastage),
		StandardNumber: in.StandardNumber,
		Brand:          in.Brand,
		StockType:      int32(in.StockType),
		Status:         in.Status,
		PutawayTime:    in.PutawayTime,
		CoverImage:     in.CoverImage,
		TemplateID:     int64(in.TemplateId),
		RecentNumber:   in.RecentNumber,
		Limitation:     in.Limitation,
		LiTemplateID:   in.LiTemplateId,
		Content:        in.Content,
		Notes:          in.Note,
		SaleTotal:      int32(in.SaleTotal),
		GasType:        int32(in.GasTypes),
		Recommend:      1, // 默认推荐状态
	}

	// 更新操作时设置Identity
	if in.Identity != "" {
		mallProduct.Identity = in.Identity
	}

	// 根据序列号设置气体类型
	if in.SerialId == "gas_by_kg" {
		mallProduct.GasType = 2
	} else if in.SerialId == "gas_by_bottle" {
		mallProduct.GasType = 1
	}

	return &mallProduct, nil
}
func itemToModelSpec(identity string) ([]*models.MallProductSpec, error) {
	var specification = make([]*models.MallProductSpec, 0)

	// for _, v := range in {

	// 	data := models.MallProductSpec{
	// 		Title:           v.Title,
	// 		StockType:       v.StockType,
	// 		Stock:           v.Stock,
	// 		Price:           v.Price,
	// 		DirectSales:     v.DirectSales,
	// 		DsTpType:        v.DsTpType,
	// 		TpType:          v.TpType,
	// 		Img:             v.Img,
	// 		ProductIdentity: identity,
	// 	}
	// 	if v.Identity == "" {
	// 		data.Identity = utils.UUID()
	// 	} else {
	// 		data.ID = uint(v.Id)
	// 		data.Identity = v.Identity
	// 	}

	// 	specification = append(specification, &data)
	// }
	return specification, nil
}

// itemToModelPhoto 转换产品图片数据
func itemToModelPhoto(identity string, in []*pb.PhotoItem) []*models.MallProductPhotos {
	photo := make([]*models.MallProductPhotos, 0, len(in))
	for _, v := range in {
		img := &models.MallProductPhotos{
			Url:             v.Url,
			ProductIdentity: identity,
			Name:            v.Name,
		}

		// 更新操作时设置ID和Identity
		if v.Identity != "" {
			img.ID = uint(v.Id)
			img.Identity = v.Identity
		} else {
			// 新建时生成新的Identity
			img.Identity = utils.ULID()
		}
		photo = append(photo, img)
	}
	return photo
}
