package com.zksy.base.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.base.water.domain.WaterMonitorData;
import com.zksy.base.water.service.WaterMonitorDataService;
import com.zksy.base.water.mapper.WaterMonitorDataMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【water_monitor_data(水位监测数据记录表)】的数据库操作Service实现
* @createDate 2026-01-21 11:15:38
*/
@Service
public class WaterMonitorDataServiceImpl extends ServiceImpl<WaterMonitorDataMapper, WaterMonitorData>
    implements WaterMonitorDataService{
    @Override
    public IPage<WaterMonitorData> selectWaterMonitorDataPage(Page<WaterMonitorData> page, WaterMonitorData waterMonitorData) {
        LambdaQueryWrapper<WaterMonitorData> queryWrapper = new LambdaQueryWrapper<>();
        // 设备编码模糊查询
        if (waterMonitorData.getDeviceCode() != null && !waterMonitorData.getDeviceCode().isEmpty()) {
            queryWrapper.like(WaterMonitorData::getDeviceCode, waterMonitorData.getDeviceCode());
        }
        // 数据类型筛选
        if (waterMonitorData.getDataType() != null && !waterMonitorData.getDataType().isEmpty()) {
            queryWrapper.eq(WaterMonitorData::getDataType, waterMonitorData.getDataType());
        }
        // 按创建时间降序排列
        queryWrapper.orderByDesc(WaterMonitorData::getCreateTime);
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Map<String, Object>> statisticsByDevice(LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.statisticsByDevice(startTime, endTime);
    }

    @Override
    public IPage<WaterMonitorData> selectOverLimitData(Page<WaterMonitorData> page, String threshold,
                                                       LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.selectOverLimitData(page, threshold, startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> statisticsOnlineDevice(LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.statisticsOnlineDevice(startTime, endTime);
    }

    @Override
    public List<WaterMonitorData> getLatestDataByDevice() {
        // 子查询获取每个设备最新的记录ID
        String sql = "SELECT MAX(id) FROM water_monitor_data GROUP BY device_code";
        LambdaQueryWrapper<WaterMonitorData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.inSql(WaterMonitorData::getId, sql);
        return baseMapper.selectList(queryWrapper);
    }
}




