package timeslicequery

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

func (v *Query) execute(ctx context.Context, req *timeslice.Manager) error {

	start := time.Now()

	managerStartStr := req.StartTime.Format(time.DateTime)
	managerEndStr := req.EndTime.Format(time.DateTime)

	log.Warnf("微信券查询,%s到%s,开始", managerStartStr, managerEndStr)
	fmt.Printf("微信券查询,%s到%s,开始\n", managerStartStr, managerEndStr)

	taskCount, err := timeslice.NewManager(v.callbackFunc).Run(ctx, req)
	if err != nil {
		log.Errorf("微信券查询,%s到%s,失败:%v", managerStartStr, managerEndStr, err)
	}

	elapsed := time.Now().Sub(start).String()

	log.Warnf("微信券查询,%s到%s,总任务数:%d,总耗时:%s", managerStartStr, managerEndStr, taskCount, elapsed)
	fmt.Printf("微信券查询,%s到%s,总任务数:%d,总耗时:%s\n", managerStartStr, managerEndStr, taskCount, elapsed)

	return nil
}

func (v *Query) callbackFunc(ctx context.Context, req *timeslice.Task) error {

	startTimeStr := req.Process.Manager.StartTime.Format(time.DateTime)
	endTimeStr := req.Process.Manager.EndTime.Format(time.DateTime)

	currentStartTimeStr := req.CurrentStartTime.Format(time.DateTime)
	currentEndTimeStr := req.CurrentEndTime.Format(time.DateTime)

	start := time.Now()

	bReq := &do.WechatQuery{
		StartTime: currentStartTimeStr,
		EndTime:   currentEndTimeStr,
		ProductNo: req.Process.Manager.ProductNo,
		BatchNo:   req.Process.Manager.BatchNo,
	}

	num := 0
	errNum := 0
	useNum := 0

	err := v.orderRepo.FinSucByStockIdInBatches(ctx, bReq, func(ctx context.Context, rows []*bo.OrderBo) error {

		for _, order := range rows {

			num += 1
			if err := v.wechatQuery(ctx, order, &useNum); err != nil {

				errNum += 1

				logFields := map[string]string{
					"order_no":  order.OrderNo,
					"coupon_id": order.VoucherNo,
					"open_id":   order.Account,
					"stock_id":  order.BatchNo,
					"err":       err.Error(),
				}
				log.Errorf("微信券查询,%s到%s,taskId:%d,错误:%+v", startTimeStr, endTimeStr, req.TaskID, logFields)

				if errNum > 20 {
					return fmt.Errorf("微信券查询,%s到%s,第%d个任务,已经连续发生20次错误%+v", startTimeStr, endTimeStr, req.TaskID, logFields)
				}
			}

		}

		return nil
	})

	end := time.Now()

	logFields := map[string]any{
		"sTime":   currentStartTimeStr + "到" + currentEndTimeStr,
		"num":     num,
		"useNum":  useNum,
		"errNum":  errNum,
		"batchNo": req.Process.Manager.BatchNo,
		"elapsed": end.Sub(start).String(),
	}
	log.Warnf("微信券查询,%s到%s,taskId:%d,处理完毕:%+v", startTimeStr, endTimeStr, req.TaskID, logFields)

	return err
}
