package biz

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"time"
	"voucher/internal/biz/bo"
)

func (v *VoucherBiz) PushWechatRetry(ctx context.Context, productNo string) error {

	product, err := v.ProductRepo.GetByProductNo(ctx, productNo)
	if err != nil {
		return err
	}

	queue := v.bc.RdsMQ.GetWechatRetry()
	if queue == nil {
		return fmt.Errorf("队列不存在")
	}

	_, err = v.rdb.Rdb.RPush(ctx, queue.Name, product.BatchNo).Result()
	if err != nil {
		return fmt.Errorf("添加到队列失败:%v", err)
	}

	return nil
}

func (v *VoucherBiz) WechatRetry(ctx context.Context, batchNo string) error {

	start := time.Now()
	log.Warnf("失败订单重试开始:%s,batchNo:%s", start.String(), batchNo)
	fmt.Printf("失败订单重试开始:%s,batchNo:%s", start.String(), batchNo)

	num := 0
	err := v.OrderRepo.FinFailByStockIdInBatches(ctx, batchNo, func(ctx context.Context, rows []*bo.OrderBo) error {

		if len(rows) == 0 {
			log.Infof("微信查询券订单状态,batchNo[%s],已处理[%d]单，无订单,结束执行", batchNo, num)
			return nil
		}

		for _, order := range rows {

			num += 1
			if err := v.orderRetry(ctx, order); err != nil {
				log.Errorf("失败订单重试发生错误,batchNo:%s,orderNo:%s,appId:%s,openId:%s,err:%v",
					batchNo, order.OrderNo, order.AppID, order.Account, err)
			}

		}

		time.Sleep(1 * time.Second)

		return nil
	})

	log.Warnf("微信券查询处理耗时:%s,batchNo:%s,处理%d单", time.Now().Sub(start).String(), batchNo, num)
	fmt.Printf("微信券查询处理耗时:%s,batchNo:%s,处理%d单", time.Now().Sub(start).String(), batchNo, num)

	return err
}
