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"
	"gorm.io/gorm"
)

// 获取产品列表
func ItemFetch(ctx context.Context, in *pb.MallFetchRequest) (reply *pb.ListReply, err error) {
	if in.GetStoreIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var (
		cnt      int64 = 0
		pageNo   int64 = in.GetPageNo()
		pageSize int64 = in.GetPageSize()
		offset   int64 = (pageNo - 1) * pageSize
		params         = map[string]string{
			"mall_product.store_identity": in.GetStoreIdentity(),
		}
		idList  = make([]uint, 0)
		product []*models.MallProduct
	)

	// vlidate request page_no,page_size.
	if pageNo < 1 {
		pageNo = 1
		offset = 0
	}
	if pageSize <= 0 {
		pageSize = 10
		offset = (pageNo - 1) * pageSize
	}

	if err := impl.DBService.Model(&models.MallProduct{}).Where(params).Preload("Images").Preload("Specs.Spec").Preload("Categories.Category").
		Order("created_at desc").Count(&cnt).Offset(int(offset)).Limit(int(pageSize)).Find(&product).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	tx := impl.DBService.Model(&models.MallProduct{})
	//  根据传入的分类id进行过滤
	if len(in.GetCategoryId()) != 0 {
		tx = tx.Where("product_category.category_id in ?", idList).
			Joins("left join product_category on mall_product.id = product_category.product_id").
			Joins("left join mall_category on mall_category.id = product_category.category_id")
	}
	// 根据传入的关键字进行模糊搜索
	if in.GetKeyword() != "" {
		tx = tx.Where("mall_product.title like ?", "%"+in.GetKeyword()+"%")
	}
	// 根据传入的价格区间进行价格过滤
	if in.GetMinPrice() != 0 || in.GetMaxPrice() != 0 {
		tx = tx.Joins("left join product_spec on product_spec.product_id = mall_product.id").
			Joins("left join mall_product_spec on mall_product_spec.id = product_spec.spec_id").
			Where("mall_product_spec.price between ? and ?", in.GetMinPrice(), in.GetMaxPrice())
	}

	// 根据传入sort排序
	switch in.GetSort() {
	case "1":
		tx = tx.Order("mall_product.title asc")
	case "2":
		tx = tx.Order("mall_product.title desc")
	case "3":
		tx = tx.Order("mall_product.sales_price asc")
	default:
		tx = tx.Order("mall_product.created_at desc")
	}
	if err := tx.Where(params).Preload("Images").
		Preload("Specs.Spec", func(db *gorm.DB) *gorm.DB { return db.Order("mall_product_spec.price") }).
		Preload("Categories.Category").Count(&cnt).Offset(int(offset)).Limit(int(pageSize)).
		Find(&product).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	//  将数据库中的数据转换成pb.ProductItem
	data := ModelsToProductItems(product)
	for _, val := range data {
		for _, v := range val.Categories {
			val.CategoryId = append(val.CategoryId, v.Id)
		}
	}
	for _, val := range data {
		for _, v := range val.Specification {
			val.SpecId = append(val.SpecId, v.Id)
		}
	}
	return &pb.ListReply{
		Count: cnt,
		Data:  data,
	}, nil
}
