package com.sooka.sponest.monitor.device.service.impl;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.datascope.annotation.DataScopeMutiDept;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.sooka.sponest.monitor.aidevicedept.domain.CenterdataTAidevicedept;
import com.sooka.sponest.monitor.base.service.impl.BaseService;
import com.sooka.sponest.monitor.camera.domain.CameraCodeAndNameVO;
import com.sooka.sponest.monitor.camera.domain.CentermonitorTCameraType;
import com.sooka.sponest.monitor.device.domain.*;
import com.sooka.sponest.monitor.device.mapper.CentermonitorTMonitoringDeviceCameraMapper;
import com.sooka.sponest.monitor.device.mapper.CentermonitorTMonitoringDeviceMapper;
import com.sooka.sponest.monitor.device.service.*;
import com.sooka.sponest.monitor.remoteapi.service.center.event.RemoteEventBaseService;
import com.sooka.sponest.monitor.remoteapi.service.center.system.RemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 监测设备Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-14
 */
@Service
@Slf4j
public class CentermonitorTMonitoringDeviceServiceImpl extends BaseService implements ICentermonitorTMonitoringDeviceService {
    @Resource
    private CentermonitorTMonitoringDeviceMapper centermonitorTMonitoringDeviceMapper;

    @Resource
    private ICentermonitorTMonitoringDeviceThresholdService centermonitorTMonitoringDeviceThresholdService;

    @Resource
    private ICentermonitorTMonitoringDeviceSoilMoistureThresholdService centermonitorTMonitoringDeviceSoilMoistureThresholdService;

    @Resource
    private ICentermonitorTMonitoringDeviceAtmosphereThresholdService centermonitorTMonitoringDeviceAtmosphereThresholdService;

    @Resource
    private ICentermonitorTMonitoringDeviceWaterQualityThresholdService centermonitorTMonitoringDeviceWaterQualityThresholdService;

    @Resource
    private RemoteService remoteService;

    @Resource
    private RemoteEventBaseService eventBaseService;

    private static final FastDateFormat simpleDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    Logger logger = LoggerFactory.getLogger(CentermonitorTMonitoringDeviceServiceImpl.class);

    @Autowired
    private CentermonitorTMonitoringDeviceCameraMapper centermonitorTMonitoringDeviceCameraMapper;

    /**
     * 查询监测设备
     *
     * @param id 监测设备主键
     * @return 监测设备
     */
    @Override
    public CentermonitorTMonitoringDevice selectCentermonitorTMonitoringDeviceById(String id) {
        /*图片前缀*/
        List<String> imgList = new ArrayList<>();
        R<String> url = remoteService.selectConfigKey_fileUrl();
        Map<String, Object> mapList = new HashMap<>();
        CentermonitorTMonitoringDevice device = centermonitorTMonitoringDeviceMapper.selectCentermonitorTMonitoringDeviceById(id);
        device.setForSystem(centermonitorTMonitoringDeviceMapper.SelectTypeById(id));
        mapList.put("设备名称", ObjectUtils.isEmpty(device) ? 0 : device.getDeviceName());
        mapList.put("品牌", ObjectUtils.isEmpty(device) ? 0 : device.getBrand());
        mapList.put("工作状态", ObjectUtils.isEmpty(device) ? 0 : device.getWorkingStatusText());
        mapList.put("设备类型", ObjectUtils.isEmpty(device) ? 0 : device.getDeviceTypeText());
        mapList.put("所属区域", ObjectUtils.isEmpty(device) ? 0 : device.getAddress());
        if (StringUtils.isNotEmpty(device.getCameraCode())) {
            device.setCameraCodeList(Arrays.asList(device.getCameraCode().split(",")));
        }
        ArrayList<CentermonitorTMonitoringDeviceImg> deviceImg = centermonitorTMonitoringDeviceMapper.selectCentermonitorTDeviceImgByDeviceId(id);
        for (CentermonitorTMonitoringDeviceImg img : deviceImg) {
            String imgPath = img.getDeviceImg();
            if (imgPath != null && !imgPath.isEmpty()) {
                img.setDeviceImg(url.getData() + imgPath);
                imgList.add(url.getData() + imgPath);
            }
        }
        Map<String, Object> map = new HashMap<>();
        switch (device.getDeviceType()) {
            case "1":
                //水质
                CentermonitorTMonitoringDataWaterQuality centermonitorTMonitoringDataWaterQuality = centermonitorTMonitoringDeviceMapper.selectWaterQualityCentermonitorByCode(device.getDeviceCode());
                map.put("水质悬浮物(mg/L)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterQuality) ? 0 : centermonitorTMonitoringDataWaterQuality.getWaterQualitySuspension());
                map.put("化学需氧量(mg/L)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterQuality) ? 0 : centermonitorTMonitoringDataWaterQuality.getCod());
                map.put("氨氮(mg/L)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterQuality) ? 0 : centermonitorTMonitoringDataWaterQuality.getAmmoniaNitrogen());
                map.put("水中PH(pH)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterQuality) ? 0 : centermonitorTMonitoringDataWaterQuality.getWaterPh());
                map.put("水温(℃)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterQuality) ? 0 : centermonitorTMonitoringDataWaterQuality.getWaterTemperature());
                map.put("信号强度(RSSI)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterQuality) ? 0 : centermonitorTMonitoringDataWaterQuality.getSignalStrength());
                break;
            case "7":
                //水流速
                CentermonitorTMonitoringDataWaterVelocity centermonitorTMonitoringDataWaterVelocity = centermonitorTMonitoringDeviceMapper.selectWaterVelocityCentermonitorBySTCode(device.getDeviceCode());
                map.put("瞬时流量(m3/s)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterVelocity) ? 0 : centermonitorTMonitoringDataWaterVelocity.getQ());
                map.put("瞬时流速(m/s)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterVelocity) ? 0 : centermonitorTMonitoringDataWaterVelocity.getV1());
                map.put("设备温度", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterVelocity) ? 0 : centermonitorTMonitoringDataWaterVelocity.getDTEMP());
                map.put("水位", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterVelocity) ? 0 : centermonitorTMonitoringDataWaterVelocity.getZ());
                map.put("水深", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterVelocity) ? 0 : centermonitorTMonitoringDataWaterVelocity.getZ1());
                map.put("电池电量(%)", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterVelocity) ? 0 : centermonitorTMonitoringDataWaterVelocity.getBAT());
                break;
            case "2":
                //土壤墒情
                CentermonitorTMonitoringDataSoilMoisture centermonitorTMonitoringDataSoilMoisture = centermonitorTMonitoringDeviceMapper.selectSoilMoistureCentermonitorByCode(device.getDeviceCode());
                map.put("温度(℃)", ObjectUtils.isEmpty(centermonitorTMonitoringDataSoilMoisture) ? 0 : centermonitorTMonitoringDataSoilMoisture.getTemperature());
                map.put("湿度(%RH)", ObjectUtils.isEmpty(centermonitorTMonitoringDataSoilMoisture) ? 0 : centermonitorTMonitoringDataSoilMoisture.getHumidity());
                map.put("ph值(PH)", ObjectUtils.isEmpty(centermonitorTMonitoringDataSoilMoisture) ? 0 : centermonitorTMonitoringDataSoilMoisture.getPh());
                map.put("导电率(us/cm)", ObjectUtils.isEmpty(centermonitorTMonitoringDataSoilMoisture) ? 0 : centermonitorTMonitoringDataSoilMoisture.getConductivity());
                map.put("氮含量(mg/kg)", ObjectUtils.isEmpty(centermonitorTMonitoringDataSoilMoisture) ? 0 : centermonitorTMonitoringDataSoilMoisture.getNitrogen());
                map.put("磷含量(mg/kg)", ObjectUtils.isEmpty(centermonitorTMonitoringDataSoilMoisture) ? 0 : centermonitorTMonitoringDataSoilMoisture.getPhosphorus());
                map.put("钾含量(mg/kg)", ObjectUtils.isEmpty(centermonitorTMonitoringDataSoilMoisture) ? 0 : centermonitorTMonitoringDataSoilMoisture.getPotassium());
                break;
            case "5":
                //大气
                CentermonitorTMonitoringDataAtmosphere centermonitorTMonitoringDataAtmosphere = centermonitorTMonitoringDeviceMapper.selectAtmosphereCentermonitorByCode(device.getDeviceCode());
                map.put("二氧化硫(ug/m3)", ObjectUtils.isEmpty(centermonitorTMonitoringDataAtmosphere) ? 0 : centermonitorTMonitoringDataAtmosphere.getSulfurDioxide());
                map.put("二氧化氮(ug/m3)", ObjectUtils.isEmpty(centermonitorTMonitoringDataAtmosphere) ? 0 : centermonitorTMonitoringDataAtmosphere.getNitrogenDioxide());
                map.put("细颗粒(ug/m3)", ObjectUtils.isEmpty(centermonitorTMonitoringDataAtmosphere) ? 0 : centermonitorTMonitoringDataAtmosphere.getFineParticle());
                map.put("温度(℃)", ObjectUtils.isEmpty(centermonitorTMonitoringDataAtmosphere) ? 0 : centermonitorTMonitoringDataAtmosphere.getTemperature());
                map.put("湿度(%RH)", ObjectUtils.isEmpty(centermonitorTMonitoringDataAtmosphere) ? 0 : centermonitorTMonitoringDataAtmosphere.getHumidity());
                map.put("一氧化碳(mg/m3)", ObjectUtils.isEmpty(centermonitorTMonitoringDataAtmosphere) ? 0 : centermonitorTMonitoringDataAtmosphere.getCarbonMonoxide());
                break;
            case "6":
                //水压
                CentermonitorTMonitoringDataWaterPressure centermonitorTMonitoringDataWaterPressure = centermonitorTMonitoringDeviceMapper.selectWaterPressureCentermonitorByIMEICode(device.getDeviceCode());
                map.put("水压值", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterPressure) ? 0 : centermonitorTMonitoringDataWaterPressure.getHydraulicValue());
                map.put("水压下限阈值", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterPressure) ? 0 : centermonitorTMonitoringDataWaterPressure.getHydraulicThresholdMin());
                map.put("水压上限阈值", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterPressure) ? 0 : centermonitorTMonitoringDataWaterPressure.getHydraulicThresholdMax());
                map.put("信号强度", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterPressure) ? 0 : centermonitorTMonitoringDataWaterPressure.getSignalPower());
                map.put("电池电量", ObjectUtils.isEmpty(centermonitorTMonitoringDataWaterPressure) ? 0 : centermonitorTMonitoringDataWaterPressure.getBatteryValue());
                break;
            case "4":
                //病虫害
                CentermonitorTMonitoringDataInsectPests centermonitorTMonitoringDataInsectPests = centermonitorTMonitoringDeviceMapper.selectInsectPestsCentermonitorByCode(device.getDeviceCode());
                R<String> insectUrl = remoteService.selectConfigKey_fileUrl();
                map.put("上次识别数量", ObjectUtils.isEmpty(centermonitorTMonitoringDataInsectPests) ? "" : centermonitorTMonitoringDataInsectPests.getOldCount());
                map.put("上次识别结果", ObjectUtils.isEmpty(centermonitorTMonitoringDataInsectPests) ? "" : centermonitorTMonitoringDataInsectPests.getOldResults());
                map.put("上次标注后图片", ObjectUtils.isEmpty(centermonitorTMonitoringDataInsectPests) ? "" : insectUrl.getData() + centermonitorTMonitoringDataInsectPests.getOldTaggingImgUrl());
                map.put("最新识别数量", ObjectUtils.isEmpty(centermonitorTMonitoringDataInsectPests) ? "" : centermonitorTMonitoringDataInsectPests.getNewCount());
                map.put("最新识别结果", ObjectUtils.isEmpty(centermonitorTMonitoringDataInsectPests) ? "" : centermonitorTMonitoringDataInsectPests.getResults());
                map.put("最新标注后图片", ObjectUtils.isEmpty(centermonitorTMonitoringDataInsectPests) ? "" : insectUrl.getData() + centermonitorTMonitoringDataInsectPests.getTaggingImgUrl());
                break;
        }

        /**检测设备和摄像头关联表构建为一个list返回给前端**/
        List<CameraCodeAndNameVO> list = centermonitorTMonitoringDeviceCameraMapper.selectByDeviceId(id);
        device.setCameras(list);

        device.setSensorDetectionList(map);
        device.setDeviceImagesList(imgList);
        device.setDeviceList(mapList);
        return device;
    }

    //水流速
    @Override
    public CentermonitorTMonitoringDataWaterVelocity selectWaterVelocityCentermonitorByST(String id) {
        return centermonitorTMonitoringDeviceMapper.selectWaterVelocityCentermonitorByST(id);
    }

    //土壤墒情
    @Override
    public CentermonitorTMonitoringDataSoilMoisture selectSoilMoistureCentermonitorByDeviceCode(String id) {
        return centermonitorTMonitoringDeviceMapper.selectSoilMoistureCentermonitorByDeviceCode(id);
    }

    //大气
    @Override
    public CentermonitorTMonitoringDataAtmosphere selectAtmosphereCentermonitorByDeviceCode(String id) {
        return centermonitorTMonitoringDeviceMapper.selectAtmosphereCentermonitorByDeviceCode(id);
    }

    //水质
    @Override
    public CentermonitorTMonitoringDataWaterQuality selectWaterQualityCentermonitorByDeviceCode(String id) {
        return centermonitorTMonitoringDeviceMapper.selectWaterQualityCentermonitorByDeviceCode(id);
    }

    //水压
    @Override
    public CentermonitorTMonitoringDataWaterPressure selectWaterPressureCentermonitorByIMEI(String id) {
        return centermonitorTMonitoringDeviceMapper.selectWaterPressureCentermonitorByIMEI(id);
    }

    //病虫害
    @Override
    public CentermonitorTMonitoringDataInsectPests selectInsectPestsCentermonitorByDeviceCode(String id) {
        /*图片前缀**/
        R<String> url = remoteService.selectConfigKey_fileUrl();
        CentermonitorTMonitoringDataInsectPests insectPests = centermonitorTMonitoringDeviceMapper.selectInsectPestsCentermonitorByDeviceCode(id);
        insectPests.setOldTaggingImgUrl(url.getData() + insectPests.getOldTaggingImgUrl());
        insectPests.setTaggingImgUrl(url.getData() + insectPests.getTaggingImgUrl());
        return insectPests;
    }

    /**
     * 查询监测设备列表
     *
     * @param centermonitorTMonitoringDevice 监测设备
     * @return 监测设备
     */
    @Override
    @DataScopeMutiDept(deptAlias = "d")
    public List<CentermonitorTMonitoringDevice> selectCentermonitorTMonitoringDeviceList(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        setSookaDataBase(centermonitorTMonitoringDevice);
        return centermonitorTMonitoringDeviceMapper.selectCentermonitorTMonitoringDeviceList(centermonitorTMonitoringDevice);
    }

    /**
     * 根据部门ID和工作状态查询传感器列表
     *
     * @param centermonitorTMonitoringDevice 传感器
     * @return 传感器集合
     */
    public List<CentermonitorTMonitoringDevice> selectDeviceListByDeptIdAndWorkingStatus(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        setSookaDataBase(centermonitorTMonitoringDevice);
        return centermonitorTMonitoringDeviceMapper.selectDeviceListByDeptIdAndWorkingStatus(centermonitorTMonitoringDevice);
    }

    /**
     * 查询监测设备列表(所有)
     *
     * @param centermonitorTMonitoringDevice 监测设备
     * @return 监测设备
     */
    @Override
    @DataScopeMutiDept(deptAlias = "d")
    public List<CentermonitorTMonitoringDevice> selectCentermonitorTMonitoringDeviceListAll(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        setSookaDataBase(centermonitorTMonitoringDevice);
        return centermonitorTMonitoringDeviceMapper.selectCentermonitorTMonitoringDeviceListAll(centermonitorTMonitoringDevice);
    }

    /**
     * 新增监测设备
     *
     * @param centermonitorTMonitoringDevice 监测设备
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCentermonitorTMonitoringDevice(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        centermonitorTMonitoringDevice.setId(IdUtils.simpleUUID());
        centermonitorTMonitoringDevice.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getUserId().toString());
        centermonitorTMonitoringDevice.setCreateTime(DateUtils.getNowDate());
        for (int i = 0; i < centermonitorTMonitoringDevice.getForSystem().size(); i++) {
            CentermonitorTCameraType type = new CentermonitorTCameraType();
            type.setId(IdUtils.simpleUUID());
            type.setCameraId(centermonitorTMonitoringDevice.getId());
            type.setType(centermonitorTMonitoringDevice.getForSystem().get(i).getType());
            type.setTypeName(centermonitorTMonitoringDevice.getForSystem().get(i).getTypeName());
            centermonitorTMonitoringDeviceMapper.insertCentermonitorTCameraType(type);
        }
        List<CentermonitorTMonitoringDeviceImg> images = new ArrayList<>();
        for (String file : centermonitorTMonitoringDevice.getDeviceImages()) {
            CentermonitorTMonitoringDeviceImg image = new CentermonitorTMonitoringDeviceImg();
            image.setDeviceImg(file.substring(file.indexOf("group1")));
            image.setDeviceId(centermonitorTMonitoringDevice.getId());
            images.add(image);
        }
        if (!images.isEmpty()) {
            centermonitorTMonitoringDeviceMapper.insertCentermonitorTDeviceImg(images);
        }
        if (CollectionUtils.isNotEmpty(centermonitorTMonitoringDevice.getCameras())) {
            centermonitorTMonitoringDeviceCameraMapper.insertDeviceCamera(centermonitorTMonitoringDevice.getId(), centermonitorTMonitoringDevice.getCameras());
        }
        return centermonitorTMonitoringDeviceMapper.insertCentermonitorTMonitoringDevice(centermonitorTMonitoringDevice);
    }

    /**
     * 修改监测设备
     *
     * @param centermonitorTMonitoringDevice 监测设备
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateCentermonitorTMonitoringDevice(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        centermonitorTMonitoringDeviceMapper.deleteTypeById(centermonitorTMonitoringDevice.getId());
        for (int i = 0; i < centermonitorTMonitoringDevice.getForSystem().size(); i++) {
            CentermonitorTCameraType type = new CentermonitorTCameraType();
            type.setId(IdUtils.simpleUUID());
            type.setCameraId(centermonitorTMonitoringDevice.getId());
            type.setType(centermonitorTMonitoringDevice.getForSystem().get(i).getType());
            type.setTypeName(centermonitorTMonitoringDevice.getForSystem().get(i).getTypeName());
            centermonitorTMonitoringDeviceMapper.insertCentermonitorTCameraType(type);
        }
        centermonitorTMonitoringDevice.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getUserId());
        centermonitorTMonitoringDevice.setUpdateTime(DateUtils.getNowDate());
        List<CentermonitorTMonitoringDeviceImg> imagesList = new ArrayList<>();
        List<String> deviceImagesList = centermonitorTMonitoringDevice.getDeviceImages();
        centermonitorTMonitoringDeviceMapper.deleteImageByDeviceId(centermonitorTMonitoringDevice.getId());
        if (CollectionUtils.isNotEmpty(deviceImagesList)) {
            for (String image : deviceImagesList) {
                if (image != null && image.contains("group")) {
                    // 修改中间表记录的 cameraImg 字段
                    CentermonitorTMonitoringDeviceImg img = new CentermonitorTMonitoringDeviceImg();
                    img.setDeviceImg(image.substring(image.indexOf("group1")));
                    img.setDeviceId(centermonitorTMonitoringDevice.getId());
                    imagesList.add(img);
                }
            }
        }
        if (!imagesList.isEmpty()) {
            centermonitorTMonitoringDeviceMapper.insertCentermonitorTDeviceImg(imagesList);
        }
        centermonitorTMonitoringDeviceCameraMapper.deleteDeviceCameraByDeviceId(centermonitorTMonitoringDevice.getId());
        if (CollectionUtils.isNotEmpty(centermonitorTMonitoringDevice.getCameras())) {
            centermonitorTMonitoringDeviceCameraMapper.insertDeviceCamera(centermonitorTMonitoringDevice.getId(), centermonitorTMonitoringDevice.getCameras());
        }
        return centermonitorTMonitoringDeviceMapper.updateCentermonitorTMonitoringDevice(centermonitorTMonitoringDevice);
    }

    /**
     * 批量删除监测设备
     *
     * @param ids 需要删除的监测设备主键
     * @return 结果
     */
    @Override
    public int deleteCentermonitorTMonitoringDeviceByIds(String[] ids) {
        for (String id : ids) {
            /*删除设备类型**/
            centermonitorTMonitoringDeviceMapper.deleteTypeById(id);
            /*删除设备部门**/
            centermonitorTMonitoringDeviceMapper.deleteDeviceDeptById(id);
            CentermonitorTMonitoringDevice device = centermonitorTMonitoringDeviceMapper.selectCentermonitorTMonitoringDeviceById(id);
            String deviceCode = device.getDeviceCode();
            /*删除监测数据**/
            centermonitorTMonitoringDeviceMapper.deleteAtmosphereDataByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteInsectPestsDataByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteSoilMoistureDataByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteWaterPressureDataByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteWaterQualityDataByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteWaterVelocityDataByCode(deviceCode);
            /*删除阈值设置**/
            centermonitorTMonitoringDeviceMapper.deleteAtmosphereThresholdByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteSoilMoistureThresholdByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteWaterQualityThresholdByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteWaterVelocityThresholdByCode(deviceCode);
            centermonitorTMonitoringDeviceMapper.deleteWaterPressureThresholdByCode(deviceCode);
            /*删除检测设备和摄像头关联表**/
            centermonitorTMonitoringDeviceCameraMapper.deleteDeviceCameraByDeviceId(id);
        }
        return centermonitorTMonitoringDeviceMapper.deleteCentermonitorTMonitoringDeviceByIds(ids);
    }

    /**
     * 删除监测设备信息
     *
     * @param id 监测设备主键
     * @return 结果
     */
    @Override
    public int deleteCentermonitorTMonitoringDeviceById(String id) {
        /*删除设备类型**/
        centermonitorTMonitoringDeviceMapper.deleteTypeById(id);
        /*删除设备部门**/
        centermonitorTMonitoringDeviceMapper.deleteDeviceDeptById(id);
        return centermonitorTMonitoringDeviceMapper.deleteCentermonitorTMonitoringDeviceById(id);
    }

    /**
     * 查询监测设备列表根据部门id查询
     *
     * @param str 监测设备
     * @return 监测设备
     */
    @Override
    public List<CentermonitorTMonitoringDevice> selectListByDeptId(List<String> str) {
        return centermonitorTMonitoringDeviceMapper.selectListByDeptId(str);
    }

    /**
     * 土壤设备告警方法
     */
    private void soilMoistureWarn(CentermonitorTMonitoringDevice device,
                                  CentermonitorTMonitoringThresholdSoilMoisture thresholdSoilMoisture,
                                  CentermonitorTMonitoringDataSoilMoisture centermonitorTMonitoringDataSoilMoisture) throws ParseException {
        boolean flag = false;
        //告警报文
        String title = "【土壤传感器阈值告警】传感器名称：" + device.getDeviceName() + "  设备编码：" + device.getDeviceCode() + ";";
        String warnText;
        StringBuilder stringBuilder = new StringBuilder(title);
        if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getTemperature()) < Double.parseDouble(thresholdSoilMoisture.getTemperatureThresholdDown()) ||
                Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getTemperature()) > Double.parseDouble(thresholdSoilMoisture.getTemperatureThresholdUp())) {
            if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getTemperature()) < Double.parseDouble(thresholdSoilMoisture.getTemperatureThresholdDown())) {
                warnText = "温度过低";
            } else {
                warnText = "温度过高";
            }
            flag = true;
            stringBuilder.append("  ").append(warnText).append(", 温度：").append(centermonitorTMonitoringDataSoilMoisture.getTemperature()).append("℃  参考阈值：").append(thresholdSoilMoisture.getTemperatureThresholdDown()).append("~").append(thresholdSoilMoisture.getTemperatureThresholdUp()).append("℃;");
        }
        if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getHumidity()) < Double.parseDouble(thresholdSoilMoisture.getHumidityThresholdDown()) ||
                Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getHumidity()) > Double.parseDouble(thresholdSoilMoisture.getHumidityThresholdUp())) {
            if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getHumidity()) < Double.parseDouble(thresholdSoilMoisture.getHumidityThresholdDown())) {
                warnText = "湿度过低";
            } else {
                warnText = "湿度过高";
            }
            flag = true;
            stringBuilder.append("  ").append(warnText).append(", 当前值：").append(centermonitorTMonitoringDataSoilMoisture.getHumidity()).append("%RH;  参考阈值：").append(thresholdSoilMoisture.getHumidityThresholdDown()).append("~").append(thresholdSoilMoisture.getHumidityThresholdUp()).append("%RH;");
        }
        if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPh()) < Double.parseDouble(thresholdSoilMoisture.getPhThresholdDown()) ||
                Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPh()) > Double.parseDouble(thresholdSoilMoisture.getPhThresholdUp())) {
            if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPh()) < Double.parseDouble(thresholdSoilMoisture.getPhThresholdDown())) {
                warnText = "ph值过低";
            } else {
                warnText = "ph值过高";
            }
            flag = true;
            stringBuilder.append("  ").append(warnText).append(", 当前值：").append(centermonitorTMonitoringDataSoilMoisture.getPh()).append("PH;  参考阈值：").append(thresholdSoilMoisture.getPhThresholdDown()).append("~").append(thresholdSoilMoisture.getPhThresholdUp()).append("PH;");
        }
        if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getConductivity()) < Double.parseDouble(thresholdSoilMoisture.getConductivityThresholdDown()) ||
                Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getConductivity()) > Double.parseDouble(thresholdSoilMoisture.getConductivityThresholdUp())) {
            if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getConductivity()) < Double.parseDouble(thresholdSoilMoisture.getConductivityThresholdDown())) {
                warnText = "导电率过低";
            } else {
                warnText = "导电率过高";
            }
            flag = true;
            stringBuilder.append("  ").append(warnText).append(", 当前值：").append(centermonitorTMonitoringDataSoilMoisture.getConductivity()).append("μS/cm;  参考阈值：").append(thresholdSoilMoisture.getConductivityThresholdDown()).append("~").append(thresholdSoilMoisture.getConductivityThresholdUp()).append("μS/cm;");
        }
        if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getNitrogen()) < Double.parseDouble(thresholdSoilMoisture.getNitrogenThresholdDown()) ||
                Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getNitrogen()) > Double.parseDouble(thresholdSoilMoisture.getNitrogenThresholdUp())) {
            if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getNitrogen()) < Double.parseDouble(thresholdSoilMoisture.getNitrogenThresholdDown())) {
                warnText = "氮含量过低";
            } else {
                warnText = "氮含量过高";
            }
            flag = true;
            stringBuilder.append("  ").append(warnText).append(", 当前值：").append(centermonitorTMonitoringDataSoilMoisture.getNitrogen()).append("mg/kg;  参考阈值：").append(thresholdSoilMoisture.getNitrogenThresholdDown()).append("~").append(thresholdSoilMoisture.getNitrogenThresholdUp()).append("mg/kg");
        }
        if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPhosphorus()) < Double.parseDouble(thresholdSoilMoisture.getPhosphorusThresholdDown()) ||
                Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPhosphorus()) > Double.parseDouble(thresholdSoilMoisture.getPhosphorusThresholdUp())) {
            if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPhosphorus()) < Double.parseDouble(thresholdSoilMoisture.getPhosphorusThresholdDown())) {
                warnText = "磷含量过低";
            } else {
                warnText = "磷含量过高";
            }
            flag = true;
            stringBuilder.append("  ").append(warnText).append(", 当前值：").append(centermonitorTMonitoringDataSoilMoisture.getPhosphorus()).append("mg/kg;  参考阈值：").append(thresholdSoilMoisture.getPhosphorusThresholdDown()).append("~").append(thresholdSoilMoisture.getPhosphorusThresholdUp()).append("mg/kg;");
        }
        if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPotassium()) < Double.parseDouble(thresholdSoilMoisture.getPotassiumThresholdDown()) ||
                Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPotassium()) > Double.parseDouble(thresholdSoilMoisture.getPotassiumThresholdUp())) {
            if (Double.parseDouble(centermonitorTMonitoringDataSoilMoisture.getPotassium()) < Double.parseDouble(thresholdSoilMoisture.getPotassiumThresholdDown())) {
                warnText = "钾含量过低";
            } else {
                warnText = "钾含量过高";
            }
            flag = true;
            stringBuilder.append("  ").append(warnText).append(", 当前值：").append(centermonitorTMonitoringDataSoilMoisture.getPotassium()).append("mg/kg;  参考阈值：").append(thresholdSoilMoisture.getPotassiumThresholdDown()).append("~").append(thresholdSoilMoisture.getPotassiumThresholdUp()).append("mg/kg;");
        }
        if (!stringBuilder.toString().equals(title)) {
            System.out.println(stringBuilder);
        }
        /*
         * 环保事件（大类6）：大气监测（小类601）、水质环境（小类602）
         * 水利事件（大类5）：水压监测（小类510）、水流速（小类511）
         * 农业事件（大类4）：土壤墒情（小类403）、病虫害监测（小类401）
         * */
        if (flag) {
            SensorEventVo vo = new SensorEventVo();
            vo.setEventType("4");
            vo.setEventTypeXl("403");
            vo.setEventName(title);
            vo.setEventDescription(stringBuilder.toString());
            vo.setLatitude(device.getLatitude());
            vo.setLongitude(device.getLongitude());
            vo.setSensorId(device.getId());
            vo.setReportor(device.getDeviceName());
            vo.setReportTime(simpleDateFormat.parse(centermonitorTMonitoringDataSoilMoisture.getCreateTime()));
            vo.setAddress(device.getAddress());
        }
    }

    /**
     * 查询水流速传感器数据列表
     *
     * @param centermonitorTMonitoringDataWaterVelocity 水质传感器
     * @return 监测设备
     */
    @Override
    public List<CentermonitorTMonitoringDataWaterVelocity> selectWaterVelocityMonitoringData(CentermonitorTMonitoringDataWaterVelocity centermonitorTMonitoringDataWaterVelocity) {
        return centermonitorTMonitoringDeviceMapper.selectWaterVelocityMonitoringData(centermonitorTMonitoringDataWaterVelocity);
    }

    /**
     * 查询水质传感器数据列表
     *
     * @param centermonitorTMonitoringDataWaterQuality 水质传感器
     * @return 监测设备
     */
    @Override
    public List<CentermonitorTMonitoringDataWaterQuality> selectWaterQualityMonitoringData(CentermonitorTMonitoringDataWaterQuality centermonitorTMonitoringDataWaterQuality) {
        return centermonitorTMonitoringDeviceMapper.selectWaterQualityMonitoringData(centermonitorTMonitoringDataWaterQuality);
    }

    /**
     * 查询土壤墒情传感器数据列表
     *
     * @param centermonitorTMonitoringDataSoilMoisture 水质传感器
     * @return 监测设备
     */
    @Override
    public List<CentermonitorTMonitoringDataSoilMoisture> selectSoilMoistureMonitoringData(CentermonitorTMonitoringDataSoilMoisture centermonitorTMonitoringDataSoilMoisture) {
        return centermonitorTMonitoringDeviceMapper.selectSoilMoistureMonitoringData(centermonitorTMonitoringDataSoilMoisture);
    }

    /**
     * 查询大气传感器数据列表
     *
     * @param centermonitorTMonitoringDataAtmosphere 水质传感器
     * @return 监测设备
     */
    @Override
    public List<CentermonitorTMonitoringDataAtmosphere> selectAtmosphereMonitoringData(CentermonitorTMonitoringDataAtmosphere centermonitorTMonitoringDataAtmosphere) {
        return centermonitorTMonitoringDeviceMapper.selectAtmosphereMonitoringData(centermonitorTMonitoringDataAtmosphere);
    }

    /**
     * 查询水压传感器数据列表
     *
     * @param centermonitorTMonitoringDataWaterPressure 水压传感器
     * @return 监测设备集合
     */
    @Override
    public List<CentermonitorTMonitoringDataWaterPressure> selectWaterPressureMonitoringData(CentermonitorTMonitoringDataWaterPressure centermonitorTMonitoringDataWaterPressure) {
        return centermonitorTMonitoringDeviceMapper.selectWaterPressureMonitoringData(centermonitorTMonitoringDataWaterPressure);
    }

    /**
     * 病虫害传感器数据列表查询
     *
     * @param centermonitorTMonitoringDataInsectPests 水压传感器
     * @return 监测设备集合
     */
    @Override
    public List<CentermonitorTMonitoringDataInsectPests> selectInsectPestsMonitoringData(CentermonitorTMonitoringDataInsectPests centermonitorTMonitoringDataInsectPests) {
        /*图片前缀**/
        R<String> url = remoteService.selectConfigKey_fileUrl();
        List<CentermonitorTMonitoringDataInsectPests> insectPestsList = centermonitorTMonitoringDeviceMapper.selectInsectPestsMonitoringData(centermonitorTMonitoringDataInsectPests);
        insectPestsList.forEach(item ->
        {
            CentermonitorTMonitoringDataInsectPests dataInsectPests = new CentermonitorTMonitoringDataInsectPests();
            BeanUtils.copyProperties(item, dataInsectPests);
            dataInsectPests.setOldTaggingImgUrl(url.getData() + item.getOldTaggingImgUrl());
            dataInsectPests.setTaggingImgUrl(url.getData() + item.getTaggingImgUrl());
            insectPestsList.set(insectPestsList.indexOf(item), dataInsectPests);
        });
        return insectPestsList;
    }

    /**
     * 查询部门数据列表
     *
     * @param centerdataTAidevicedept 部门数据列表
     * @return 监测设备集合
     */
    @Override
    public List<CenterdataTAidevicedept> selectDeptMonitoringData(CenterdataTAidevicedept centerdataTAidevicedept) {
        return centermonitorTMonitoringDeviceMapper.selectDeptMonitoringData(centerdataTAidevicedept);
    }

    /**
     * 按类型查询传感器设备编码数组
     */
    @Override
    @DataScopeMutiDept(deptAlias = "d")
    public List<Map<String, String>> selectDeviceCodeMap(CentermonitorTMonitoringDevice device) {
        setSookaDataBase(device);
        return centermonitorTMonitoringDeviceMapper.selectDeviceCodeMap(device);
    }

    /**
     * 查询最新一条水质传感器监测数据 -- 根据设备编码数组
     */
    @Override
    public List<CentermonitorTMonitoringDataWaterQuality> selectWaterQualityDataByDeviceCodes(String[] deviceCodes) {
        return centermonitorTMonitoringDeviceMapper.selectWaterQualityDataByDeviceCodes(deviceCodes);
    }

    /**
     * 查询最新一条水质传感器监测数据 -- 根据设备编码数组
     */
    public List<CentermonitorTMonitoringDataSoilMoisture> selectSoilMoistureDataByDeviceCodes(String[] deviceCodes) {
        return centermonitorTMonitoringDeviceMapper.selectSoilMoistureDataByDeviceCodes(deviceCodes);
    }

    /**
     * 查询最新一条大气监测传感器监测数据 -- 根据设备编码数组
     */
    public List<CentermonitorTMonitoringDataAtmosphere> selectAtmosphereDataByDeviceCodes(String[] deviceCodes) {
        return centermonitorTMonitoringDeviceMapper.selectAtmosphereDataByDeviceCodes(deviceCodes);
    }

    /**
     * 查询最新一条水压监测传感器监测数据 -- 根据设备编码数组
     */
    public List<CentermonitorTMonitoringDataWaterPressure> selectWaterPressureDataByDeviceCodes(String[] deviceCodes) {
        return centermonitorTMonitoringDeviceMapper.selectWaterPressureDataByDeviceCodes(deviceCodes);
    }

    /**
     * 查询最新一条水流速传感器监测数据 -- 根据设备编码数组
     */
    public List<CentermonitorTMonitoringDataWaterVelocity> selectWaterVelocityDataByDeviceCodes(String[] deviceCodes) {
        return centermonitorTMonitoringDeviceMapper.selectWaterVelocityDataByDeviceCodes(deviceCodes);
    }

    /**
     * 查询最新一条病虫害传感器监测数据 -- 根据设备编码数组
     */
    public List<CentermonitorTMonitoringDataInsectPests> selectInsectPestsDataByDeviceCodes(String[] deviceCodes) {
        /*图片前缀**/
        R<String> url = remoteService.selectConfigKey_fileUrl();
        List<CentermonitorTMonitoringDataInsectPests> insectPestsList = centermonitorTMonitoringDeviceMapper.selectInsectPestsDataByDeviceCodes(deviceCodes);
        insectPestsList.forEach(item ->
        {
            CentermonitorTMonitoringDataInsectPests dataInsectPests = new CentermonitorTMonitoringDataInsectPests();
            BeanUtils.copyProperties(item, dataInsectPests);
            dataInsectPests.setOldTaggingImgUrl(url.getData() + item.getOldTaggingImgUrl());
            dataInsectPests.setTaggingImgUrl(url.getData() + item.getTaggingImgUrl());
            insectPestsList.set(insectPestsList.indexOf(item), dataInsectPests);
        });
        return insectPestsList;
    }

    @Override
    public List<DeviceIoTEquipmentStatisticsVO> getIoTEquipmentStatistics(Long deptId) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        List<DeviceIoTEquipmentStatisticsVO> returnList = new ArrayList<>();
        DeviceIoTEquipmentStatisticsVO deviceIoTEquipmentStatisticsVO = new DeviceIoTEquipmentStatisticsVO();

        CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
        centermonitorTMonitoringDevice.setDeptId(deptId == null ? SecurityUtils.getLoginUser().getSysUser().getDeptId().toString() : deptId.toString());
        setSookaDataBase(centermonitorTMonitoringDevice);

        List<DeviceIoTEquipmentStatisticsResult> list = centermonitorTMonitoringDeviceMapper.getIoTEquipmentStatistics(centermonitorTMonitoringDevice);

        int totalCount = 0;
        for (DeviceIoTEquipmentStatisticsResult result : list) {
            totalCount += result.getCount();
        }
        deviceIoTEquipmentStatisticsVO.setDeviceIoTEquipmentStatisticsResult(list);
        deviceIoTEquipmentStatisticsVO.setTotalNumber(totalCount);
        returnList.add(deviceIoTEquipmentStatisticsVO);
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long executionTime = endTime - startTime; // 计算执行时间
        System.out.println("物联设备统计代码执行时间：" + executionTime + " 毫秒");
        return returnList;
    }

    @Override
    public Map<String, List> getOnLineSensorStatistics(Long deptId) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        List<SysDept> sysDepartments = new ArrayList<>();
        Map<String, List> map = new HashMap<>();
        List<DeviceOnLineSensorStatisticsVO> deviceOnLineList = new ArrayList<>();
        List<DeviceOnLineSensorStatisticsVO> deviceOffLineList = new ArrayList<>();
        R<List<SysDept>> sysDeptList = remoteService.selectChildrenCountyOrVillagesDeptListByDeptId(deptId == null ? SecurityUtils.getLoginUser().getSysUser().getDeptId() : deptId);
        sysDepartments.addAll(sysDeptList.getData());

        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        List<Future<DeviceOnLineSensorStatisticsVO>> deviceOnLineFutures = new ArrayList<>();
        List<Future<DeviceOnLineSensorStatisticsVO>> deviceOffLineFutures = new ArrayList<>();

        for (SysDept var : sysDepartments) {
            Future<DeviceOnLineSensorStatisticsVO> deviceOnLineFuture = executorService.submit(() -> {
                CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
                centermonitorTMonitoringDevice.setDeptId(var.getDeptId().toString());
                centermonitorTMonitoringDevice.setWorkingStatus("0");
                setSookaDataBase(centermonitorTMonitoringDevice);
                List<DeviceIoTEquipmentStatisticsResult> list = centermonitorTMonitoringDeviceMapper.getOnLineSensorStatistics(centermonitorTMonitoringDevice);

                DeviceOnLineSensorStatisticsVO deviceOnLineSensorStatisticsVO = new DeviceOnLineSensorStatisticsVO();
                deviceOnLineSensorStatisticsVO.setName(var.getDeptName());
                deviceOnLineSensorStatisticsVO.setDeviceTypeOne(list.get(0).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeTwo(list.get(1).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeThree(list.get(2).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeFour(list.get(3).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeFive(list.get(4).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeSix(list.get(5).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeSeven(list.get(6).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeEight(list.get(7).getCount());
                return deviceOnLineSensorStatisticsVO;
            });

            deviceOnLineFutures.add(deviceOnLineFuture);
        }

        for (SysDept var : sysDepartments) {
            Future<DeviceOnLineSensorStatisticsVO> deviceOffLineFuture = executorService.submit(() -> {
                CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
                centermonitorTMonitoringDevice.setDeptId(var.getDeptId().toString());
                centermonitorTMonitoringDevice.setWorkingStatus("1");
                setSookaDataBase(centermonitorTMonitoringDevice);
                List<DeviceIoTEquipmentStatisticsResult> list = centermonitorTMonitoringDeviceMapper.getOnLineSensorStatistics(centermonitorTMonitoringDevice);

                DeviceOnLineSensorStatisticsVO deviceOnLineSensorStatisticsVO = new DeviceOnLineSensorStatisticsVO();
                deviceOnLineSensorStatisticsVO.setName(var.getDeptName());
                deviceOnLineSensorStatisticsVO.setDeviceTypeOne(list.get(0).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeTwo(list.get(1).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeThree(list.get(2).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeFour(list.get(3).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeFive(list.get(4).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeSix(list.get(5).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeSeven(list.get(6).getCount());
                deviceOnLineSensorStatisticsVO.setDeviceTypeEight(list.get(7).getCount());
                return deviceOnLineSensorStatisticsVO;
            });

            deviceOffLineFutures.add(deviceOffLineFuture);
        }

        executorService.shutdown();

        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        for (Future<DeviceOnLineSensorStatisticsVO> deviceOnLineFuture : deviceOnLineFutures) {
            try {
                deviceOnLineList.add(deviceOnLineFuture.get());
            } catch (InterruptedException | ExecutionException e) {
                // 处理异常
            }
        }

        for (Future<DeviceOnLineSensorStatisticsVO> deviceOffLineFuture : deviceOffLineFutures) {
            try {
                deviceOffLineList.add(deviceOffLineFuture.get());
            } catch (InterruptedException | ExecutionException e) {
                // 处理异常
            }
        }
        map.put("deviceOnLineList", deviceOnLineList);
        map.put("deviceOffLineList", deviceOffLineList);
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long executionTime = endTime - startTime; // 计算执行时间
        System.out.println("区县传感器统计代码执行时间：" + executionTime + " 毫秒");
        return map;
    }

    /**
     * 离线原因数量地区分布
     */
    @Override
    public List<Map<String, List>> getOfflineReasonCountStatistics(List<SysDept> sysDepartments) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        int threadPoolSize = 8; // 设置线程池大小
        ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize); // 创建固定大小的线程池

        List<Map<String, List>> list = new ArrayList<>();
        Map<String, List> map = new HashMap<>();
//        List<SysDept> sysDepartments = new ArrayList();
//        R<List<SysDept>> sysDeptList = remoteService.selectChildrenCountyOrVillagesDeptListByDeptId(deptId == null ? SecurityUtils.getLoginUser().getSysUser().getDeptId() : deptId);
//        sysDepartments.addAll(sysDeptList.getData());

        try {
            CountDownLatch latch = new CountDownLatch(8); // 创建CountDownLatch，用于等待所有线程执行完毕
            for (int i = 1; i <= 8; i++) {
                int finalI = i;
                executor.execute(() -> {
                    List<DeviceOfflineSensorStatisticsVO> result = new ArrayList<>();
                    for (SysDept var : sysDepartments) {
                        CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
                        centermonitorTMonitoringDevice.setDeptId(var.getDeptId().toString());
                        centermonitorTMonitoringDevice.setDeviceType(String.valueOf(finalI));
                        setSookaDataBase(centermonitorTMonitoringDevice);
                        List<DeviceIoTEquipmentStatisticsResult> newlist = centermonitorTMonitoringDeviceMapper.getOfflineReasonCountStatistics(centermonitorTMonitoringDevice);

                        DeviceOfflineSensorStatisticsVO deviceOfflineSensorStatisticsVO = new DeviceOfflineSensorStatisticsVO();
                        deviceOfflineSensorStatisticsVO.setName(var.getDeptName());
                        deviceOfflineSensorStatisticsVO.setDeviceTypeOne(newlist.get(0).getCount());
                        deviceOfflineSensorStatisticsVO.setDeviceTypeTwo(newlist.get(1).getCount());
                        deviceOfflineSensorStatisticsVO.setDeviceTypeThree(newlist.get(2).getCount());
                        deviceOfflineSensorStatisticsVO.setDeviceTypeFour(newlist.get(3).getCount());
                        result.add(deviceOfflineSensorStatisticsVO);
                    }
                    map.put("deviceType" + finalI, result);
                    latch.countDown(); // 当前线程执行完毕，倒计时减一
                });
            }

            latch.await(); // 等待所有线程执行完毕

            list.add(map);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // 处理异常
        } finally {
            executor.shutdown(); // 关闭线程池
        }
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long executionTime = endTime - startTime; // 计算执行时间
        System.out.println("离线原因数量地区分布代码执行时间：" + executionTime + " 毫秒");
        return list;
    }

//    public void getDeviceDataListToJudgeWorkingStatus(CentermonitorTMonitoringDevice device){
//        if()

    //        return centermonitorTMonitoringDeviceMapper.getDeviceListToJudgeWorkingStatus(device);
//    }

    /**
     * 在线设备分析
     */
    @Override
    public Map<String, List> getDeviceAnalysis(Long deptId) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
        setSookaDataBase(centermonitorTMonitoringDevice);
        centermonitorTMonitoringDevice.setDeptId(deptId == null ? SecurityUtils.getLoginUser().getSysUser().getDeptId().toString() : deptId.toString());
        List<CentermonitorTMonitoringDevice> device = centermonitorTMonitoringDeviceMapper.getDeviceAnalysis(centermonitorTMonitoringDevice);
        List<String> nameList = new ArrayList<>();
        List<Integer> onList = new ArrayList<>();
        List<Integer> offList = new ArrayList<>();
        for (CentermonitorTMonitoringDevice tar : device) {
            nameList.add(tar.getDictName());
            offList.add(tar.getDeviceOffline());
            onList.add(tar.getDeviceOnline());
        }
        Map<String, List> resultMap = new HashMap<>();
        resultMap.put("dictName", nameList);
        resultMap.put("deviceOffline", offList);
        resultMap.put("deviceOnline", onList);
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long executionTime = endTime - startTime; // 计算执行时间
        System.out.println("在线设备分析代码执行时间：" + executionTime + " 毫秒");
        return resultMap;
    }

    /**
     * 设备故障分布
     */
    @Override
    public Map<String, List> getFaultDistribution(Long deptId) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        Map<String, List> returnMap = new HashMap<>();
        List<SysDept> sysDepartments = new ArrayList();
        List<DeviceEquipmentFaultStatistics> deviceEquipmentFaultList = new ArrayList<>();
        R<List<SysDept>> sysDeptList = remoteService.selectChildrenCountyOrVillagesDeptListByDeptId(deptId == null ? SecurityUtils.getLoginUser().getSysUser().getDeptId() : deptId);
        sysDepartments.addAll(sysDeptList.getData());
        for (SysDept var : sysDepartments) {
            List<Map<String, String>> rertunList = new ArrayList<>();
            CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
            centermonitorTMonitoringDevice.setDeptId(var.getDeptId().toString());
            setSookaDataBase(centermonitorTMonitoringDevice);
            List<CentermonitorTMonitoringDevice> deviceList = centermonitorTMonitoringDeviceMapper.getFaultDistribution(centermonitorTMonitoringDevice);
            DeviceEquipmentFaultStatistics deviceEquipmentFaultStatistics = new DeviceEquipmentFaultStatistics();
            deviceEquipmentFaultStatistics.setDeptName(var.getDeptName());
            deviceEquipmentFaultStatistics.setDeptId(var.getDeptId());
            for (CentermonitorTMonitoringDevice tar : deviceList) {
                Map<String, String> map = new HashMap<>();
                map.put("name", tar.getDictName());
                map.put("value", tar.getDeviceOnline().toString());
                rertunList.add(map);
            }
            deviceEquipmentFaultStatistics.setDeviceList(rertunList);
            deviceEquipmentFaultList.add(deviceEquipmentFaultStatistics);
        }
        List<Map<String, String>> deptInfoList = sysDepartments.stream()
                .map(item -> {
                    Map<String, String> deptInfo = new HashMap<>();
                    deptInfo.put("deptId", String.valueOf(item.getDeptId()));
                    deptInfo.put("deptName", item.getDeptName());
                    return deptInfo;
                })
                .collect(Collectors.toList());
        returnMap.put("deptInfoList", deptInfoList);
        returnMap.put("equipmentFaultList", deviceEquipmentFaultList);
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long executionTime = endTime - startTime; // 计算执行时间
        System.out.println("设备故障分布代码执行时间：" + executionTime + " 毫秒");
        return returnMap;
    }

    /**
     * 采集数量分析
     */
    @Override
    public Map<String, List> getSensorDataCount(Long deptId) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
        centermonitorTMonitoringDevice.setDeptId(deptId == null ? SecurityUtils.getLoginUser().getSysUser().getDeptId().toString() : deptId.toString());
        setSookaDataBase(centermonitorTMonitoringDevice);
        List<CentermonitorTMonitoringDevice> device = centermonitorTMonitoringDeviceMapper.getSensorDataCount(centermonitorTMonitoringDevice);
        List<String> nameList = new ArrayList<>();
        List<Integer> onList = new ArrayList<>();
        for (CentermonitorTMonitoringDevice tar : device) {
            nameList.add(tar.getSensorType());
            onList.add(tar.getDataCount());
        }
        Map<String, List> resultMap = new HashMap<>();
        resultMap.put("sensorType", nameList);
        resultMap.put("dataCount", onList);
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long executionTime = endTime - startTime; // 计算执行时间
        System.out.println("采集数量分析代码执行时间：" + executionTime + " 毫秒");
        return resultMap;
    }

    /**
     * 物联广场右上角统计数
     */
    @Override
    public R getDeviceSquareNumber(Long deptId) {
        CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
        setSookaDataBase(centermonitorTMonitoringDevice);
        centermonitorTMonitoringDevice.setDeptId(deptId == null ? SecurityUtils.getLoginUser().getSysUser().getDeptId().toString() : deptId.toString());
        List<CentermonitorTMonitoringDevice> device = centermonitorTMonitoringDeviceMapper.getDeviceSquareNumber(centermonitorTMonitoringDevice);
        List<Integer> dataList = new ArrayList<>();
        List<Integer> onList = new ArrayList<>();
        for (CentermonitorTMonitoringDevice tar : device) {
            if (tar != null) {
                dataList.add(tar.getDataCount());
                onList.add(tar.getDeviceOffline());
            }
        }
        Map<String, List> resultMap = new HashMap<>();
        resultMap.put("dataCount", dataList);
        resultMap.put("deviceOffline", onList);
        return R.ok(resultMap);
    }

    /**
     * 物联网中台统一入口
     */
    @Override
    public R getInternetOfThings(Long deptId) {
        log.info("物联网中台统一入口");
        log.info("开始时间:{}", System.currentTimeMillis());
        Map<String, List<?>> map = new HashMap<>();
        List<SysDept> sysDepartments = new ArrayList<>();
        List<SysDept> list = SecurityUtils.getLoginUser().getSysUser().getDepts();
        if (deptId != null) {
            R<List<SysDept>> sysDeptList = remoteService.selectChildrenCountyOrVillagesDeptListByDeptId(deptId);
            sysDepartments.addAll(sysDeptList.getData());
        } else {
            for (SysDept var : list) {
                R<List<SysDept>> sysDeptList = remoteService.selectChildrenCountyOrVillagesDeptListByDeptId(var.getDeptId());
                sysDepartments.addAll(sysDeptList.getData());
            }
        }
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        Future<Map<String, List>> getSensorDataCount = executorService.submit(() -> {
            return this.getSensorDataCount(deptId);
        });
        Future<Map<String, List>> getDeviceAnalysis = executorService.submit(() -> {
            return this.getDeviceAnalysis(deptId);
        });
        Future<List<DeviceIoTEquipmentStatisticsVO>> getIoTEquipmentStatistics = executorService.submit(() -> {
            return this.getIoTEquipmentStatistics(deptId);
        });
        Future<Map<String, List>> getOnLineSensorStatistics = executorService.submit(() -> {
            return this.getOnLineSensorStatistics(deptId);
        });
        Future<Map<String, List>> getFaultDistribution = executorService.submit(() -> {
            return this.getFaultDistribution(deptId);
        });
        Future<List<Map<String, List>>> getOfflineReasonCountStatistics = executorService.submit(() -> {
            return this.getOfflineReasonCountStatistics(sysDepartments);
        });
        // 等待所有任务完成
        executorService.shutdown();
        try {
            //采集数量分析
            map.put("sensorType", getSensorDataCount.get().get("sensorType"));
            map.put("dataCount", getSensorDataCount.get().get("dataCount"));
            //在线设备分析
            map.put("dictName", getDeviceAnalysis.get().get("dictName"));
            map.put("deviceOffline", getDeviceAnalysis.get().get("deviceOffline"));
            map.put("deviceOnline", getDeviceAnalysis.get().get("deviceOnline"));
            //物联设备统计
            List<List<DeviceIoTEquipmentStatisticsVO>> iotEquipmentStatistics = Collections.singletonList(getIoTEquipmentStatistics.get());
            map.put("iotEquipmentStatistics", iotEquipmentStatistics);
            //区县传感器统计
            map.put("deviceOnLineList", getOnLineSensorStatistics.get().get("deviceOnLineList"));
            map.put("deviceOffLineList", getOnLineSensorStatistics.get().get("deviceOffLineList"));
            //设备故障分布
            map.put("deptInfoList", getFaultDistribution.get().get("deptInfoList"));
            map.put("equipmentFaultList", getFaultDistribution.get().get("equipmentFaultList"));
            //离线原因数量地区分布
            List<List<Map<String, List>>> offlineReasonCountStatistics = Collections.singletonList(getOfflineReasonCountStatistics.get());
            map.put("offlineReasonCountStatistics", offlineReasonCountStatistics);
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (Exception e) {
            // 处理中断异常
        }


        // 线程1：采集数量分析
//        Thread sensorDataCountThread = new Thread(() -> {
//            Map<String, List<?>> sensorDataCount = new HashMap<>();
//            sensorDataCount.put("sensorType", this.getSensorDataCount(deptId).get("sensorType"));
//            sensorDataCount.put("dataCount", this.getSensorDataCount(deptId).get("dataCount"));
//            map.put("sensorDataCount", Collections.singletonList(sensorDataCount));
//            log.info("sensorDataCountThread 完成");
//        });
//
//        // 线程2：在线设备分析
//        Thread deviceAnalysisThread = new Thread(() -> {
//            Map<String, List<?>> deviceAnalysis = new HashMap<>();
//            deviceAnalysis.put("dictName", this.getDeviceAnalysis(deptId).get("dictName"));
//            deviceAnalysis.put("deviceOffline", this.getDeviceAnalysis(deptId).get("deviceOffline"));
//            deviceAnalysis.put("deviceOnline", this.getDeviceAnalysis(deptId).get("deviceOnline"));
//            map.put("deviceAnalysis", Collections.singletonList(deviceAnalysis));
//            log.info("deviceAnalysisThread 完成");
//        });
//
//        // 线程3：物联设备统计
//        Thread iotEquipmentStatisticsThread = new Thread(() -> {
//            List<List<DeviceIoTEquipmentStatisticsVO>> iotEquipmentStatistics = Collections.singletonList(this.getIoTEquipmentStatistics(deptId));
//            map.put("iotEquipmentStatistics", iotEquipmentStatistics);
//            log.info("iotEquipmentStatisticsThread 完成");
//        });
//
//        // 线程4：区县传感器统计
//        Thread onlineSensorStatisticsThread = new Thread(() -> {
//            Map<String, List<?>> onlineSensorStatistics = new HashMap<>();
//            onlineSensorStatistics.put("deviceOnLineList", this.getOnLineSensorStatistics(sysDepartments).get("deviceOnLineList"));
//            onlineSensorStatistics.put("deviceOffLineList", this.getOnLineSensorStatistics(sysDepartments).get("deviceOffLineList"));
//            map.put("onlineSensorStatistics", Collections.singletonList(onlineSensorStatistics));
//            log.info("onlineSensorStatisticsThread 完成");
//        });
//
//        // 线程5：设备故障分布
//        Thread faultDistributionThread = new Thread(() -> {
//            Map<String, List<?>> faultDistribution = new HashMap<>();
//            faultDistribution.put("deptInfoList", this.getFaultDistribution(sysDepartments).get("deptInfoList"));
//            faultDistribution.put("equipmentFaultList", this.getFaultDistribution(sysDepartments).get("equipmentFaultList"));
//            map.put("faultDistribution", Collections.singletonList(faultDistribution));
//            log.info("faultDistributionThread 完成");
//        });
//
//        // 线程6：离线原因数量地区分布
//        Thread offlineReasonCountStatisticsThread = new Thread(() -> {
//            List<List<Map<String, List>>> offlineReasonCountStatistics = Collections.singletonList(this.getOfflineReasonCountStatistics(sysDepartments));
//            map.put("offlineReasonCountStatistics", offlineReasonCountStatistics);
//            log.info("offlineReasonCountStatisticsThread 完成");
//        });
//
//        // 启动线程
//        sensorDataCountThread.start();
//        deviceAnalysisThread.start();
//        iotEquipmentStatisticsThread.start();
//        onlineSensorStatisticsThread.start();
//        faultDistributionThread.start();
//        offlineReasonCountStatisticsThread.start();
//
//        // 等待所有线程执行完成
//        try {
//            sensorDataCountThread.join();
//            deviceAnalysisThread.join();
//            iotEquipmentStatisticsThread.join();
//            onlineSensorStatisticsThread.join();
//            faultDistributionThread.join();
//            offlineReasonCountStatisticsThread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        log.info("结束时间:{}", System.currentTimeMillis());
        return R.ok(map);
    }

    @Override
    public R getIoTEquipmentDetails(Long deptId, String deviceCode, String deviceType) {
        //1:水质环境;2:土壤墒情;4:病虫害监测;5:大气监测 ;6:水压监测;7:水流速;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        LocalDate date = LocalDate.now();
        for (int i = 1; i <= 7; i++) {
            LocalDate currentDate = date.minusDays(i);
            dateList.add(formatter.format(currentDate));
        }
        deptId = null == deptId ? SecurityUtils.getLoginUser().getSysUser().getDeptId() : deptId;
        CentermonitorTMonitoringDevice centermonitorTMonitoringDevice = new CentermonitorTMonitoringDevice();
        centermonitorTMonitoringDevice.setDeptId(deptId.toString());
        centermonitorTMonitoringDevice.setDeviceCode(deviceCode);
        centermonitorTMonitoringDevice.setDeviceType(deviceType);
        CenterMonitorIoTEquipmentDetailsVO centerMonitorIoTEquipmentDetailsVO = this.centermonitorTMonitoringDeviceMapper.getIoTEquipmentDetails(centermonitorTMonitoringDevice);
        if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(centerMonitorIoTEquipmentDetailsVO)) {
            centerMonitorIoTEquipmentDetailsVO.setDateList(dateList);
            switch (deviceType) {
                case "1":
                    centerMonitorIoTEquipmentDetailsVO.setNameList(selectIoTWaterQuality(deviceCode).get("nameList"));
                    Map<String, List> waterQualityMap = selectIoTWaterQuality(deviceCode);
                    waterQualityMap.remove("nameList");
                    centerMonitorIoTEquipmentDetailsVO.setDataSourceList(waterQualityMap);
//                    centerMonitorIoTEquipmentDetailsVO.setHydraulicPressure(Optional.ofNullable(selectIoTWaterQuality(deviceCode).get(0).getWaterPh()).orElse("0"));
//                    centerMonitorIoTEquipmentDetailsVO.setReportingDate(Optional.ofNullable(selectIoTWaterQuality(deviceCode).get(0).getCreateTime()).orElse(formatter.format(LocalDate.now())));
                    centerMonitorIoTEquipmentDetailsVO.setAlarmType("水质环境");
                    centerMonitorIoTEquipmentDetailsVO.setRemark("水质环境阈值报警");
                    break;
                case "2":
                    centerMonitorIoTEquipmentDetailsVO.setNameList(selectIoTSoil(deviceCode).get("nameList"));
                    Map<String, List> soilMap = selectIoTSoil(deviceCode);
                    soilMap.remove("nameList");
                    centerMonitorIoTEquipmentDetailsVO.setDataSourceList(soilMap);
//                    centerMonitorIoTEquipmentDetailsVO.setHydraulicPressure(Optional.ofNullable(selectIoTSoil(deviceCode).get(0).getPh()).orElse("0"));
//                    centerMonitorIoTEquipmentDetailsVO.setReportingDate(Optional.ofNullable(selectIoTSoil(deviceCode).get(0).getCreateTime()).orElse(formatter.format(LocalDate.now())));
                    centerMonitorIoTEquipmentDetailsVO.setAlarmType("土壤墒情");
                    centerMonitorIoTEquipmentDetailsVO.setRemark("土壤墒情阈值报警");
                    break;
                case "4":
                    centerMonitorIoTEquipmentDetailsVO.setNameList(getIoTInsectPests(deviceCode).get("nameList"));
                    Map<String, List> insectPestsMap = getIoTInsectPests(deviceCode);
                    insectPestsMap.remove("nameList");
                    centerMonitorIoTEquipmentDetailsVO.setDataSourceList(insectPestsMap);
//                    centerMonitorIoTEquipmentDetailsVO.setNameList(Collections.singletonList("newCount"));
//                    centerMonitorIoTEquipmentDetailsVO.setHydraulicPressure(Optional.ofNullable(getIoTInsectPests(deviceCode).get(0).getNewCount()).orElse(0).toString());
//                    centerMonitorIoTEquipmentDetailsVO.setReportingDate(Optional.ofNullable(getIoTInsectPests(deviceCode).get(0).getCreateTime()).orElse(formatter.format(LocalDate.now())));
                    centerMonitorIoTEquipmentDetailsVO.setAlarmType("病虫害监测");
                    centerMonitorIoTEquipmentDetailsVO.setRemark("病虫害监测阈值报警");
                    break;
                case "5":
                    centerMonitorIoTEquipmentDetailsVO.setNameList(getIoTAtmosphereMonitoring(deviceCode).get("nameList"));
                    Map<String, List> atmosphereMonitoringMap = getIoTAtmosphereMonitoring(deviceCode);
                    atmosphereMonitoringMap.remove("nameList");
                    centerMonitorIoTEquipmentDetailsVO.setDataSourceList(atmosphereMonitoringMap);
//                    centerMonitorIoTEquipmentDetailsVO.setNameList(Arrays.asList("temperature", "humidity", "nitrogenDioxide", "sulfurDioxide","carbonMonoxide","fineParticle"));
//                centerMonitorIoTEquipmentDetailsVO.setHydraulicPressure(Optional.ofNullable(getIoTAtmosphereMonitoring(deviceCode).get(0).getNewCount()).orElse(0).toString());
//                    centerMonitorIoTEquipmentDetailsVO.setReportingDate(Optional.ofNullable(getIoTAtmosphereMonitoring(deviceCode).get(0).getCreateTime()).orElse(formatter.format(LocalDate.now())));
                    centerMonitorIoTEquipmentDetailsVO.setAlarmType("大气监测");
                    centerMonitorIoTEquipmentDetailsVO.setRemark("大气监测阈值报警");
                    break;
                case "6":
                    centerMonitorIoTEquipmentDetailsVO.setNameList(getIoTWaterPressure(deviceCode).get("nameList"));
                    Map<String, List> waterPressureMap = getIoTWaterPressure(deviceCode);
                    waterPressureMap.remove("nameList");
                    centerMonitorIoTEquipmentDetailsVO.setDataSourceList(waterPressureMap);
//                    centerMonitorIoTEquipmentDetailsVO.setNameList(Arrays.asList("hydraulicValue", "hydraulicThresholdMin", "hydraulicThresholdMax"));
//                    centerMonitorIoTEquipmentDetailsVO.setHydraulicPressure(Optional.ofNullable(getIoTWaterPressure(deviceCode).get(0).getHydraulicThresholdMin()).orElse("0") + "-" + Optional.ofNullable(getIoTWaterPressure(deviceCode).get(0).getHydraulicThresholdMax()).orElse("0"));
//                    centerMonitorIoTEquipmentDetailsVO.setReportingDate(Optional.ofNullable(getIoTWaterPressure(deviceCode).get(0).getCreateTime()).orElse(formatter.format(LocalDate.now())));
                    centerMonitorIoTEquipmentDetailsVO.setAlarmType("水压监测");
                    centerMonitorIoTEquipmentDetailsVO.setRemark("水压监测阈值报警");
                    break;
                case "7":
                    centerMonitorIoTEquipmentDetailsVO.setNameList(getIoTWaterVelocity(deviceCode).get("nameList"));
                    Map<String, List> waterVelocityMap = getIoTWaterVelocity(deviceCode);
                    waterVelocityMap.remove("nameList");
                    centerMonitorIoTEquipmentDetailsVO.setDataSourceList(waterVelocityMap);
//                    centerMonitorIoTEquipmentDetailsVO.setNameList(Arrays.asList("z", "v1", "z1", "q"));
//                centerMonitorIoTEquipmentDetailsVO.setHydraulicPressure(Optional.ofNullable(getIoTWaterVelocity(deviceCode).get(0).getHydraulicThresholdMin()).orElse("0") + "-" + Optional.ofNullable(getIoTWaterPressure(deviceCode).get(0).getHydraulicThresholdMax()).orElse("0"));
//                    centerMonitorIoTEquipmentDetailsVO.setReportingDate(Optional.ofNullable(getIoTWaterVelocity(deviceCode).get(0).getCreateTime()).orElse(formatter.format(LocalDate.now())));
                    centerMonitorIoTEquipmentDetailsVO.setAlarmType("水流速");
                    centerMonitorIoTEquipmentDetailsVO.setRemark("水流速阈值报警");
                    break;
            }
        }
        return R.ok(centerMonitorIoTEquipmentDetailsVO);
    }

    public Map<String, List> selectIoTWaterQuality(String deviceCode) {
        List<CentermonitorTMonitoringDataWaterQualityIoTResult> returnList = new ArrayList<>(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.now();
        for (int i = 1; i <= 7; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = formatter.format(currentDate);
            CentermonitorTMonitoringDataWaterQualityIoTResult addEntity = centermonitorTMonitoringDeviceMapper.getIoTWaterQuality(deviceCode, formattedDate);
            if (org.apache.commons.lang3.ObjectUtils.isEmpty(addEntity)) {
                CentermonitorTMonitoringDataWaterQualityIoTResult centermonitorTMonitoringDataWaterQualityIoTResult = new CentermonitorTMonitoringDataWaterQualityIoTResult(formattedDate, "0", "0", "0", "0", "0");
                returnList.add(centermonitorTMonitoringDataWaterQualityIoTResult);
            } else {
                addEntity.setDate(formattedDate);
                returnList.add(addEntity);
            }
        }
        List<String> waterPhList = returnList.stream().map(CentermonitorTMonitoringDataWaterQualityIoTResult::getWaterPh).collect(Collectors.toList());
        List<String> waterTemperatureList = returnList.stream().map(CentermonitorTMonitoringDataWaterQualityIoTResult::getWaterTemperature).collect(Collectors.toList());
        List<String> waterQualitySuspensionList = returnList.stream().map(CentermonitorTMonitoringDataWaterQualityIoTResult::getWaterQualitySuspension).collect(Collectors.toList());
        List<String> conductivityList = returnList.stream().map(CentermonitorTMonitoringDataWaterQualityIoTResult::getConductivity).collect(Collectors.toList());
        List<String> codList = returnList.stream().map(CentermonitorTMonitoringDataWaterQualityIoTResult::getCod).collect(Collectors.toList());
        Map<String, List> map = new HashMap<>();
        map.put("waterPh", waterPhList);
        map.put("waterTemperature", waterTemperatureList);
        map.put("waterQualitySuspension", waterQualitySuspensionList);
        map.put("conductivity", conductivityList);
        map.put("cod", codList);
        List<String> valueList = Arrays.asList("waterPh", "waterTemperature", "waterQualitySuspension", "conductivity", "cod");
        List<String> keyList = Arrays.asList("水中PH", "水温", "水质悬浮物", "水中电导率", "化学需氧量");
        List<Map<String, String>> nameList = IntStream.range(0, valueList.size())
                .mapToObj(i -> {
                    Map<String, String> nameMap = new HashMap<>();
                    nameMap.put("name", keyList.get(i));
                    nameMap.put("value", valueList.get(i));
                    return nameMap;
                })
                .collect(Collectors.toList());
        map.put("nameList",nameList);
        return map;
    }

    public Map<String, List> selectIoTSoil(String deviceCode) {
        List<CentermonitorTMonitoringDataSoilMoistureIoTResult> returnList = new ArrayList<>(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.now();
        for (int i = 1; i <= 7; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = formatter.format(currentDate);
            CentermonitorTMonitoringDataSoilMoistureIoTResult addEntity = centermonitorTMonitoringDeviceMapper.getIoTSoil(deviceCode, formattedDate);
            if (org.apache.commons.lang3.ObjectUtils.isEmpty(addEntity)) {
                CentermonitorTMonitoringDataSoilMoistureIoTResult centermonitorTMonitoringDataSoilMoistureIoTResult = new CentermonitorTMonitoringDataSoilMoistureIoTResult(formattedDate, "0", "0", "0", "0", "0", "0", "0");
                returnList.add(centermonitorTMonitoringDataSoilMoistureIoTResult);
            } else {
                addEntity.setDate(formattedDate);
                returnList.add(addEntity);
            }
        }

        List<String> temperatureList = returnList.stream().map(CentermonitorTMonitoringDataSoilMoistureIoTResult::getTemperature).collect(Collectors.toList());
        List<String> humidityList = returnList.stream().map(CentermonitorTMonitoringDataSoilMoistureIoTResult::getHumidity).collect(Collectors.toList());
        List<String> phList = returnList.stream().map(CentermonitorTMonitoringDataSoilMoistureIoTResult::getPh).collect(Collectors.toList());
        List<String> conductivityList = returnList.stream().map(CentermonitorTMonitoringDataSoilMoistureIoTResult::getConductivity).collect(Collectors.toList());
        List<String> nitrogenList = returnList.stream().map(CentermonitorTMonitoringDataSoilMoistureIoTResult::getNitrogen).collect(Collectors.toList());
        List<String> phosphorusList = returnList.stream().map(CentermonitorTMonitoringDataSoilMoistureIoTResult::getPhosphorus).collect(Collectors.toList());
        List<String> potassiumList = returnList.stream().map(CentermonitorTMonitoringDataSoilMoistureIoTResult::getPotassium).collect(Collectors.toList());
        Map<String, List> map = new HashMap<>();
        map.put("temperature", temperatureList);
        map.put("humidity", humidityList);
        map.put("ph", phList);
        map.put("conductivity", conductivityList);
        map.put("nitrogen", nitrogenList);
        map.put("phosphorus", phosphorusList);
        map.put("potassium", potassiumList);
        List<String> valueList = Arrays.asList("temperature", "humidity","ph", "conductivity", "nitrogen","phosphorus","potassium");
        List<String> keyList = Arrays.asList("温度", "湿度", "ph值", "导电率", "氮含量", "磷含量", "钾含量");
        List<Map<String, String>> nameList = IntStream.range(0, valueList.size())
                .mapToObj(i -> {
                    Map<String, String> nameMap = new HashMap<>();
                    nameMap.put("name", keyList.get(i));
                    nameMap.put("value", valueList.get(i));
                    return nameMap;
                })
                .collect(Collectors.toList());
        map.put("nameList",nameList);
        return map;
    }

    public Map<String, List> getIoTInsectPests(String deviceCode) {
        List<CentermonitorTMonitoringDataInsectPestsIoTResult> returnList = new ArrayList<>(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.now();
        for (int i = 1; i <= 7; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = formatter.format(currentDate);
            CentermonitorTMonitoringDataInsectPestsIoTResult addEntity = centermonitorTMonitoringDeviceMapper.getIoTInsectPests(deviceCode, formattedDate);
            if (org.apache.commons.lang3.ObjectUtils.isEmpty(addEntity)) {
                CentermonitorTMonitoringDataInsectPestsIoTResult centermonitorTMonitoringDataInsectPestsIoTResult = new CentermonitorTMonitoringDataInsectPestsIoTResult(formattedDate, 0);
                returnList.add(centermonitorTMonitoringDataInsectPestsIoTResult);
            } else {
                addEntity.setDate(formattedDate);
                returnList.add(addEntity);
            }
        }
        List<Integer> newCountList = returnList.stream().map(CentermonitorTMonitoringDataInsectPestsIoTResult::getNewCount).collect(Collectors.toList());
        Map<String, List> map = new HashMap<>();
        map.put("newCount", newCountList);
        List<String> valueList = Collections.singletonList("newCount");
        List<String> keyList = Collections.singletonList("识别数量");
        List<Map<String, String>> nameList = IntStream.range(0, valueList.size())
                .mapToObj(i -> {
                    Map<String, String> nameMap = new HashMap<>();
                    nameMap.put("name", keyList.get(i));
                    nameMap.put("value", valueList.get(i));
                    return nameMap;
                })
                .collect(Collectors.toList());
        map.put("nameList",nameList);
        return map;
    }

    public Map<String, List> getIoTAtmosphereMonitoring(String deviceCode) {
        List<CentermonitorTMonitoringDataAtmosphereIoTResult> returnList = new ArrayList<>(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.now();
        for (int i = 1; i <= 7; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = formatter.format(currentDate);
            CentermonitorTMonitoringDataAtmosphereIoTResult addEntity = centermonitorTMonitoringDeviceMapper.getIoTAtmosphere(deviceCode, formattedDate);
            if (org.apache.commons.lang3.ObjectUtils.isEmpty(addEntity)) {
                CentermonitorTMonitoringDataAtmosphereIoTResult centermonitorTMonitoringDataAtmosphereIoTResult = new CentermonitorTMonitoringDataAtmosphereIoTResult(formattedDate, "0", "0", "0", "0", "0", "0");
                returnList.add(centermonitorTMonitoringDataAtmosphereIoTResult);
            } else {
                addEntity.setDate(formattedDate);
                returnList.add(addEntity);
            }
        }
        List<String> temperatureList = returnList.stream().map(CentermonitorTMonitoringDataAtmosphereIoTResult::getTemperature).collect(Collectors.toList());
        List<String> humidityList = returnList.stream().map(CentermonitorTMonitoringDataAtmosphereIoTResult::getHumidity).collect(Collectors.toList());
        List<String> nitrogenDioxideList = returnList.stream().map(CentermonitorTMonitoringDataAtmosphereIoTResult::getNitrogenDioxide).collect(Collectors.toList());
        List<String> sulfurDioxideList = returnList.stream().map(CentermonitorTMonitoringDataAtmosphereIoTResult::getSulfurDioxide).collect(Collectors.toList());
        List<String> carbonMonoxideList = returnList.stream().map(CentermonitorTMonitoringDataAtmosphereIoTResult::getCarbonMonoxide).collect(Collectors.toList());
        List<String> fineParticleList = returnList.stream().map(CentermonitorTMonitoringDataAtmosphereIoTResult::getFineParticle).collect(Collectors.toList());
        Map<String, List> map = new HashMap<>();
        map.put("temperature", temperatureList);
        map.put("humidity", humidityList);
        map.put("nitrogenDioxide", nitrogenDioxideList);
        map.put("sulfurDioxide", sulfurDioxideList);
        map.put("carbonMonoxide", carbonMonoxideList);
        map.put("fineParticle", fineParticleList);
        List<String> valueList = Arrays.asList("temperature", "humidity", "nitrogenDioxide", "sulfurDioxide","carbonMonoxide","fineParticle");
        List<String> keyList = Arrays.asList("温度", "湿度", "二氧化氮", "二氧化硫","一氧化碳","可吸入细颗粒（pm2.5）");
        List<Map<String, String>> nameList = IntStream.range(0, valueList.size())
                .mapToObj(i -> {
                    Map<String, String> nameMap = new HashMap<>();
                    nameMap.put("name", keyList.get(i));
                    nameMap.put("value", valueList.get(i));
                    return nameMap;
                })
                .collect(Collectors.toList());
        map.put("nameList",nameList);
        return map;
    }


    public Map<String, List> getIoTWaterPressure(String deviceCode) {
        List<CentermonitorTMonitoringDataWaterPressureIoTResult> returnList = new ArrayList<>(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.now();
        for (int i = 1; i <= 7; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = formatter.format(currentDate);
            CentermonitorTMonitoringDataWaterPressureIoTResult addEntity = centermonitorTMonitoringDeviceMapper.getIoTWaterPressure(deviceCode, formattedDate);
            if (org.apache.commons.lang3.ObjectUtils.isEmpty(addEntity)) {
                CentermonitorTMonitoringDataWaterPressureIoTResult centermonitorTMonitoringDataWaterPressureIoTResult = new CentermonitorTMonitoringDataWaterPressureIoTResult(formattedDate, "0", "0", "0");
                returnList.add(centermonitorTMonitoringDataWaterPressureIoTResult);
            } else {
                addEntity.setDate(formattedDate);
                returnList.add(addEntity);
            }
        }
        List<String> hydraulicValueList = returnList.stream().map(CentermonitorTMonitoringDataWaterPressureIoTResult::getHydraulicValue).collect(Collectors.toList());
        List<String> hydraulicThresholdMinList = returnList.stream().map(CentermonitorTMonitoringDataWaterPressureIoTResult::getHydraulicThresholdMin).collect(Collectors.toList());
        List<String> hydraulicThresholdMaxList = returnList.stream().map(CentermonitorTMonitoringDataWaterPressureIoTResult::getHydraulicThresholdMax).collect(Collectors.toList());
        Map<String, List> map = new HashMap<>();
        map.put("hydraulicValue", hydraulicValueList);
        map.put("hydraulicThresholdMin", hydraulicThresholdMinList);
        map.put("hydraulicThresholdMax", hydraulicThresholdMaxList);
        List<String> valueList = Arrays.asList("hydraulicValue", "hydraulicThresholdMin", "hydraulicThresholdMax");
        List<String> keyList = Arrays.asList("水压值", "水压下限阈值", "水压上限阈值");
        List<Map<String, String>> nameList = IntStream.range(0, valueList.size())
                .mapToObj(i -> {
                    Map<String, String> nameMap = new HashMap<>();
                    nameMap.put("name", keyList.get(i));
                    nameMap.put("value", valueList.get(i));
                    return nameMap;
                })
                .collect(Collectors.toList());
        map.put("nameList",nameList);
        return map;
    }


    public Map<String, List> getIoTWaterVelocity(String deviceCode) {
        List<CentermonitorTMonitoringDataWaterVelocityIoTResult> returnList = new ArrayList<>(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.now();
        for (int i = 1; i <= 7; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = formatter.format(currentDate);
            CentermonitorTMonitoringDataWaterVelocityIoTResult addEntity = centermonitorTMonitoringDeviceMapper.getIoTWaterVelocity(deviceCode, formattedDate);
            if (ObjectUtils.isEmpty(addEntity)) {
                CentermonitorTMonitoringDataWaterVelocityIoTResult newEntity = new CentermonitorTMonitoringDataWaterVelocityIoTResult(formattedDate, 0.0, 0.0, 0.0, 0.0);
                returnList.add(newEntity);
            } else {
                addEntity.setDate(formattedDate);
                returnList.add(addEntity);
            }
        }
        List<Double> zList = returnList.stream().map(CentermonitorTMonitoringDataWaterVelocityIoTResult::getZ).collect(Collectors.toList());
        List<Double> v1List = returnList.stream().map(CentermonitorTMonitoringDataWaterVelocityIoTResult::getV1).collect(Collectors.toList());
        List<Double> z1List = returnList.stream().map(CentermonitorTMonitoringDataWaterVelocityIoTResult::getZ1).collect(Collectors.toList());
        List<Double> qList = returnList.stream().map(CentermonitorTMonitoringDataWaterVelocityIoTResult::getQ).collect(Collectors.toList());
        Map<String, List> map = new HashMap<>();
        map.put("z", zList);
        map.put("v1", v1List);
        map.put("z1", z1List);
        map.put("q", qList);
        List<String> valueList = Arrays.asList("z", "v1", "z1", "q");
        List<String> keyList = Arrays.asList("水位", "瞬时流速", "水深", "瞬时流量");
        List<Map<String, String>> nameList = IntStream.range(0, valueList.size())
                .mapToObj(i -> {
                    Map<String, String> nameMap = new HashMap<>();
                    nameMap.put("name", keyList.get(i));
                    nameMap.put("value", valueList.get(i));
                    return nameMap;
                })
                .collect(Collectors.toList());
        map.put("nameList",nameList);
        return map;
    }
}
