package com.shzg.project.worn.service.impl;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.shzg.common.utils.DateUtils;
import com.shzg.common.utils.DeptScopeUtils;
import com.shzg.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shzg.project.worn.mapper.MqttSensorThresholdMapper;
import com.shzg.project.worn.domain.MqttSensorThreshold;
import com.shzg.project.worn.service.IMqttSensorThresholdService;

/**
 * 传感器阈值配置Service业务层处理（最终版）
 *
 * 规则：
 * 1. 设备优先
 * 2. 仓库兜底
 * 3. 统一入口（无旧方法）
 */
@Service
public class MqttSensorThresholdServiceImpl implements IMqttSensorThresholdService
{
    /**
     * 阈值缓存
     * key: deviceId:deptId:metric
     */
    private final ConcurrentMap<String, Optional<MqttSensorThreshold>> thresholdCache = new ConcurrentHashMap<>();

    @Autowired
    private MqttSensorThresholdMapper mqttSensorThresholdMapper;

    // ==================== 基础CRUD ====================

    @Override
    public MqttSensorThreshold selectMqttSensorThresholdById(Long id)
    {
        return mqttSensorThresholdMapper.selectMqttSensorThresholdById(id);
    }

    @Override
    public List<MqttSensorThreshold> selectMqttSensorThresholdList(MqttSensorThreshold mqttSensorThreshold)
    {
        if (!SecurityUtils.isAdmin())
        {
            mqttSensorThreshold.setDeptIds(DeptScopeUtils.getDeptScope());
        }
        return mqttSensorThresholdMapper.selectMqttSensorThresholdList(mqttSensorThreshold);
    }

    @Override
    public int insertMqttSensorThreshold(MqttSensorThreshold mqttSensorThreshold)
    {
        mqttSensorThreshold.setCreateTime(DateUtils.getNowDate());
        int rows = mqttSensorThresholdMapper.insertMqttSensorThreshold(mqttSensorThreshold);
        clearThresholdCache();
        return rows;
    }

    @Override
    public int updateMqttSensorThreshold(MqttSensorThreshold mqttSensorThreshold)
    {
        mqttSensorThreshold.setUpdateTime(DateUtils.getNowDate());
        int rows = mqttSensorThresholdMapper.updateMqttSensorThreshold(mqttSensorThreshold);
        clearThresholdCache();
        return rows;
    }

    @Override
    public int deleteMqttSensorThresholdByIds(Long[] ids)
    {
        int rows = mqttSensorThresholdMapper.deleteMqttSensorThresholdByIds(ids);
        clearThresholdCache();
        return rows;
    }

    @Override
    public int deleteMqttSensorThresholdById(Long id)
    {
        int rows = mqttSensorThresholdMapper.deleteMqttSensorThresholdById(id);
        clearThresholdCache();
        return rows;
    }
    /**
     * 获取阈值（设备优先 → 仓库兜底）
     */
    @Override
    public MqttSensorThreshold getThreshold(Long deviceId, Long deptId, String metricType)
    {
        if (metricType == null || metricType.trim().isEmpty()) {
            return null;
        }

        String cacheKey = buildCacheKey(deviceId, deptId, metricType);

        Optional<MqttSensorThreshold> cached = thresholdCache.computeIfAbsent(cacheKey, key -> {

            // 1️⃣ 设备优先
            if (deviceId != null) {
                MqttSensorThreshold t =
                        mqttSensorThresholdMapper.selectByDeviceAndMetric(deviceId, metricType);
                if (t != null) {
                    return Optional.of(t);
                }
            }

            // 2️⃣ 仓库兜底
            if (deptId != null) {
                MqttSensorThreshold t =
                        mqttSensorThresholdMapper.selectByDeptAndMetric(deptId, metricType);
                if (t != null) {
                    return Optional.of(t);
                }
            }

            // 3️⃣ 未配置
            return Optional.empty();
        });

        return cached.orElse(null);
    }

    // ==================== 工具方法 ====================

    private String buildCacheKey(Long deviceId, Long deptId, String metricType)
    {
        return (deviceId == null ? "0" : deviceId)
                + ":" +
                (deptId == null ? "0" : deptId)
                + ":" +
                metricType.trim().toLowerCase();
    }

    private void clearThresholdCache()
    {
        thresholdCache.clear();
    }
}