package agency

import (
	"context"

	"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 Pending(ctx context.Context, in *pb.FetchRequest) (reply *pb.AgencyReply, err error) {
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	var (
		cnt    int64 = 0
		Offset int64 = (in.GetPageNo() - 1) * in.GetPageSize()
		data         = make([]*models.MarketAgency, 0)
	)

	if in.GetPageNo() < 1 {
		in.PageNo = 1
	}
	if in.GetPageSize() < 0 {
		in.PageSize = 50
	}
	tx := models.DBService.Model(&models.MarketAgency{}).Where("approve = 0").Order("created_at desc")
	if in.GetIdentity() != "" {
		tx.Where("identity = ?", in.GetIdentity())
	}
	if err := tx.Count(&cnt).Limit(int(in.GetPageSize())).Offset(int(Offset)).Find(&data).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.AgencyReply{
		Data:  ref(data),
		Count: int64(len(data)),
	}, nil
}
