package org.eco.als.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import com.ql.util.express.Operator;
import org.eco.common.core.exception.BusinessException;
import org.eco.common.core.utils.DateUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wanggaokun
 */
public class CheckVibrationDuration extends Operator {
    // 线程安全的状态存储：key=振动值，value=首次达到该值的时间戳（毫秒）
    private static final Map<String, Long> VIBRATION_STATE = new HashMap<>();

    @Override
    public Object executeInner(Object[] list) {
        try {
        double currentVibration = (Double) list[0];
        String symbol = list[1].toString();
        double targetVibration = (Double) list[2];
        double durationSeconds = (Double) list[3];
            String curr = (String) list[4];
            FastDateFormat format = FastDateFormat.getInstance(DateUtils.checkTimeFormat(curr));
            long firstTimeDefault = DateUtil.parse(curr, format).getTime();
        boolean result = false;
        switch (symbol) {
            case "=":
                result = currentVibration == targetVibration;
                break;
            case "<":
                result = currentVibration < targetVibration;
                break;
            case ">":
                result = currentVibration > targetVibration;
                break;
            case "<=":
                result = currentVibration <= targetVibration;
                break;
            case ">=":
                result = currentVibration >= targetVibration;
                break;
            case "!=":
                result = currentVibration != targetVibration;
                break;
            default:
        }
        String key = currentVibration + symbol + targetVibration + durationSeconds;
        // 如果当前振动值不等于目标值，清除状态并返回false
        if (!result) {
            VIBRATION_STATE.remove(key);
            return false;
        }
        // 获取或记录首次达到目标值的时间戳
        long firstTime = VIBRATION_STATE.getOrDefault(key, firstTimeDefault);
        VIBRATION_STATE.putIfAbsent(key, firstTime);

        // 计算已持续时间（秒）
        long elapsedSeconds = (firstTimeDefault - firstTime) / 1000;
        // 返回是否满足持续时间要求
        return elapsedSeconds >= durationSeconds;
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }
}
