package handler

import (
	"bufio"
	"io"
	"os"
	"reflect"
	"regexp"
	"strconv"
	"strings"

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

func AnalyseData(apiName string) []common.GourdCase {
	var recs []common.GourdCase

	file, err := os.Open("../testData/" + apiName + ".csv")
	util.Check(err)
	defer file.Close()

	rd := bufio.NewReader(file)

	first := 0

	var headRow []string

	for {

		//var rec common.GourdCase
		rec := common.MakeGourdCase()

		line, err := rd.ReadString('\n') //以'\n'为结束符读入一行

		if err != nil || io.EOF == err {
			break
		}

		row := strings.Split(line, "|")

		if first == 0 { //头

			first = 1
			headRow = row

			for i, hval := range row {
				//去掉换行符
				hval = strings.Replace(hval, "\n", "", -1)
				hval = strings.Replace(hval, "\r", "", -1)
				headRow[i] = hval
			}

		} else {

			for i, hval := range row {

				//去掉换行符
				hval = strings.Replace(hval, "\n", "", -1)
				hval = strings.Replace(hval, "\r", "", -1)

				var tmp []string

				//fmt.Println(headRow[i] + ":" + hval)

				tempLen := len(hval)
				if tempLen == 0 {
					continue
				}

				re := regexp.MustCompile("\\$[A-Za-z0-9_]+\\$")
				submatch := re.FindAllStringSubmatch(hval, -1)
				for _, text := range submatch {
					oriVal := text[0][1 : len(text[0])-1]
					//fmt.Println("oriVal:",oriVal)
					//新增对component的解析
					tempValue := AnalyseComponent(oriVal)

					//fmt.Println(tempValue)
					//fmt.Println(reflect.ValueOf(tempValue).Kind())
					if reflect.ValueOf(tempValue).Kind() == reflect.String {
						//fmt.Println("解析值为string类型:")
						//解析值为string 类型
						value := reflect.ValueOf(tempValue).String()
						//对相应的变量执行替换
						hval = strings.Replace(hval, text[0], value, -1)

					} else if reflect.ValueOf(tempValue).Kind() == reflect.Int64 {
						//fmt.Println("解析值为int类型:")
						//fmt.Println(reflect.ValueOf(tempValue).Kind())
						//fmt.Println(tempValue)
						//fmt.Println(reflect.ValueOf(tempValue).String())
						tmpInt := reflect.ValueOf(tempValue).Int()
						value := strconv.FormatInt(tmpInt, 10)
						if hval == text[0] {
							//fmt.Println("value:", value)
							hval = value
							//hval = reflect.ValueOf(tempValue)
						} else {
							hval = strings.Replace(hval, text[0], value, -1)
						}

					}
				}

				if headRow[i] == "caseNo" {
					rec.CaseId = hval

				} else if headRow[i] == "desc" {
					rec.Desc = hval
				} else if headRow[i] == "apiName" {
					rec.Api = hval
				} else if headRow[i] == "method" {
					rec.Method = hval
				} else if headRow[i] == "isNeed" {
					rec.IsNeed = hval
				} else if headRow[i] == "retry" {
					rec.Retry, err = strconv.Atoi(hval) //string->int
					util.Check(err)
				} else if headRow[i] == "status" {
					rec.Status, err = strconv.Atoi(hval) //string->int
					util.Check(err)
				} else if headRow[i] == "digestAuth" {
					// add digest auth to test openapi
					rec.DigestAuth = strings.Split(hval, ",")
				} else if headRow[i] == "severity" {
					switch hval {
					case "blocker":
						rec.Severity = severity.Blocker
					case "critical":
						rec.Severity = severity.Critical
					case "normal":
						rec.Severity = severity.Normal
					case "minor":
						rec.Severity = severity.Minor
					case "trivial":
						rec.Severity = severity.Trivial
					default:
						rec.Severity = severity.Normal
					}
				} else if headRow[i] == "body" {
					rec.Body = hval
					////1.创建json数据
					//b := []byte(hval)
					//////2.声明空interface
					//var i interface{}
					////3.解析
					//err := json.Unmarshal(b, &i)
					//rec.Body = i
					//util.Check(err)

				} else if headRow[i][0] == 'a' || headRow[i][0] == 'e' {
					//tmp = strings.Split(headRow[i], ".")
					tmp = strings.SplitN(headRow[i], ".", 2)
					if tmp[0] == "apiPath" { //apiParam
						rec.Paths[tmp[1]] = hval
					} else if tmp[0] == "apiParam" { //apiHeader
						rec.Params[tmp[1]] = hval
					} else if tmp[0] == "apiHeader" {
						rec.Headers[tmp[1]] = hval
					} else if tmp[0] == "expectJson" {
						rec.JsonExpect[tmp[1]] = hval
					} else if tmp[0] == "expectJsonInt" {
						if hval != "" {
							rec.ExpectJsonInt[tmp[1]], err = strconv.Atoi(hval)
							util.Check(err)
						}
					} else if tmp[0] == "expectJsonBoolean" {
						if hval != "" {
							flag := false
							if hval == "1" {
								flag = true
							}
							rec.ExpectJsonBoolean[tmp[1]] = flag
						}
					} else if tmp[0] == "expectJsonExist" {
						if hval != "" {
							flag := false
							if hval == "1" {
								flag = true
							}
							rec.ExpectJsonExist[tmp[1]] = flag
						}
					}
				}
			}
			//fmt.Println(rec)
			recs = append(recs, *rec)
		}
	}
	//util.DebugLog("数据文件解析完毕！")

	return recs
}
