package com.zcxk.charge.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zcxk.charge.api.vo.DeviceVo;
import com.zcxk.charge.api.vo.ReprotWaterPumpVo;
import com.zcxk.charge.core.dao.ReportWaterPumpStateMapper;
import com.zcxk.charge.api.dto.DeviceDto;
import com.zcxk.charge.api.dto.watepump.ReprotWaterPumpQueryDto;
import com.zcxk.charge.web.service.DeviceService;
import com.zcxk.charge.web.service.ReportWaterPumpStateService;
import com.zcxk.core.oauth2.util.UserUtil;
import com.zcxk.core.utils.DateUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
/**
 * @author  andy
 */
@Service
@Log4j2
public class ReportWaterPumpStateServiceImpl implements ReportWaterPumpStateService {

    @Autowired
    private ReportWaterPumpStateMapper reportWaterPumpStateMapper;

    @Autowired
    private DeviceService deviceService;

    @Override
    public List<ReprotWaterPumpVo> findReportWaterPumpStateList(Long sceneId, List<Long> sceneIds, Integer days) {
        // 查询场景下的所有设备信息
        List<DeviceVo> devices = new ArrayList<>();
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setSceneIds(sceneIds);
        if (deviceDto.getSceneIds().size() > 0){
            devices.addAll(deviceService.selectList(deviceDto));
        }
        ReprotWaterPumpQueryDto queryDto = new ReprotWaterPumpQueryDto();
        queryDto.setDeviceIds(devices);
        queryDto.setTenantId(UserUtil.getCurrentUser().getTenantId());
        queryDto.setBeginTime(DateUtil.formatDate(DateUtil.addDayOfDate(new Date(), -(days-1)),"yyyy-MM-dd") + " 00:00:00");
        queryDto.setSceneId(sceneId);
        List<ReprotWaterPumpVo>  result = reportWaterPumpStateMapper.findReportWaterPumpStateList(queryDto);
        if (CollectionUtil.isEmpty(result)) {
            return result;
        }
        Comparator<ReprotWaterPumpVo> byYear  = Comparator.comparing(ReprotWaterPumpVo::getYear);
        Comparator<ReprotWaterPumpVo> byMonth = Comparator.comparing(ReprotWaterPumpVo::getMonth);
        Comparator<ReprotWaterPumpVo> byDay   = Comparator.comparing(ReprotWaterPumpVo::getDay);
        Collections.sort(result, byYear.thenComparing(byMonth.thenComparing(byDay)));
        return result;
    }
}
