package com.tofly.custom.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.constant.CalendarHelper;
import com.tofly.common.constant.Constant;
import com.tofly.custom.entity.dto.ScadaReportDto;
import com.tofly.custom.entity.dto.StartEndTimeDto;
import com.tofly.custom.entity.dto.WisdomDisplayDto;
import com.tofly.custom.entity.vo.*;
import com.tofly.custom.mapper.CustomDisplayMapper;
import com.tofly.custom.service.CustomDisplayService;
import com.tofly.scada.common.DateTimeUtil;
import com.tofly.scada.entity.DeviceArchiveManage;
import com.tofly.scada.entity.ScadaReport;
import com.tofly.scada.entity.TfWaterInfo;
import com.tofly.scada.handle.ScadaHandler;
import com.tofly.scada.mapper.AllocationMapper;
import com.tofly.scada.service.DeviceArchiveManageService;
import com.tofly.scada.service.ScadaReportService;
import com.tofly.scada.service.TfWaterInfoService;
import com.tofly.water.mapper.OverviewMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class CustomDisplayServiceImpl implements CustomDisplayService {

    private final CustomDisplayMapper customDisplayMapper;
    private final ScadaReportService scadaReportService;
    private final DeviceArchiveManageService deviceService;
    private final TfWaterInfoService tfWaterInfoService;
    private final AllocationMapper allocationMapper;
    private final OverviewMapper overviewMapper;
    private final ScadaHandler scadaHandler;

    private static final Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]*");

    /**
     * 设置水厂，污水今日/昨日厂进水，出水数据
     *
     * @param waterStationVo
     * @param codesJin
     * @param codesChu
     */
    public void setWaterSupplyInfo(WaterStationVo waterStationVo, String codesJin, String codesChu) {
        List<String> listJin = overviewMapper.getWaterAllocation(waterStationVo.getId(), codesJin, "1");
        List<String> listChu = overviewMapper.getWaterAllocation(waterStationVo.getId(), codesChu, "0");
        String strJin = listJin.stream().collect(Collectors.joining(","));
        String strChu = listChu.stream().collect(Collectors.joining(","));

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 6);
        String endHour = CalendarHelper.getFormatDate(calendar.getTime(), "yyyyMMdd HH");
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        String startHour = CalendarHelper.getFormatDate(calendar.getTime(), "yyyyMMdd HH");
        Map<String, Object> map = overviewMapper.waterSupplyDayReport(startHour, endHour, null, waterStationVo.getId(), strJin, strChu);
        if (map != null) {
            String waterChuTotal = map.get("waterChuTotal") != null ? String.valueOf(map.get("waterChuTotal")):"0.0";
            String waterJinTotal = map.get("waterJinTotal") != null ? String.valueOf(map.get("waterJinTotal")):"0.0";
            waterStationVo.setTodayWaterSupply(Double.parseDouble(waterChuTotal));
            waterStationVo.setTodayWaterUser(Double.parseDouble(waterJinTotal));
        }
        //昨天的数据
        String endHourYesterday = CalendarHelper.getFormatDate(calendar.getTime(), "yyyyMMdd HH");
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        String startHourYesterday = CalendarHelper.getFormatDate(calendar.getTime(), "yyyyMMdd HH");
        Map<String, Object> map_yes = overviewMapper.waterSupplyDayReport(startHourYesterday, endHourYesterday, null, waterStationVo.getId(), strJin, strChu);
        if (map_yes != null) {
            String waterChuTotal = map_yes.get("waterChuTotal") != null ? String.valueOf(map_yes.get("waterChuTotal")):"0.0";
            String waterJinTotal = map_yes.get("waterJinTotal") != null ? String.valueOf(map_yes.get("waterJinTotal")):"0.0";
            waterStationVo.setYesterdayWaterSupply(Double.parseDouble(waterChuTotal));
            waterStationVo.setYesterdayWaterUser(waterJinTotal != null ? Double.parseDouble(waterJinTotal):0.0);
        }

    }

    @Override
    public List<WaterStationVo> viewStationDeviceIndex(WisdomDisplayDto wis, String codesJin, String codesChu) {
        Integer statisticsType = wis.getStatisticsType();
        Integer tableType = wis.getTableType();
        String isQueryDevice = wis.getIsQueryDevice();
        String isQueryAlarm = wis.getIsQueryAlarm();
        if (tableType == null) {
            wis.setTableType(1);
        }
        if (statisticsType == null) {
            wis.setStatisticsType(0);
        }
        if (StringUtils.isBlank(isQueryDevice)) {
            isQueryDevice = "0";
        }
        if (StringUtils.isBlank(isQueryAlarm)) {
            isQueryAlarm = "0";
        }

        List<WaterStationVo> stationInfoVos = customDisplayMapper.getWaterStationInfo(wis);
        if (CollUtil.isEmpty(stationInfoVos)) {
            return null;
        }
        List<Long> waterIds = stationInfoVos.stream().map(TfWaterInfo::getId).collect(Collectors.toList());
        wis.setWaterStationIds(waterIds);
        // 获取所有设备列表
        List<DeviceArchiveManage> deviceList = null;
        if (isQueryDevice.equals("1")) {
            deviceList = deviceService.list(new QueryWrapper<DeviceArchiveManage>()
                    .isNotNull("WATER_ID")
                    .in(CollUtil.isNotEmpty(wis.getDeviceCodes()), "CODE", wis.getDeviceCodes())
                    .in(CollUtil.isNotEmpty(wis.getWaterStationIds()), "WATER_ID", wis.getWaterStationIds())
                    .like(StringUtils.isNotBlank(wis.getDeviceName()), "NAME", wis.getDeviceName()));
        }


        // 获取所有厂站今日供水量
      /*  WisdomDisplayDto wisToday = new WisdomDisplayDto();
        wisToday.setTableType(3);
        wisToday.setStartDate(DateUtil.format(new Date(), "yyyy-MM-dd") + " 00:00:00");
        wisToday.setEndDate(DateUtil.format(new Date(), "yyyy-MM-dd") + " 23:59:59");
        wisToday.setIndexType(IndexTypeDictEnum.CUM_POS_FLOW.getType());
        wisToday.setWaterStationIds(wis.getWaterStationIds());
        List<ScadaIndexVo> stationIndexVos = customDisplayMapper.getScadaIndexData(wisToday);
        Map<Long, List<ScadaIndexVo>> stationVos = stationIndexVos.stream().collect(Collectors.groupingBy(ScadaIndexVo::getWaterId, Collectors.toList()));
*/
        List<ScadaIndexVo> indexListAll = customDisplayMapper.getScadaIndexData(wis);
        List<ScadaReport> scadaReportList = scadaReportService.list();
        for (WaterStationVo one : stationInfoVos) {
            setWaterSupplyInfo(one, codesJin, codesChu);
            // 获取当前厂站今日供水量
           /*  BigDecimal todayWaterSupply =new BigDecimal(0);
            WaterSupplyVo vo= waterSupplyVos.stream().filter(item->item.getWaterId().equals(one.getId())).findFirst().orElse(null);
             if(vo!=null){
                 todayWaterSupply=vo.getWaterSupplyDay();
             }
           double todayWaterSupply = 0.0;
            if (CollUtil.isNotEmpty(stationVos) && CollUtil.isNotEmpty(stationVos.get(one.getId()))) {
                List<ScadaIndexVo> stationCumFlowVos = stationVos.get(one.getId());
                if (CollUtil.isNotEmpty(stationCumFlowVos)) {
                    BigDecimal startVal = new BigDecimal(stationCumFlowVos.get(stationCumFlowVos.size() - 1).getIndexValue());
                    BigDecimal endVal = new BigDecimal(stationCumFlowVos.get(0).getIndexValue());
                    if (endVal.compareTo(startVal) > 0) {
                        todayWaterSupply = endVal.subtract(startVal).doubleValue();
                    }
                }
            }
            one.setTodayWaterSupply(todayWaterSupply);
*/
            if (isQueryDevice.equals("0")) {
                continue;
            }

            // 获取当前厂站的所有设备
            if (CollUtil.isEmpty(deviceList)) {
                continue;
            }
            List<DeviceArchiveManage> deviceListFinal = deviceList.stream()
                    .filter(e -> e.getWaterId() == Long.parseLong(String.valueOf(one.getId())))
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(deviceListFinal)) {
                continue;
            }
            for (DeviceArchiveManage device : deviceListFinal) {
                // 获取当前设备的所有指标
                List<ScadaIndexVo> indexListFinal = indexListAll.stream().filter(e -> Objects.equals(e.getDeviceId(), device.getId())).collect(Collectors.toList());
                if (CollUtil.isEmpty(indexListFinal)) {
                    continue;
                }
                if (isQueryAlarm.equals("0")) {
                    device.setIndexList(indexListFinal);
                    continue;
                }
                // 获取指标报警信息
                for (ScadaIndexVo index : indexListFinal) {
                    index.setIsAlarm("0");
                    if (StringUtils.isBlank(index.getReportIds())) {
                        continue;
                    }
                    List<Long> reportIdList = Arrays.stream(index.getReportIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
                    List<ScadaReport> reportList = scadaReportList.stream().filter(e -> reportIdList.contains(e.getId())).collect(Collectors.toList());
                    if (CollUtil.isEmpty(reportList)) {
                        continue;
                    }
                    for (ScadaReport report : reportList) {
                        Double value = Double.parseDouble(index.getIndexValue());
                        Double lower = Double.parseDouble(report.getReportLower());
                        Double upper = Double.parseDouble(report.getReportUpper());
                        if (value.compareTo(upper) <= 0 && value.compareTo(lower) >= 0) {
                            index.setIsAlarm("1");
                            index.setReportLevel(report.getReportLevel());
                            index.setReportLower(report.getReportLower());
                            index.setReportUpper(report.getReportUpper());
                        }
                    }
                }
                device.setIndexList(indexListFinal);
            }
            one.setDeviceList(deviceListFinal);
        }
        return stationInfoVos;
    }

    @Override
    public List<WaterStationVo> viewStationIndex(WisdomDisplayDto wis, String codesJin, String codesChu) {
        Integer statisticsType = wis.getStatisticsType();
        Integer tableType = wis.getTableType();
        String isQueryIndex = wis.getIsQueryIndex();
        String isQueryAlarm = wis.getIsQueryAlarm();
        if (tableType == null) {
            wis.setTableType(1);
        }
        if (statisticsType == null) {
            wis.setStatisticsType(0);
        }
        if (StringUtils.isBlank(isQueryIndex)) {
            isQueryIndex = "0";
        }
        if (StringUtils.isBlank(isQueryAlarm)) {
            isQueryAlarm = "0";
        }

        List<WaterStationVo> stationInfoVos = customDisplayMapper.getWaterStationInfo(wis);
        if (CollUtil.isEmpty(stationInfoVos)) {
            return null;
        }

        // 获取所有水厂今日供水量
       /* WisdomDisplayDto wisToday = new WisdomDisplayDto();
        wisToday.setTableType(3);
        wisToday.setStartDate(DateUtil.format(new Date(), "yyyy-MM-dd") + " 00:00:00");
        wisToday.setEndDate(DateUtil.format(new Date(), "yyyy-MM-dd") + " 23:59:59");
        wisToday.setIndexType(IndexTypeDictEnum.CUM_POS_FLOW.getType());
        List<ScadaIndexVo> stationIndexVos = customDisplayMapper.getScadaIndexData(wisToday);
        Map<Long, List<ScadaIndexVo>> stationVos = stationIndexVos.stream().collect(Collectors.groupingBy(ScadaIndexVo::getWaterId, Collectors.toList()));
*/
        List<ScadaIndexVo> indexListAll = customDisplayMapper.getScadaIndexData(wis);
        List<ScadaReport> scadaReportList = scadaReportService.list();
        for (WaterStationVo one : stationInfoVos) {
            setWaterSupplyInfo(one, codesJin, codesChu);
            /*// 获取当前水厂今日供水量
            double todayWaterSupply = 0.0;
            if (CollUtil.isNotEmpty(stationVos) && CollUtil.isNotEmpty(stationVos.get(one.getId()))) {
                List<ScadaIndexVo> stationCumFlowVos = stationVos.get(one.getId());
                if (CollUtil.isNotEmpty(stationCumFlowVos)) {
                    BigDecimal startVal = new BigDecimal(stationCumFlowVos.get(stationCumFlowVos.size() - 1).getIndexValue());
                    BigDecimal endVal = new BigDecimal(stationCumFlowVos.get(0).getIndexValue());
                    if (endVal.compareTo(startVal) > 0) {
                        todayWaterSupply = endVal.subtract(startVal).doubleValue();
                    }
                }
            }
            one.setTodayWaterSupply(todayWaterSupply);*/

            if (isQueryIndex.equals("0")) {
                continue;
            }

            // 获取当前水厂的所有指标
            List<ScadaIndexVo> indexListFinal = indexListAll.stream().filter(e -> Objects.equals(e.getWaterId(), one.getId())).collect(Collectors.toList());
            if (CollUtil.isEmpty(indexListFinal)) {
                continue;
            }
            if (isQueryAlarm.equals("0")) {
                one.setIndexList(indexListFinal);
                continue;
            }
            // 获取指标报警信息
            for (ScadaIndexVo index : indexListFinal) {
                index.setIsAlarm("0");
                if (StringUtils.isBlank(index.getReportIds())) {
                    continue;
                }
                List<Long> reportIdList = Arrays.stream(index.getReportIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
                List<ScadaReport> reportList = scadaReportList.stream().filter(e -> reportIdList.contains(e.getId())).collect(Collectors.toList());
                if (CollUtil.isEmpty(reportList)) {
                    continue;
                }
                for (ScadaReport report : reportList) {
                    Double value = Double.parseDouble(index.getIndexValue());
                    Double lower = Double.parseDouble(report.getReportLower());
                    Double upper = Double.parseDouble(report.getReportUpper());
                    if (value.compareTo(upper) <= 0 && value.compareTo(lower) >= 0) {
                        index.setIsAlarm("1");
                        index.setReportLevel(report.getReportLevel());
                        index.setReportLower(report.getReportLower());
                        index.setReportUpper(report.getReportUpper());
                    }
                }
            }
            one.setIndexList(indexListFinal);
        }
        return stationInfoVos;
    }

    @Override
    public List<DeviceArchiveManage> viewDeviceIndex(WisdomDisplayDto wis) {
        Integer statisticsType = wis.getStatisticsType();
        List<DeviceByTypeVo> voList = customDisplayMapper.getDeviceType();
        Integer tableType = wis.getTableType();
        String isQueryAlarm = wis.getIsQueryAlarm();
        String isQueryIndex = wis.getIsQueryIndex();
        if (tableType == null) {
            wis.setTableType(1);
        }
        if (statisticsType == null) {
            wis.setStatisticsType(0);
        }
        if (StringUtils.isBlank(isQueryAlarm)) {
            isQueryAlarm = "0";
        }
        if (StringUtils.isBlank(isQueryIndex)) {
            isQueryIndex = "0";
        }


        // 获取所有设备列表
        LambdaQueryWrapper<DeviceArchiveManage> wrapper = Wrappers.<DeviceArchiveManage>lambdaQuery()
                .in(CollUtil.isNotEmpty(wis.getDeviceCodes()), DeviceArchiveManage::getCode, wis.getDeviceCodes())
                .in(CollUtil.isNotEmpty(wis.getDeviceStatusList()), DeviceArchiveManage::getStatus, wis.getDeviceStatusList())
                .in(CollUtil.isNotEmpty(wis.getTypes()), DeviceArchiveManage::getType, wis.getTypes())
                .in(CollUtil.isNotEmpty(wis.getDeviceIds()), DeviceArchiveManage::getId, wis.getDeviceIds())
                .in(CollUtil.isNotEmpty(wis.getWaterStationIds()), DeviceArchiveManage::getWaterId, wis.getWaterStationIds())
                .like(StringUtils.isNotBlank(wis.getDeviceName()), DeviceArchiveManage::getName, wis.getDeviceName());
        if (StringUtils.isNotBlank(wis.getLikeStr()) && wis.getSearchOption() == 1) {
            wrapper.nested(x -> x.like(DeviceArchiveManage::getName, wis.getLikeStr()).or().
                    like(DeviceArchiveManage::getManufacturer, wis.getLikeStr()).or().
                    like(DeviceArchiveManage::getPhone, wis.getLikeStr()).or().
                    like(DeviceArchiveManage::getModelSpecification, wis.getLikeStr()).or().
                    like(DeviceArchiveManage::getCode, wis.getLikeStr()).or().
                    like(DeviceArchiveManage::getAddress, wis.getLikeStr()).or().
                    like(DeviceArchiveManage::getDescribe, wis.getLikeStr()));
        }
        List<DeviceArchiveManage> deviceList = deviceService.list(wrapper);
        for (DeviceArchiveManage device : deviceList) {
            DeviceByTypeVo vo = voList.stream().filter(item -> item.getDeviceType().equals(device.getDeviceType())).findFirst().orElse(null);
            if (vo != null) {
                device.setDeviceTypeName(vo.getDeviceTypeName());
            }
        }
        if (isQueryIndex.equals("0")) {
            return deviceList;
        }


        List<ScadaIndexVo> indexListAll = customDisplayMapper.getScadaIndexData(wis);
        List<ScadaReport> scadaReportList = scadaReportService.list();
        for (DeviceArchiveManage device : deviceList) {
            // 获取当前设备的所有指标

            List<ScadaIndexVo> indexListFinal = indexListAll.stream().filter(e -> Objects.equals(e.getDeviceId(), device.getId())).collect(Collectors.toList());
            if (CollUtil.isEmpty(indexListFinal)) {
                continue;
            }
            if (isQueryAlarm.equals("0")) {
                device.setIndexList(indexListFinal);
                continue;
            }
            // 获取指标报警信息
            for (ScadaIndexVo index : indexListFinal) {
                index.setIsAlarm("0");
                if (StringUtils.isBlank(index.getReportIds())) {
                    continue;
                }
                List<Long> reportIdList = Arrays.stream(index.getReportIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
                List<ScadaReport> reportList = scadaReportList.stream().filter(e -> reportIdList.contains(e.getId())).collect(Collectors.toList());
                if (CollUtil.isEmpty(reportList)) {
                    continue;
                }

                for (ScadaReport report : reportList) {
                    Double value = Double.parseDouble(index.getIndexValue());
                    Double lower = Double.parseDouble(report.getReportLower());
                    Double upper = Double.parseDouble(report.getReportUpper());
                    if (value.compareTo(upper) <= 0 && value.compareTo(lower) >= 0) {
                        index.setIsAlarm("1");
                        index.setReportLevel(report.getReportLevel());
                        index.setReportLower(report.getReportLower());
                        index.setReportUpper(report.getReportUpper());
                    }
                }
            }
            device.setIndexList(indexListFinal);
            if (CollUtil.isNotEmpty(wis.getReportLevels())) {
                List<ScadaIndexVo> searchIndexVo = new ArrayList<>();
                for (String reportLevels : wis.getReportLevels()) {
                    List<ScadaIndexVo> result = indexListFinal.stream().filter(item -> StringUtils.isNotEmpty(item.getReportLevel())
                            && item.getReportLevel().contains(reportLevels)).collect(Collectors.toList());
                    searchIndexVo.addAll(result);
                }
                device.setIndexList(searchIndexVo);
            }
            if (CollUtil.isNotEmpty(wis.getIndexAlarmStatus())) {
                indexListFinal = device.getIndexList();
                List<ScadaIndexVo> searchIndexVo = new ArrayList<>();
                for (String alarmStatus : wis.getIndexAlarmStatus()) {
                    List<ScadaIndexVo> result = indexListFinal.stream().filter(item -> StringUtils.isNotEmpty(item.getIsAlarm())
                            && item.getIsAlarm().equals(alarmStatus)).collect(Collectors.toList());
                    searchIndexVo.addAll(result);
                }
                device.setIndexList(searchIndexVo);
            }
        }
        return deviceList;
    }


    @Override
    public List<WaterSourceScadaVo> getWaterSourceScada(String startDate, String endDate, String indexTypes) {
        List<Long> indexTypeList = null;
        if (StringUtils.isNotBlank(indexTypes)) {
            indexTypeList = Arrays.stream(indexTypes.split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }
        return customDisplayMapper.getWaterSourceScada(startDate, endDate, indexTypeList);
    }

    @Override
    public IndexValCensusVo indexValCensus() {
        IndexValCensusVo res = new IndexValCensusVo();
        // 计算水厂总数
        res.setWaterStationTotal(customDisplayMapper.getWaterStationCount("1"));
        // 计算加压站总数
        res.setPressurizeStationTotal(customDisplayMapper.getWaterStationCount("2"));
        // 计算总户数
        res.setTableUserTotal(customDisplayMapper.getTableUserNum());
        // 计算管网总长度
        List<PipeMaterialCensusVo> pipeMaterialCensusVos = customDisplayMapper.getPipeMaterialCensus();
        BigDecimal pipeLength = BigDecimal.ZERO;
        for (PipeMaterialCensusVo one : pipeMaterialCensusVos) {
            if (one.getNum() != null) {
                pipeLength = pipeLength.add(one.getNum());
            }
        }
        res.setPipeTotalLength(pipeLength);
        // 计算设计供水能力
        res.setDesignProcessingCapacity(customDisplayMapper.getDesignProcessCapacity(null).divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_UP));
        return res;
    }

    @Override
    public List<ScadaIndexVo> getScadaIndexData(WisdomDisplayDto dto) {
        Integer statisticsType = dto.getStatisticsType();
        Integer tableType = dto.getTableType();
        String isQueryAlarm = dto.getIsQueryAlarm();
        if (tableType == null) {
            dto.setTableType(1);
        }
        if (statisticsType == null) {
            dto.setStatisticsType(0);
        }
        if (StringUtils.isBlank(isQueryAlarm)) {
            isQueryAlarm = "0";
        }

        List<ScadaIndexVo> scadaIndexVoList = customDisplayMapper.getScadaIndexData(dto);
        if (isQueryAlarm.equals("0")) {
            return scadaIndexVoList;
        }
        for (ScadaIndexVo scadaIndexVo : scadaIndexVoList) {
            scadaIndexVo.setTimeRange(dto.getStartDate() + "-" + dto.getEndDate());
        }
        if (CollUtil.isNotEmpty(dto.getContrastTimes())) {
            List<StartEndTimeDto> startEndTimes = dto.getContrastTimes();
            for (StartEndTimeDto startEndTime : startEndTimes) {
                if (StringUtils.isBlank(startEndTime.getStartTime()) || StringUtils.isBlank(startEndTime.getEndTime())) {
                    continue;
                }
                dto.setStartDate(startEndTime.getStartTime());
                dto.setEndDate(startEndTime.getEndTime());
                List<ScadaIndexVo> scadaIndexVosFinal = customDisplayMapper.getScadaIndexData(dto);
                if (CollUtil.isNotEmpty(scadaIndexVosFinal)) {
                    for (ScadaIndexVo scadaIndexVo : scadaIndexVosFinal) {
                        scadaIndexVo.setTimeRange(dto.getStartDate() + "-" + dto.getEndDate());
                    }
                    scadaIndexVoList.addAll(scadaIndexVosFinal);
                }
            }
        }
        List<ScadaReport> scadaReportList = scadaReportService.list();

        List<ScadaIndexVo> res = new ArrayList<>();
        for (ScadaIndexVo scadaIndexVo : scadaIndexVoList) {
            scadaIndexVo.setIsAlarm("0");
            if (StringUtils.isBlank(scadaIndexVo.getReportIds())) {
                if (CollUtil.isEmpty(dto.getReportLevels())) {
                    res.add(scadaIndexVo);
                }
                continue;
            }
            List<Long> reportIdList = Arrays.stream(scadaIndexVo.getReportIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            List<ScadaReport> reportList = scadaReportList.stream().filter(e -> reportIdList.contains(e.getId())).collect(Collectors.toList());
            if (CollUtil.isEmpty(reportList)) {
                if (CollUtil.isEmpty(dto.getReportLevels())) {
                    res.add(scadaIndexVo);
                }
                continue;
            }
            for (ScadaReport report : reportList) {
                Double value = Double.parseDouble(scadaIndexVo.getIndexValue());
                if (value.compareTo(Double.parseDouble(report.getReportLower())) >= 0
                        && value.compareTo(Double.parseDouble(report.getReportUpper())) <= 0) {
                    scadaIndexVo.setIsAlarm("1");
                    scadaIndexVo.setReportLevel(report.getReportLevel());
                    scadaIndexVo.setReportLower(report.getReportLower());
                    scadaIndexVo.setReportUpper(report.getReportUpper());
                    break;
                }
            }
            // 筛选报警等级
            if (CollUtil.isNotEmpty(dto.getReportLevels()) && StringUtils.isBlank(scadaIndexVo.getReportLevel())) {
                continue;
            }
            if (CollUtil.isNotEmpty(dto.getReportLevels())
                    && StringUtils.isNotBlank(scadaIndexVo.getReportLevel())
                    && !dto.getReportLevels().contains(scadaIndexVo.getReportLevel())) {
                continue;
            }
            res.add(scadaIndexVo);
        }
        return res;
    }

    @Override
    public List<UserTotalVo> getUserTotalMonth(String startDate, String endDate) {
        List<String> dates = getDates(startDate, endDate, "2");
        List<UserTotalVo> userTotalVos = customDisplayMapper.getNewUserTotalMonth();
        List<UserTotalVo> res = new ArrayList<>();
        for (String date : dates) {
            UserTotalVo vo = new UserTotalVo();
            vo.setScadaTime(date);
            List<UserTotalVo> userTotalVosFinal = userTotalVos.stream().filter(e -> e.getScadaTime().equals(date)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(userTotalVosFinal)) {
                vo.setNewUserTotal(userTotalVosFinal.get(0).getNewUserTotal());
            }
            vo.setUserTotal(customDisplayMapper.getUserTotal(date));
            res.add(vo);
        }
        return res;
    }

    @Override
    public List<DeviceByTypeVo> getDeviceByType(String deviceName) {
        return customDisplayMapper.getDeviceTypeList(deviceName);


    }

    @Override
    public Page<ScadaIndexVo> getHistoryPageData(Page page, WisdomDisplayDto dto) {
        return customDisplayMapper.getHistoryPageData(page, dto);
    }

    public List<ScadaIndexReportVo> getScadaCommReport(String codeChu,ScadaReportDto dto) {
        //结果返回放到list中
        List<ScadaIndexReportVo> list=new ArrayList<>();

        //特定的指标计算水厂的总瞬时量
        List<String> codesChu=Arrays.asList(codeChu.split(","));

        String startDate=dto.getStartDate();
        String endDate=dto.getEndDate();
        String startTime=dto.getStartTime()==null?"00:00:00":dto.getStartTime();
        String endTime=dto.getEndTime()==null?"23:59:59":dto.getEndTime();
        Integer minutes=dto.getMinutes();
        String codes=dto.getCodes();
        boolean isNight=dto.getSearchType()==1?true:false; //是否查询夜间最小流程
        //格式化时间
        String simpleDateFormat = "yyyy-MM-dd";
        String simpleDateFormatMinutes;
      if(isNight){
         simpleDateFormatMinutes= "yyyy-MM-dd";
      } else {
          simpleDateFormatMinutes = "yyyy-MM-dd HH:mm";
      }
        //取时间放到listDates中
        List<String> listDates = new ArrayList<>();
        List<String> dates = CalendarHelper.getDayBetweenDate(startDate, endDate, simpleDateFormat);
        if(isNight){
            listDates.addAll(dates);
        }else{
            //不是夜间流量，就按照传入的时间来分时段
            dates.forEach(item -> {
                List<String> minutesList = CalendarHelper.getMinutesBetweenDate(item + " " + startTime, item + " " + endTime, minutes, simpleDateFormatMinutes);
                listDates.addAll(minutesList);
            });
        }
        List<String> indexCodes=Arrays.asList(codes.split(","));
        listDates.forEach(date->{
            //赋值
        ScadaIndexReportVo scadaIndexReportVo=new ScadaIndexReportVo();

        scadaIndexReportVo.setDateTime(date);
         //查询开始时间
        LocalDateTime localTime=DateTimeUtil.fromLong2LocalDateTime(CalendarHelper.ConvertStrToDate(scadaIndexReportVo.getDateTime(),simpleDateFormatMinutes).getTime());
        Date LocalBeginTime = DateTimeUtil.convertLDTToDate(localTime);
        Date localEndTime;
        String totalFlow;
        //按照时间范围存储scada数据 waterIndexTypeVoListComm
        List<ScadaFlowVo> waterIndexTypeVoListComm;
        if(isNight){
            //夜间最小流量，按照天来找最小值，找到对应的结束时间
            localEndTime=DateTimeUtil.convertLDTToDate(localTime.plusDays(1).plusSeconds(-1));
            totalFlow=customDisplayMapper.getNightTotalFlow(codesChu,LocalBeginTime,localEndTime);
            waterIndexTypeVoListComm=customDisplayMapper.getWaterNightFlowComm(indexCodes,LocalBeginTime,localEndTime);
        }else {
            localEndTime=DateTimeUtil.convertLDTToDate(localTime.plusMinutes(minutes).plusSeconds(-1));
            totalFlow=customDisplayMapper.getTotalFlow(codesChu,LocalBeginTime,localEndTime);
            waterIndexTypeVoListComm=customDisplayMapper.getWaterFlowComm(indexCodes,LocalBeginTime,localEndTime);
        }
       if(StringUtils.isNotBlank(totalFlow) &&totalFlow.startsWith(".")){
           totalFlow="0"+totalFlow;
       }
        scadaIndexReportVo.setTotalFlow(totalFlow);

        //按照设备类型进行数据分组
        List<IndexTypeVo> indexTypeVos=new ArrayList<>();

        Map<String,List<ScadaFlowVo>> mapIndexType=waterIndexTypeVoListComm.stream().collect(Collectors.groupingBy(item->item.getIndexType()+"@"+item.getIndexTypeName()));
        mapIndexType.forEach((v,k)->{
            IndexTypeVo indexTypeVo=new IndexTypeVo();
            String indexType=v.split("@")[0];
            String indexTypeName=v.split("@")[1];
            Set<String> indexUnits=k.stream().map(ScadaFlowVo::getUnit).collect(Collectors.toSet());
            String indexUnit=StringUtils.join(indexUnits,",");
            indexTypeVo.setIndexType(indexType);
            indexTypeVo.setIndexTypeName(indexTypeName);
            indexTypeVo.setIndexUnit(indexUnit);
            indexTypeVo.setScadaList(k.stream().sorted(Comparator.comparing(ScadaFlowVo::getSortNumber)).collect(Collectors.toList()));
            indexTypeVos.add(indexTypeVo);
        });
        scadaIndexReportVo.setIndexTypeVos(indexTypeVos);
        //按照水厂进行数据分组
        List<WaterNameVo> waterNameVos=new ArrayList<>();
        Map<String,List<ScadaFlowVo>> mapWaterType=waterIndexTypeVoListComm.stream().collect(Collectors.groupingBy(item->item.getWaterId()+"@"+item.getWaterName()));
        mapWaterType.forEach((v,k)->{
            WaterNameVo waterNameVo=new WaterNameVo();
            String waterId=v.split("@")[0];
            String waterName=v.split("@")[1];
            waterNameVo.setWaterId(waterId);
            waterNameVo.setWaterName(waterName);
            waterNameVo.setScadaList(k.stream().sorted(
                    Comparator.comparing(ScadaFlowVo::getIndexType)
                            .thenComparing(ScadaFlowVo::getSortNumber)).collect(Collectors.toList()));
            waterNameVos.add(waterNameVo);
        });
        scadaIndexReportVo.setWaterNameVos(waterNameVos);
       list.add(scadaIndexReportVo);
    });
        return list;
    }

    @Override
    public Object getIndexListByType(String waterType, String indexType) {
        List<String>waterTypes=null;
        List<String>indexTypes=null;
        if(StringUtils.isNotEmpty(waterType)){
            waterTypes=Arrays.asList(waterType.split(","));
        }
        if(StringUtils.isNotEmpty(indexType)){
            indexTypes=Arrays.asList(indexType.split(","));
        }
       return allocationMapper.getIndexListByType(waterTypes,indexTypes);
    }

    @Override
    public void synStatisticsScada(String type, String startTime, String endTime) {
        switch (type) {
            case "0":
                scadaHandler.syncTwentyFourHourData(DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss"), DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss"));
                break;
            case "1":
                scadaHandler.saveHistoryCode(DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss"), DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss"), 1);
                break;
            case "2":
                scadaHandler.saveStatisticsCode(DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss"), DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss"), 2);
                break;
            case "3":
                scadaHandler.saveStatisticsCode(DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss"), DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss"), 3);
                break;
        }
    }

    /**
     * @param startDate  开始时间
     * @param endDate 结束时间
     * @param type 0小时 1天 2月 3年
     * @description 获取时间列表
     */
    List<String> getDates(String startDate, String endDate, String type) {
        List<String> dates = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.parse(startDate, "yyyy-MM-dd HH:mm:ss"));
        while (DateUtil.format(cal.getTime(), "yyyy-MM-dd HH:mm:ss").compareTo(endDate) <= 0) {
            switch (type) {
                case "0":
                    dates.add(DateUtil.format(cal.getTime(), "yyyy-MM-dd HH"));
                    cal.add(Calendar.HOUR_OF_DAY, +1);
                    break;
                case "1":
                    dates.add(DateUtil.format(cal.getTime(), "yyyy-MM-dd"));
                    cal.add(Calendar.DAY_OF_MONTH, +1);
                    break;
                case "2":
                    dates.add(DateUtil.format(cal.getTime(), "yyyy-MM"));
                    cal.add(Calendar.MONTH, +1);
                    break;
                case "3":
                    dates.add(DateUtil.format(cal.getTime(), "yyyy"));
                    cal.add(Calendar.YEAR, +1);
                    break;
            }
        }
        return dates;
    }

}