package Fhumptrend

import (
	"fmt"
	"github.com/xuri/excelize/v2"
	"math"
	"strconv"
	"testing"
	"time"
)

// TaskData 结构体
type TaskData struct {
	T_t    float32   // 温度℃
	T_time time.Time // 记录时间
}

// 加载 Excel 数据
func loadExcelData(filePath string) ([]TaskData, error) {
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		return nil, err
	}

	rows, err := f.GetRows("Sheet1")
	if err != nil {
		return nil, err
	}

	var data []TaskData
	for _, row := range rows {
		if len(row) < 2 {
			continue
		}

		temp := row[0]
		timeStr := row[1]

		tempFloat, err := parseFloat32(temp)
		if err != nil {
			continue
		}

		// 修改时间格式为 "2006-01-02 15:04:05"
		timeTime, err := time.Parse("2006-01-02 15:04:05", timeStr)
		if err != nil {
			continue
		}

		data = append(data, TaskData{
			T_t:    tempFloat,
			T_time: timeTime,
		})
	}

	return data, nil
}

// 解析字符串为 float32
func parseFloat32(s string) (float32, error) {
	f, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return 0, err
	}
	// 四舍五入到1位小数
	rounded := math.Round(f*10) / 10
	return float32(rounded), nil
}

// 计算驼峰趋势
func calculateHumps(data []TaskData) []map[string]interface{} {
	var humps []map[string]interface{}
	n := len(data)
	if n < 3 {
		return humps
	}

	i := 0
	for i < n-5 {
		// 寻找开始的最低点
		for !(data[i].T_t <= data[i+1].T_t && data[i+1].T_t <= data[i+2].T_t) {
			i++
			if i > n-5 {
				break
			}
		}
		start := i

		// 寻找最高点
		for !(data[i].T_t >= data[i+1].T_t && data[i+1].T_t > data[i+2].T_t && data[i+2].T_t > data[i+3].T_t) {
			i++
			if i > n-5 {
				break
			}
		}
		peak := i
		Abs_peak := math.Abs(float64(data[start].T_t - data[peak].T_t))
		if Abs_peak < 0.2 {
			continue
		}

		// 寻找结束的最低点
		for !(data[i].T_t <= data[i+1].T_t && data[i+1].T_t < data[i+2].T_t && data[i+2].T_t < data[i+3].T_t) {
			i++
			if i > n-5 {
				break
			}
		}
		end := i
		Abs_end := math.Abs(float64(data[end].T_t - data[peak].T_t))
		if Abs_end < 0.3 {
			continue
		}

		// 如果找到了一个完整的驼峰
		if start < peak && peak < end {
			humps = append(humps, map[string]interface{}{
				"start": data[start],
				"peak":  data[peak],
				"end":   data[end],
			})
		}
		i = peak //
	}

	return humps
}

// 测试函数
func TestBeego(t *testing.T) {
	filePath := "20250314134901.xlsx"
	data, err := loadExcelData(filePath)
	if err != nil {
		t.Fatalf("Failed to load Excel data: %v", err)
	}

	humps := calculateHumps(data)
	for _, hump := range humps {
		start := hump["start"].(TaskData)
		peak := hump["peak"].(TaskData)
		end := hump["end"].(TaskData)
		fmt.Printf("Hump: Start(T_t: %.2f, T_time: %s) -> Peak(T_t: %.2f, T_time: %s) -> End(T_t: %.2f, T_time: %s)\n",
			start.T_t, start.T_time.Format("2006-01-02 15:04:05"),
			peak.T_t, peak.T_time.Format("2006-01-02 15:04:05"),
			end.T_t, end.T_time.Format("2006-01-02 15:04:05"))
	}
}
