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 Fetch(ctx context.Context, in *pb.FetchRequest) (reply *pb.AgencyReply, err error) {
	var (
		cnt    int64 = 0
		Offset int64 = (in.GetPageNo() - 1) * in.GetPageSize()
		data         = make([]*models.MarketAgency, 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 := models.DBService.Model(&models.MarketAgency{})
	if in.GetIdentity() != "" {
		tx.Where("identity = ?", in.GetIdentity())
	}
	if in.GetApprove() != 0 {
		tx = tx.Where("approve = ?", in.GetApprove())
	}
	if in.GetStatus() != 0 {
		tx = tx.Where("status = ?", in.GetStatus())
	}
	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.AgencyReply{
		Data:  ref(data),
		Count: int64(len(data)),
	}, nil
}
