package com.zksy.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.api.domain.WarningThreshold;
import com.zksy.api.mapper.WarningThresholdMapper;
import com.zksy.api.service.WarningThresholdService;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
* @author Administrator
* @description 针对表【warning_threshold(预警阈值)】的数据库操作Service实现
* @createDate 2025-09-01 09:59:43
*/
@Service
public class WarningThresholdServiceImpl extends ServiceImpl<WarningThresholdMapper, WarningThreshold>
    implements WarningThresholdService{
    /**
     * 根据设备编号查询该设备所有预警值
     * device_code 字段支持多个设备编号，用逗号分隔
     */
    @Override
    public WarningThreshold getWarningThresholdByDeviceAndCode(String deviceCode, String warningCodes) {
        LambdaQueryWrapper<WarningThreshold> lambdaQueryWrapper = Wrappers.lambdaQuery(WarningThreshold.class)
                .apply("CONCAT(',', device_code, ',') LIKE CONCAT('%,', {0}, ',%')", deviceCode)
                .eq(WarningThreshold::getWarningCode,warningCodes);

        List<WarningThreshold> thresholds = baseMapper.selectList(lambdaQueryWrapper);
        if (thresholds == null || thresholds.isEmpty()) {
            return null;
        }
        // 分时阈值支持：同一设备+预警编码可配置多条不同生效时段阈值，
        // 优先返回当前时间生效的阈值；未命中分时时段时返回全天阈值（无分时字段），
        // 两者都没有时返回第一条。
        String now = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
        WarningThreshold fullDayThreshold = null;
        for (WarningThreshold threshold : thresholds) {
            boolean hasPeriod = threshold.getPeriodStart() != null && !threshold.getPeriodStart().isEmpty()
                    && threshold.getPeriodEnd() != null && !threshold.getPeriodEnd().isEmpty();
            if (!hasPeriod) {
                if (fullDayThreshold == null) {
                    fullDayThreshold = threshold;
                }
                continue;
            }
            if (now.compareTo(threshold.getPeriodStart()) >= 0 && now.compareTo(threshold.getPeriodEnd()) <= 0) {
                return threshold;
            }
        }
        return fullDayThreshold != null ? fullDayThreshold : thresholds.get(0);
    }
}




