package com.agri.system.service.impl;

import com.agri.common.utils.DateUtils;
import com.agri.system.domain.SysDtuData;
import com.agri.system.domain.vo.UChartsDataView;
import com.agri.system.mapper.SysDtuDataMapper;
import com.agri.system.service.ISysDtuDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;

/**
 * DTU温湿度上报数据Service业务层处理
 *
 * @author agri
 * @date 2025-12-23
 */
@Service
public class SysDtuDataServiceImpl extends ServiceImpl<SysDtuDataMapper, SysDtuData>  implements ISysDtuDataService
{
    @Autowired
    private SysDtuDataMapper sysDtuDataMapper;

    /**
     * 查询DTU温湿度上报数据
     *
     * @param id DTU温湿度上报数据主键
     * @return DTU温湿度上报数据
     */
    @Override
    public SysDtuData selectSysDtuDataById(Long id)
    {
        return sysDtuDataMapper.selectSysDtuDataById(id);
    }

    /**
     * 查询DTU温湿度上报数据列表
     *
     * @param sysDtuData DTU温湿度上报数据
     * @return DTU温湿度上报数据
     */
    @Override
    public List<SysDtuData> selectSysDtuDataList(SysDtuData sysDtuData)
    {
        return sysDtuDataMapper.selectSysDtuDataList(sysDtuData);
    }

    @Override
    public SysDtuData findDtuDataByInfo(SysDtuData sysDtuData)
    {
        return sysDtuDataMapper.findDtuDataByInfo(sysDtuData);
    }


    /**
     * 新增DTU温湿度上报数据
     *
     * @param sysDtuData DTU温湿度上报数据
     * @return 结果
     */
    @Override
    public int insertSysDtuData(SysDtuData sysDtuData)
    {
        sysDtuData.setCreateTime(DateUtils.getNowDate());
        return sysDtuDataMapper.insertSysDtuData(sysDtuData);
    }

    /**
     * 修改DTU温湿度上报数据
     *
     * @param sysDtuData DTU温湿度上报数据
     * @return 结果
     */
    @Override
    public int updateSysDtuData(SysDtuData sysDtuData)
    {
        return sysDtuDataMapper.updateSysDtuData(sysDtuData);
    }

    /**
     * 批量删除DTU温湿度上报数据
     *
     * @param ids 需要删除的DTU温湿度上报数据主键
     * @return 结果
     */
    @Override
    public int deleteSysDtuDataByIds(Long[] ids)
    {
        return sysDtuDataMapper.deleteSysDtuDataByIds(ids);
    }

    /**
     * 删除DTU温湿度上报数据信息
     *
     * @param id DTU温湿度上报数据主键
     * @return 结果
     */
    @Override
    public int deleteSysDtuDataById(Long id)
    {
        return sysDtuDataMapper.deleteSysDtuDataById(id);
    }


    /**
     * 查询指定imei列表中每个imei的最后一条数据（按id倒序，优先用id，自增主键性能最优）
     * @param imeiList 要查询的imei列表
     *                 改造后：添加最后一分钟时间过滤，避免全表扫描
     * @return 每个imei的最后一条数据列表
     */
    @Override
    public List<Map<String, Object>> getLastDtuDataByImeiList(List<String> imeiList) {

        if (imeiList == null || imeiList.isEmpty()) {
            log.error("imeiList列表为空");
            return Collections.emptyList();
        }

        // 3. 执行查询（如果用 ServiceImpl，直接调 list(mainQueryWrapper) 即可）
        return baseMapper.getLastDtuDataByImeiList(imeiList);
    }

    @Override
    public UChartsDataView getHistoryData(String imei, LocalDateTime startTime, LocalDateTime endTime) {
        // 非空校验
        Assert.hasText(imei, "设备IMEI不能为空");

        // 时间参数兜底
        LocalDateTime finalStartTime = ObjectUtils.isEmpty(startTime)
                ? LocalDateTime.of(LocalDate.now(), LocalTime.MIN)
                : startTime;
        LocalDateTime finalEndTime = ObjectUtils.isEmpty(endTime)
                ? LocalDateTime.now()
                : endTime;

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        List<SysDtuData> historyData = baseMapper.getHistoryData(imei, finalStartTime, finalEndTime);
        List<String> categories = new ArrayList<>();
        List<BigDecimal> temp1List = new ArrayList<>();
        List<BigDecimal> temp2List = new ArrayList<>();
        List<BigDecimal> temp3List = new ArrayList<>();
        List<BigDecimal> temp4List = new ArrayList<>();
        List<BigDecimal> humi1List = new ArrayList<>();
        List<BigDecimal> humi2List = new ArrayList<>();
        List<BigDecimal> humi3List = new ArrayList<>();
        List<BigDecimal> humi4List = new ArrayList<>();

        // 工具方法：null转0
        // 一次遍历收集所有数据（性能最优）
        if (CollectionUtils.isNotEmpty(historyData)) {
            historyData.forEach(dtuData -> {
                categories.add(dtuData.getTime().format(formatter));
                temp1List.add(dtuData.getTemp1());
                temp2List.add(dtuData.getTemp2());
                temp3List.add(dtuData.getTemp3());
                temp4List.add(dtuData.getTemp4());
                humi1List.add(dtuData.getHumi1());
                humi2List.add(dtuData.getHumi2());
                humi3List.add(dtuData.getHumi3());
                humi4List.add(dtuData.getHumi4());
            });
        }

        // 设置返回数据
        UChartsDataView uChartsData = new UChartsDataView();
        uChartsData.setCategories(categories);
        uChartsData.setSeries(Arrays.asList(
                new UChartsDataView.UChartsSeries("温度1", true,BigDecimal.ZERO, temp1List),
                new UChartsDataView.UChartsSeries("温度2", true,BigDecimal.ZERO, temp2List),
                new UChartsDataView.UChartsSeries("温度3", true,BigDecimal.ZERO, temp3List),
                new UChartsDataView.UChartsSeries("温度4", true,BigDecimal.ZERO, temp4List),
                new UChartsDataView.UChartsSeries("湿度1", false, BigDecimal.ONE, humi1List),
                new UChartsDataView.UChartsSeries("湿度2", false, BigDecimal.ONE, humi2List),
                new UChartsDataView.UChartsSeries("湿度3", false, BigDecimal.ONE, humi3List),
                new UChartsDataView.UChartsSeries("湿度4", false, BigDecimal.ONE, humi4List)
        ));
        return uChartsData;
    }
}
