package supply

import (
	"context"

	"bsm/full/module/ec/market/internal/impl"
	"bsm/full/module/ec/market/internal/models"
	pb "bsm/full/module/ec/market/pb"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
)

// 供应商列表
func Fetch(ctx context.Context, in *pb.MarketFetchRequest) (reply *pb.SupplyReply, err error) {
	var (
		cnt    int64 = 0
		Offset int64 = (in.GetPageNo() - 1) * in.GetPageSize()
		data         = make([]*models.MarketSupply, 0)
	)
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	if in.GetPageNo() < 1 {
		in.PageNo = 1
	}
	if in.GetPageSize() < 10 {
		in.PageSize = 50
	}
	tx := impl.DBService.Model(&models.MarketSupply{}).Where("status = ?", 1)
	if in.GetIdentity() != "" {
		tx.Where("identity = ?", in.GetIdentity())
	}
	if err := tx.Order("created_at desc").Count(&cnt).Limit(int(in.GetPageSize())).Offset(int(Offset)).Find(&data).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	return &pb.SupplyReply{
		Data:  ref(data),
		Count: int64(len(data)),
	}, nil
}
