package main

import (
	"cicv-data-closedloop/pjisuv_msgs"
	"fmt"
	"math"
	"time"
)

var (
	cacheSlice       []float64
	timeWindowLength = 3
	timeWindowBegin  time.Time
)

func Topic() string {
	return "/pj_control_pub"
}

// Label todo 禁止存在下划线_
func Label() string {
	return "CmdStrAngleUnstable"
}

func Rule(data *pjisuv_msgs.CommonVehicleCmd) string {

	// 初始化第一次
	if len(cacheSlice) == 0 {
		cacheSlice = append(cacheSlice, data.ICPVCmdStrAngle)
		timeWindowBegin = time.Now()
		return ""
	}
	// 每3秒判断一次
	if time.Since(timeWindowBegin).Seconds() > float64(timeWindowLength) {
		fmt.Println("已缓存的数据为：", cacheSlice)
		numCount := countSignChange(cacheSlice)
		fmt.Println("抖动次数为：", numCount)
		if numCount > 3 {
			return "CmdStrAngleUnstable"
		}
	}
	return ""
}

func countSignChange(numbers []float64) int {
	var prevSign bool
	var prevValue float64
	count := 0
	if len(numbers) > 1 {
		prevSign = numbers[0] >= 0.0 // 记录前一个数的正负符号
		prevValue = numbers[0]
	}
	for _, num := range numbers[1:] {
		currentSign := num >= 0 // 计算当前数的正负符号
		currentValue := num
		if prevSign != currentSign && (math.Abs(prevValue) > 10 || math.Abs(currentValue) > 10) {
			count += 1
		}
		prevSign = currentSign
	}
	return count
}
