package handler

import (
	"fmt"
	"testing"
	"time"

	"github.com/dailymotion/allure-go"
	"github.com/tidbcloud/qa-Gourd/common"
)

func DoTest(t *testing.T, apiName string, env string) []common.GourdCase {
	defer func() {
		if e := recover(); e != nil {
			fmt.Printf("Panicing %s\r\n", e)
		}
	}()

	data := AnalyseData(apiName) //解析csv文件设置的请求数据
	//fmt.Printf("AnalyseData, data is: %v", data)
	//fmt.Println()
	AnalyseConfig(env)
	//fmt.Println(data)

	main := t
	for index, cs := range data {
		if len(cs.Method) == 0 {
			break
		}
		curTime := time.Now()
		fmt.Printf("CaseId:%s, Desc:%s, Api:%s, Path:%s, Method:%s, Param:%s, Body:%s, Status:%d, CurrentTime:%s, Response[X-Debug-Trace-Id]:%s", cs.CaseId, cs.Desc, cs.Api, cs.Paths, cs.Method, cs.Params, cs.Body, cs.Status, curTime)
		_ = main

		t.Run(cs.Desc, func(t *testing.T) { //子测试
			//	添加allure报告
			allure.Test(
				t,
				allure.Epic(apiName),
				allure.Feature(cs.Desc),
				//allure.Severity(cs.Severity),
				allure.Description(fmt.Sprintf("%s, CaseId:%s, Desc:%s, Api:%s, Path:%s, Method:%s, Param:%s, Body:%s, Status:%d, CurrentTime:%s", cs.Desc, cs.CaseId, cs.Desc, cs.Api, cs.Paths, cs.Method, cs.Params, cs.Body, cs.Status, curTime)),
				allure.Action(func() {
					if cs.IsNeed == "Y" {
						DoRequest(t, &cs)
						CheckResult(t, &cs) //返回结果校验
					} else {
						allure.SkipTest(t)
						t.Skip()
					}
				}),
				allure.Reason(fmt.Sprintf("CurrentTime:%s", curTime)))
		})

		data[index].Res = cs.Res
		//fmt.Printf("response is:%v", cs.Res.Raw())
	}
	return data
}
