package script

import (
	"encoding/json"
	"fmt"
	"golang.org/x/sync/errgroup"
	"testing"
	"time"
	"voucher/internal/biz/bo"
)

func Test_timeSliceQueryPush(t *testing.T) {

	startTime, err := time.Parse(time.DateTime, "2025-05-01 00:00:00")
	if err != nil {
		t.Error(err)
		return
	}

	endTime, err := time.Parse(time.DateTime, "2025-05-01 02:00:03")
	if err != nil {
		t.Error(err)
		return
	}

	duration := 5 * time.Hour

	//requestUrl := URL
	requestUrl := DEV_URL

	if err = timeSliceQueryPush(startTime, endTime, duration, requestUrl); err != nil {
		t.Error(err)
	}
}

func Test_pushWechatQuery(t *testing.T) {

	startTime, err := time.Parse(time.DateTime, "2025-05-31 00:00:00")
	if err != nil {
		t.Error(err)
		return
	}

	endTime, err := time.Parse(time.DateTime, "2025-05-01 10:00:00")
	if err != nil {
		t.Error(err)
		return
	}

	duration := 1 * time.Hour

	requestUrl := SINGLE_URL

	if err = pushWechatQuery(startTime, endTime, duration, requestUrl); err != nil {
		t.Error(err)
	}
}

func Test_moreTime(t *testing.T) {

	startTime, err := time.Parse(time.DateTime, "2025-05-31 00:00:00")
	if err != nil {
		t.Error(err)
		return
	}

	endTime, err := time.Parse(time.DateTime, "2025-05-31 10:00:00")
	if err != nil {
		t.Error(err)
		return
	}

	//duration := 240 * time.Hour
	duration := 1 * time.Hour

	for start := startTime; start.Before(endTime); start = start.Add(duration) {

		end := start.Add(duration) // 计算每次请求的结束时间
		if end.After(endTime) {
			end = endTime
		}

		// 创建请求体
		requestBody := map[string]any{
			"start_time":       start.Format(time.DateTime),
			"end_time":         end.Format(time.DateTime),
			"go_num":           2, // 并发数量
			"time_slice_hours": 1, // 时间间隔
			"product_no":       "",
		}

		// 将请求体转换为 JSON 格式
		bodyBytes, err2 := json.Marshal(requestBody)
		if err2 != nil {
			t.Error(err)
			return
		}

		fmt.Printf("body:%s\n", string(bodyBytes))
	}
}

func Test_goMoreTime(t *testing.T) {

	startTime, err := time.Parse(time.DateTime, "2025-05-01 00:00:00")
	if err != nil {
		t.Error(err)
		return
	}

	//endTime, err := time.Parse(time.DateTime, "2025-05-31 23:59:59")
	endTime, err := time.Parse(time.DateTime, "2025-05-01 23:59:59")
	if err != nil {
		t.Error(err)
		return
	}

	duration := 1 * time.Hour

	eg := new(errgroup.Group)
	eg.SetLimit(5)

	for start := startTime; start.Before(endTime); start = start.Add(duration) {

		end := start.Add(duration) // 计算每次请求的结束时间
		if end.After(endTime) {
			end = endTime
		}

		req := &bo.FindInBatchesUseBo{
			StartTime: &start,
			EndTime:   &end,
		}

		// 将请求体转换为 JSON 格式
		reqStr, err2 := json.Marshal(req)
		if err2 != nil {
			t.Error(err)
			return
		}

		eg.Go(func() error {
			// 任务逻辑...
			time.Sleep(2 * time.Second)
			return fmt.Errorf("任务失败")
		})

		fmt.Printf("%s\n", string(reqStr))
	}

	err = eg.Wait() // 仅返回第一个错误
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("所有任务完成")
	}
}
