package data

import (
	"server/dao"
	"time"
)

type ProcessedPowerData struct {
	TotalActivePower float64
	UploadTime       time.Time
}

func parseTime(uploadTimeString string) (time.Time, error) {
	parsedTime, err := time.Parse("2006-01-02 15:04:05", uploadTimeString)
	if err != nil {
		return time.Time{}, err
	}
	return parsedTime, nil
}

func PreprocessData(data []dao.InductanceDetails) ([]ProcessedPowerData, error) {
	processedData := make([]ProcessedPowerData, len(data))
	for i, d := range data {
		t, err := parseTime(d.UploadTime)
		if err != nil {
			return nil, err
		}
		processedData[i] = ProcessedPowerData{
			TotalActivePower: float64(d.TotalActivePower),
			UploadTime:       t,
		}
	}
	return processedData, nil
}

func CalculateDailyEnergyConsumption(data []ProcessedPowerData) float64 {
	if len(data) < 2 {
		// 如果数据不足，根据实际情况返回值或进行估算
		return 0 // 或者其它逻辑
	}
	var totalEnergy float64 = 0

	for i := 0; i < len(data)-1; i++ {
		current := data[i]
		next := data[i+1]

		duration := next.UploadTime.Sub(current.UploadTime).Minutes() // 时间差（分钟）

		if duration > 10 { // 如果间隔超过10分钟，则用最后一次上报的功率估算缺失部分
			missingIntervals := int(duration / 10)
			for j := 0; j < missingIntervals; j++ {
				totalEnergy += (current.TotalActivePower * 10 / 60 / 1000) // 计算每个10分钟的能量消耗
			}
		} else {
			energy := ((current.TotalActivePower + next.TotalActivePower) / 2) * duration / 60 / 1000 // 平均功率乘以时间转换为kW·h
			totalEnergy += energy
		}
	}

	return totalEnergy
}
