package product

import (
	"context"

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

// Detail 获取产品详情
func ItemDetail(ctx context.Context, in *pb.IdentRequest) (reply *pb.ProductItem, err error) {
	if in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var data = &models.MallProduct{}
	err = impl.DBService.Preload("Specs.Spec").Preload("Images").Preload("Categories.Category").Where("identity = ?", in.Identity).First(data).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	reply, err = ModelToProductItem(data)
	if err != nil {
		return nil, err
	}
	if reply.SupplyId != 0 {
		supply := map[string]any{}
		if err := impl.DBService.Table("market_supply").Take(&supply, "id = ?", reply.SupplyId).Error; err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}
		reply.SupplyName = supply["name"].(string)
	}

	for _, v := range data.Categories {
		reply.CategoryId = append(reply.CategoryId, int64(v.CategoryId))

	}
	for _, v := range data.Specs {
		reply.SpecId = append(reply.SpecId, int64(v.SpecId))
	}
	return reply, nil
}
