package com.sooka.sponest.monitor.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
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.device.domain.*;
import com.sooka.sponest.monitor.device.mapper.CentermonitorTMonitoringDeviceCameraMapper;
import com.sooka.sponest.monitor.device.service.*;
import com.sooka.sponest.monitor.remoteapi.service.center.middleground.RemoteMiddleGroundService;
import com.sooka.sponest.monitor.remoteapi.service.center.system.RemoteService;
import com.sooka.sponest.monitor.util.BeanUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 监测设备Controller
 *
 * @author ruoyi
 * @date 2023-03-14
 */
@RestController
@RequestMapping("/device")
public class CentermonitorTMonitoringDeviceController extends BaseController {

    //水质
    private static final String device_water_quality = "1";
    //土壤墒情
    private static final String device_soil_moisture = "2";
    //污染源
    private static final String device_pollution_sources = "3";
    //病虫害
    private static final String device_insect_pests = "4";
    //大气监测
    private static final String device_air_quality = "5";
    //水压监测
    private static final String device_water_pressure = "6";
    //水流速
    private static final String device_water_velocity = "7";

    @Resource
    private ICentermonitorTMonitoringDeviceService centermonitorTMonitoringDeviceService;

    @Resource
    private ICentermonitorTMonitoringDeviceAtmosphereThresholdService atmosphereThresholdService;

    @Resource
    private ICentermonitorTMonitoringDeviceSoilMoistureThresholdService soilMoistureThresholdService;

    @Resource
    private ICentermonitorTMonitoringDeviceThresholdService thresholdService;

    @Resource
    private ICentermonitorTMonitoringDeviceWaterQualityThresholdService waterQualityThresholdService;

    @Resource
    private RemoteService remoteService;

    @Resource
    private RemoteMiddleGroundService remoteMiddleGroundService;
    @Resource
    private CentermonitorTMonitoringDeviceCameraMapper centermonitorTMonitoringDeviceCameraMapper;

    /**
     * 查询监测设备列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @RequiresPermissions("camera:device:list")
    @GetMapping("/list")
    public TableDataInfo list(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        startPage();
        List<CentermonitorTMonitoringDevice> list = centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceList(centermonitorTMonitoringDevice);
        return getDataTable(list);
    }

    /**
     * 查询监测设备列表(可用系统)
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询监测设备列表远程调用", notes = "查询监测设备列表远程调用")
    @PostMapping("/listDevice")
    public AjaxResult listDevice(@RequestBody CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceList(centermonitorTMonitoringDevice));
    }

    /**
     * 查询监测设备列表(所有)
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询监测设备列表远程调用", notes = "查询监测设备列表远程调用")
    @GetMapping("/listDeviceAll")
    public TableDataInfo listDeviceAll(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        startPage();
        List<CentermonitorTMonitoringDevice> list = centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceListAll(centermonitorTMonitoringDevice);
        return getDataTable(list);
    }

    /**
     * 传感器告警状态修改
     */
    @Log(title = "传感器", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "传感器告警状态修改", notes = "传感器告警状态修改")
    @PutMapping("/changeWarn")
    public AjaxResult changeWarn(@RequestBody CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        return toAjax(centermonitorTMonitoringDeviceService.updateCentermonitorTMonitoringDevice(centermonitorTMonitoringDevice));
    }

    /**
     * 导出监测设备列表
     */
    @RequiresPermissions("camera:device:export")
    @Log(title = "监测设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        List<CentermonitorTMonitoringDevice> list = centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceList(centermonitorTMonitoringDevice);
        ExcelUtil<CentermonitorTMonitoringDevice> util = new ExcelUtil<CentermonitorTMonitoringDevice>(CentermonitorTMonitoringDevice.class);
        util.exportExcel(response, list, "监测设备数据");
    }

    /**
     * 根据ID查询传感器详细信息
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据ID查询传感器详细信息", notes = "根据ID查询传感器详细信息")
    @RequestMapping(value = "/selectByDeviceId/{id}", method = GET)
    @ApiImplicitParam(name = "id", value = "主键id", paramType = "query")
    public AjaxResult selectByDeviceId(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceById(id));
    }

    /**
     * 获取监测设备详细信息
     */
    @RequiresPermissions("camera:device:query")
    @GetMapping(value = "/{id}")
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceById(id));
    }

    /**
     * 新增监测设备
     */
    @RequiresPermissions("camera:device:add")
    @Log(title = "监测设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        return toAjax(centermonitorTMonitoringDeviceService.insertCentermonitorTMonitoringDevice(centermonitorTMonitoringDevice));
    }

    /**
     * 修改监测设备
     */
    @RequiresPermissions("camera:device:edit")
    @Log(title = "监测设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        return toAjax(centermonitorTMonitoringDeviceService.updateCentermonitorTMonitoringDevice(centermonitorTMonitoringDevice));
    }

    /**
     * 删除监测设备
     */
    @RequiresPermissions("camera:device:remove")
    @Log(title = "监测设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(centermonitorTMonitoringDeviceService.deleteCentermonitorTMonitoringDeviceByIds(ids));
    }

    /**
     * 根据部门id查询部门及部门以下的数据，没有则默认查询所有
     *
     * @param centermonitorTMonitoringDevice
     * @param
     * @return
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getSensorListByDeptId")
    public R getListBydept(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        startPage();
        if (StringUtils.isEmpty(centermonitorTMonitoringDevice.getDeptId())) {
            //获取当前登录用户信息 及以下部门信息
            List<SysDept> user = SecurityUtils.getLoginUser().getSysUser().getDepts();
            List<String> str = new ArrayList<>();
            for (SysDept dep : user) {
                str.add(dep.getDeptId().toString());
            }
            List<CentermonitorTMonitoringDevice> list = centermonitorTMonitoringDeviceService.selectListByDeptId(str);
            return R.ok(list);
        } else {
            List<CentermonitorTMonitoringDevice> list = centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceList(centermonitorTMonitoringDevice);
            return R.ok(list);
        }
    }


    /**
     * 查询水流速传感器数据列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询水流速传感器数据列表", notes = "查询水流速传感器数据列表")
    @RequiresPermissions("camera:device:data")
    @GetMapping("/selectWaterVelocityMonitoringData")
    public TableDataInfo selectWaterVelocityMonitoringData(CentermonitorTMonitoringDataWaterVelocity centermonitorTMonitoringDataWaterVelocity) {
        startPage();
        List<CentermonitorTMonitoringDataWaterVelocity> list = centermonitorTMonitoringDeviceService.selectWaterVelocityMonitoringData(centermonitorTMonitoringDataWaterVelocity);
        return getDataTable(list);
    }

    /**
     * 查询水质传感器数据列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询水质传感器数据列表", notes = "查询水质传感器数据列表")
    @RequiresPermissions("camera:device:data")
    @GetMapping("/selectWaterQualityMonitoringData")
    public TableDataInfo selectWaterQualityMonitoringData(CentermonitorTMonitoringDataWaterQuality centermonitorTMonitoringDataWaterQuality) {
        startPage();
        List<CentermonitorTMonitoringDataWaterQuality> list = centermonitorTMonitoringDeviceService.selectWaterQualityMonitoringData(centermonitorTMonitoringDataWaterQuality);
        return getDataTable(list);
    }

    /**
     * 查询土壤墒情传感器数据列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询土壤墒情传感器数据列表", notes = "查询土壤墒情传感器数据列表")
    @RequiresPermissions("camera:device:data")
    @GetMapping("/selectSoilMoistureMonitoringData")
    public TableDataInfo selectSoilMoistureMonitoringData(CentermonitorTMonitoringDataSoilMoisture centermonitorTMonitoringDataSoilMoisture) {
        startPage();
        List<CentermonitorTMonitoringDataSoilMoisture> list = centermonitorTMonitoringDeviceService.selectSoilMoistureMonitoringData(centermonitorTMonitoringDataSoilMoisture);
        return getDataTable(list);
    }

    /**
     * 查询大气传感器数据列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询大气传感器数据列表", notes = "查询大气传感器数据列表")
    @RequiresPermissions("camera:device:data")
    @GetMapping("/selectAtmosphereMonitoringData")
    public TableDataInfo selectAtmosphereMonitoringData(CentermonitorTMonitoringDataAtmosphere centermonitorTMonitoringDataAtmosphere) {
        startPage();
        List<CentermonitorTMonitoringDataAtmosphere> list = centermonitorTMonitoringDeviceService.selectAtmosphereMonitoringData(centermonitorTMonitoringDataAtmosphere);
        return getDataTable(list);
    }

    /**
     * 查询水压传感器数据列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询水压感器数据列表", notes = "查询水压感器数据列表")
    @RequiresPermissions("camera:device:data")
    @GetMapping("/selectWaterPressureMonitoringData")
    public TableDataInfo selectWaterPressureMonitoringData(CentermonitorTMonitoringDataWaterPressure centermonitorTMonitoringDataWaterPressure) {
        startPage();
        List<CentermonitorTMonitoringDataWaterPressure> list = centermonitorTMonitoringDeviceService.selectWaterPressureMonitoringData(centermonitorTMonitoringDataWaterPressure);
        return getDataTable(list);
    }

    /**
     * 查询病虫害传感器数据列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询病虫害传感器数据列表", notes = "查询病虫害传感器数据列表")
    @RequiresPermissions("camera:device:data")
    @GetMapping("/selectInsectPestsMonitoringData")
    public TableDataInfo selectInsectPestsMonitoringData(CentermonitorTMonitoringDataInsectPests centermonitorTMonitoringDataInsectPests) {
        startPage();
        List<CentermonitorTMonitoringDataInsectPests> list = centermonitorTMonitoringDeviceService.selectInsectPestsMonitoringData(centermonitorTMonitoringDataInsectPests);
        return getDataTable(list);
    }

    /**
     * 查询部门管理列表
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询部门管理列表", notes = "查询部门管理列表")
    @GetMapping("/selectDeptMonitoringData")
    public TableDataInfo selectDeptMonitoringData(CenterdataTAidevicedept centerdataTAidevicedept) {
        startPage();
        List<CenterdataTAidevicedept> list = centermonitorTMonitoringDeviceService.selectDeptMonitoringData(centerdataTAidevicedept);
        return getDataTable(list);
    }

    /**
     * 根据id获取水流速详细信息
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getWaterVelocity/{id}")
    public AjaxResult getWaterVelocity(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectWaterVelocityCentermonitorByST(id));
    }

    /**
     * 根据id获取土壤详细信息
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getSoilMoisture/{id}")
    public AjaxResult getSoilMoisture(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectSoilMoistureCentermonitorByDeviceCode(id));
    }

    /**
     * 根据id获取水质详细信息
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getWaterQuality/{id}")
    public AjaxResult getWaterQuality(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectWaterQualityCentermonitorByDeviceCode(id));
    }

    /**
     * 根据id获取水压详细信息
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getWaterPressure/{id}")
    public AjaxResult getWaterPressure(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectWaterPressureCentermonitorByIMEI(id));
    }

    /**
     * 根据id获取大气详细信息
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getAtmosphere/{id}")
    public AjaxResult getAtmosphere(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectAtmosphereCentermonitorByDeviceCode(id));
    }

    /**
     * 根据id获取病虫害详细信息
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getInsectPests/{id}")
    public AjaxResult getInsectPests(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTMonitoringDeviceService.selectInsectPestsCentermonitorByDeviceCode(id));
    }


    /**
     * 将传感器列表和传感器最新数据构建为一个list返回给前端
     */
    private List<CentermonitorTMonitoringDevice> putDataIntoDeviceList(List<CentermonitorTMonitoringDevice> monitoringDeviceList, List<CentermonitorTMonitoringDataWaterQuality> waterQualities,
                                                                       List<CentermonitorTMonitoringDataSoilMoisture> soilMoistures, List<CentermonitorTMonitoringDataAtmosphere> atmospheres,
                                                                       List<CentermonitorTMonitoringDataWaterPressure> waterPressures, List<CentermonitorTMonitoringDataWaterVelocity> waterVelocities,
                                                                       List<CentermonitorTMonitoringDataInsectPests> insectPests) {
        //遍历设备列表和数据列表，如果编码相同就将数据放入该对象中
        for (int j = 0; j < monitoringDeviceList.size(); j++) {
            CentermonitorTMonitoringDevice monitoringDevice = monitoringDeviceList.get(j);
            //构建水质数据
            for (int k = 0; k < waterQualities.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(waterQualities.get(k).getDeviceCode())) {
                    monitoringDevice.setData(waterQualities.size() > 0 ? BeanUtil.beanToMap(waterQualities.get(k)) : new HashMap<>());
                }
            }
            //构建土壤墒情数据
            for (int k = 0; k < soilMoistures.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(soilMoistures.get(k).getDeviceCode())) {
                    monitoringDevice.setData(soilMoistures.size() > 0 ? BeanUtil.beanToMap(soilMoistures.get(k)) : new HashMap<>());
                }
            }
            //构建大气监测数据
            for (int k = 0; k < atmospheres.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(atmospheres.get(k).getDeviceCode())) {
                    monitoringDevice.setData(atmospheres.size() > 0 ? BeanUtil.beanToMap(atmospheres.get(k)) : new HashMap<>());
                }
            }
            //构建水压监测数据
            for (int k = 0; k < waterPressures.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(waterPressures.get(k).getIMEI())) {
                    monitoringDevice.setData(waterPressures.size() > 0 ? BeanUtil.beanToMap(waterPressures.get(k)) : new HashMap<>());
                }
            }
            //构建水流速数据
            for (int k = 0; k < waterVelocities.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(waterVelocities.get(k).getST())) {
                    monitoringDevice.setData(waterVelocities.size() > 0 ? BeanUtil.beanToMap(waterVelocities.get(k)) : new HashMap<>());
                }
            }
            //构建病虫害数据
            for (int k = 0; k < insectPests.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(insectPests.get(k).getDeviceNumber())) {
                    monitoringDevice.setData(insectPests.size() > 0 ? BeanUtil.beanToMap(insectPests.get(k)) : new HashMap<>());
                }
            }
        }
        return monitoringDeviceList;
    }

    /**
     * 将传感器列表和传感器阈值构建为一个list返回给前端
     **/
    private List<CentermonitorTMonitoringDevice> putThresholdIntoDeviceList(List<CentermonitorTMonitoringDevice> monitoringDeviceList,
                                                                            List<CentermonitorTMonitoringThresholdWaterQuality> thresholdWaterQualities,
                                                                            List<CentermonitorTMonitoringThresholdSoilMoisture> thresholdSoilMoistures,
                                                                            List<CentermonitorTMonitoringThresholdAtmosphere> thresholdAtmospheres,
                                                                            List<CentermonitorTMonitoringThresholdWaterVelocity> thresholdWaterVelocities) {
        //遍历设备列表和数据列表，如果编码相同就将数据放入该对象中
        for (int j = 0; j < monitoringDeviceList.size(); j++) {
            CentermonitorTMonitoringDevice monitoringDevice = monitoringDeviceList.get(j);
            //构建水质阈值
            for (int k = 0; k < thresholdWaterQualities.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(thresholdWaterQualities.get(k).getDeviceCode())) {
                    monitoringDevice.setThreshold(thresholdWaterQualities.size() > 0 ? BeanUtil.beanToMap(thresholdWaterQualities.get(k)) : new HashMap<>());
                }
            }
            //构建土壤墒情阈值
            for (int k = 0; k < thresholdSoilMoistures.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(thresholdSoilMoistures.get(k).getDeviceCode())) {
                    monitoringDevice.setThreshold(thresholdSoilMoistures.size() > 0 ? BeanUtil.beanToMap(thresholdSoilMoistures.get(k)) : new HashMap<>());
                }
            }
            //构建大气监测阈值
            for (int k = 0; k < thresholdAtmospheres.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(thresholdAtmospheres.get(k).getDeviceCode())) {
                    monitoringDevice.setThreshold(thresholdAtmospheres.size() > 0 ? BeanUtil.beanToMap(thresholdAtmospheres.get(k)) : new HashMap<>());
                }
            }
            //构建水流速阈值
            for (int k = 0; k < thresholdWaterVelocities.size(); k++) {
                if (monitoringDevice.getDeviceCode().equals(thresholdWaterVelocities.get(k).getDeviceCode())) {
                    monitoringDevice.setThreshold(thresholdWaterVelocities.size() > 0 ? BeanUtil.beanToMap(thresholdWaterVelocities.get(k)) : new HashMap<>());
                }
            }
        }
        return monitoringDeviceList;
    }


    /**
     * 传感器列表和传感器最新数据list给前端
     */
    @GetMapping(value = "/getMonitorDeviceAndDataList")
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    public AjaxResult getMonitorDeviceAndDataList(CentermonitorTMonitoringDevice device) {
        /**存储传感器数据的 LIST**/
        List<CentermonitorTMonitoringDataWaterQuality> waterQualities = new ArrayList<>();
        List<CentermonitorTMonitoringDataSoilMoisture> soilMoistures = new ArrayList<>();
        List<CentermonitorTMonitoringDataAtmosphere> atmospheres = new ArrayList<>();
        List<CentermonitorTMonitoringDataWaterPressure> waterPressures = new ArrayList<>();
        List<CentermonitorTMonitoringDataWaterVelocity> waterVelocities = new ArrayList<>();
        List<CentermonitorTMonitoringDataInsectPests> insectPests = new ArrayList<>();
        /**存储传感器阈值的 LIST**/
        List<CentermonitorTMonitoringThresholdWaterQuality> thresholdWaterQualities = new ArrayList<>();
        List<CentermonitorTMonitoringThresholdSoilMoisture> thresholdSoilMoistures = new ArrayList<>();
        List<CentermonitorTMonitoringThresholdAtmosphere> thresholdAtmospheres = new ArrayList<>();
        List<CentermonitorTMonitoringThresholdWaterVelocity> thresholdWaterVelocities = new ArrayList<>();
        //传感器列表
        List<CentermonitorTMonitoringDevice> monitoringDeviceList = centermonitorTMonitoringDeviceService.selectCentermonitorTMonitoringDeviceList(device);
        //map 各类型传感器类型 设备编码数组
        List<Map<String, String>> deviceCodeMap = centermonitorTMonitoringDeviceService.selectDeviceCodeMap(device);
        for (int i = 0; i < deviceCodeMap.size(); i++) {
            //type 传感器类型
            String type = deviceCodeMap.get(i).get("device_type");
            //data 传感器类型
            String[] data = deviceCodeMap.get(i).get("data").split(",");
            if (type.equals(device_water_quality)) {//水质
                //数据
                waterQualities = centermonitorTMonitoringDeviceService.selectWaterQualityDataByDeviceCodes(data);
                thresholdWaterQualities = waterQualityThresholdService.selectWaterQualityThresholdByCodes(data);
            } else if (type.equals(device_soil_moisture)) {//土壤墒情
                //数据
                soilMoistures = centermonitorTMonitoringDeviceService.selectSoilMoistureDataByDeviceCodes(data);
                thresholdSoilMoistures = soilMoistureThresholdService.selectSoilMoistureThresholdByCodes(data);
            } else if (type.equals(device_air_quality)) {//大气监测
                //数据
                atmospheres = centermonitorTMonitoringDeviceService.selectAtmosphereDataByDeviceCodes(data);
                thresholdAtmospheres = atmosphereThresholdService.selectAtmosphereThresholdByCodes(data);
            } else if (type.equals(device_water_pressure)) {//水压监测
                //数据
                waterPressures = centermonitorTMonitoringDeviceService.selectWaterPressureDataByDeviceCodes(data);
            } else if (type.equals(device_water_velocity)) {//水流速
                //数据
                waterVelocities = centermonitorTMonitoringDeviceService.selectWaterVelocityDataByDeviceCodes(data);
                thresholdWaterVelocities = thresholdService.selectWaterVelocityThresholdByCodes(data);
            } else if (type.equals(device_insect_pests)) {//病虫害
                //数据
                insectPests = centermonitorTMonitoringDeviceService.selectInsectPestsDataByDeviceCodes(data);
            }
        }
        /**将传感器列表和传感器最新数据构建为一个list返回给前端**/
        monitoringDeviceList = putDataIntoDeviceList(monitoringDeviceList, waterQualities, soilMoistures, atmospheres, waterPressures, waterVelocities, insectPests);
        /**将传感器列表和传感器阈值构建为一个list返回给前端**/
        monitoringDeviceList = putThresholdIntoDeviceList(monitoringDeviceList, thresholdWaterQualities, thresholdSoilMoistures, thresholdAtmospheres, thresholdWaterVelocities);

        /**检测设备和摄像头关联表构建为一个list返回给前端**/
//        for (CentermonitorTMonitoringDevice var : monitoringDeviceList) {
//            List<CameraCodeAndNameVO> list = centermonitorTMonitoringDeviceCameraMapper.selectByDeviceId(var.getId());
//            var.setCameras(list);
//        }
        return AjaxResult.success(monitoringDeviceList);
    }


    /**
     * 【水压】指令下发方法
     */
    @ApiOperation(value = "水压传感器指令下发", notes = "水压传感器指令下发")
    @RequiresPermissions("camera:device:instruct")
    @PostMapping("/SendWaterPressCommand")
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    public AjaxResult SendWaterPressCommand(@RequestBody JSONObject json) {
        //参数
        String deviceId = json.getString("deviceCode");
        String commandType = json.getString("commandType");
        String commandValue = json.getString("commandValue");
        if (json.getString("commandType").equals("108")) {//心跳周期
            if (json.getInteger("commandValue") > 0 && json.getInteger("commandValue") <= 100) {
                return postRequest(remoteMiddleGroundService.command(buildCommand(deviceId, commandType, commandValue).toJSONString()));
            } else {
                return AjaxResult.error("参数不合法请重新校验参数");
            }
        } else if (json.getString("commandType").equals("109") || json.getString("commandType").equals("110")) {//报警阈值
            if (json.getInteger("commandValue") >= 0 && json.getInteger("commandValue") <= 10) {
                return postRequest(remoteMiddleGroundService.command(buildCommand(deviceId, commandType, commandValue).toJSONString()));
            } else {
                return AjaxResult.error("参数不合法请重新校验参数");
            }
        } else {//开关报警
            return postRequest(remoteMiddleGroundService.command(buildCommand(deviceId, commandType).toJSONString()));
        }
    }

    private AjaxResult postRequest(String result) {

        JSONObject d = JSONObject.parseObject(result).getJSONObject("data");
        if (d.getString("code").equals("0")) {
            return AjaxResult.success(d.getString("msg"));
        } else if (d.getString("code").equals("402")) {
            return AjaxResult.error(d.getString("msg"));
        } else {
            return AjaxResult.error("指令下发失败");
        }
    }

    private JSONObject buildCommand(String deviceCode, String commandType, String commandValue) {
        JSONObject param = new JSONObject();
        param.put("deviceId", deviceCode);
        param.put("commandType", commandType);
        param.put("args", commandValue);
        return param;
    }

    private JSONObject buildCommand(String deviceCode, String commandType) {
        JSONObject param = new JSONObject();
        param.put("deviceId", deviceCode);
        param.put("commandType", commandType);
        return param;
    }

    /**
     * 根据部门ID和工作状态查询传感器列表
     *
     * @param centermonitorTMonitoringDevice 传感器
     * @return 传感器集合
     */
    @Log(title = "传感器", businessType = BusinessType.OTHER)
    @GetMapping("/selectDeviceListByDeptIdAndWorkingStatus")
    @ApiOperation(value = "根据部门ID和工作状态查询传感器列表", notes = "根据部门ID和工作状态查询传感器列表")
    public TableDataInfo selectDeviceListByDeptIdAndWorkingStatus(CentermonitorTMonitoringDevice centermonitorTMonitoringDevice) {
        startPage();
        List<CentermonitorTMonitoringDevice> list = centermonitorTMonitoringDeviceService.selectDeviceListByDeptIdAndWorkingStatus(centermonitorTMonitoringDevice);
        return getDataTable(list);
    }

    /**
     * 物联设备统计
     * @param deptId 部门id
     */
//    @Log(title = "物联设备统计", businessType = BusinessType.OTHER)
//    @GetMapping("/getIoTEquipmentStatistics")
//    @ApiOperation(value = "物联设备统计", notes = "物联设备统计")
//    public R getIoTEquipmentStatistics(@RequestParam(value = "deptId",required = false) Long deptId){
//        return centermonitorTMonitoringDeviceService.getIoTEquipmentStatistics(deptId);
//    }

    /**
     * 区县传感器统计
     * @param deptId 部门id
     */
    @Log(title = "区县传感器统计", businessType = BusinessType.OTHER)
    @GetMapping("/getOnLineSensorStatistics")
    @ApiOperation(value = "区县传感器统计", notes = "区县传感器统计")
    public R getOnLineSensorStatistics(@RequestParam(value = "deptId",required = false) Long deptId){
        return R.ok(centermonitorTMonitoringDeviceService.getOnLineSensorStatistics(deptId));
    }

    /**
     * 在线设备分析 - 在线离线
     * @param deptId 部门id
     */
//    @Log(title = "在线设备分析", businessType = BusinessType.OTHER)
//    @GetMapping("/getDeviceAnalysis")
//    @ApiOperation(value = "在线设备分析", notes = "在线设备分析")
//    public R getDeviceAnalysis(@RequestParam(value = "deptId",required = false) Long deptId){
//        return centermonitorTMonitoringDeviceService.getDeviceAnalysis(deptId);
//    }

    /**
     * 离线原因数量地区分布
     * (1:水质环境;2:土壤墒情;3:污染源;4:病虫害监测;5:大气监测 ;6:水压监测;7:水流速;8:水尺)
     * @param deptId 部门id
     */
//    @Log(title = "离线原因数量地区分布", businessType = BusinessType.OTHER)
//    @GetMapping("/getOfflineReasonCountStatistics")
//    @ApiOperation(value = "离线原因数量地区分布", notes = "离线原因数量地区分布")
//    public R getOfflineReasonCountStatistics(@RequestParam(value = "deptId",required = false) Long deptId){
//        return R.ok(centermonitorTMonitoringDeviceService.getOfflineReasonCountStatistics(deptId));
//    }

    /**
     * 设备故障分布
     * @param deptId 部门id
     */
    @Log(title = "设备故障分布", businessType = BusinessType.OTHER)
    @GetMapping("/getFaultDistribution")
    @ApiOperation(value = "设备故障分布", notes = "设备故障分布")
    public Map<String, List> getFaultDistribution(@RequestParam(value = "deptId",required = false) Long deptId){
        return centermonitorTMonitoringDeviceService.getFaultDistribution(deptId);
    }

    /**
     * 采集数量分析(当天)
     * @param deptId 部门id
     */
//    @Log(title = "采集数量分析", businessType = BusinessType.OTHER)
//    @GetMapping("/getSensorDataCount")
//    @ApiOperation(value = "采集数量分析", notes = "采集数量分析")
//    public R getSensorDataCount(@RequestParam(value = "deptId",required = false) Long deptId){
//        return centermonitorTMonitoringDeviceService.getSensorDataCount(deptId);
//    }

    /**
     * 物联广场右上角统计数
     * @param deptId 部门id
     */
    @Log(title = "物联广场右上角统计数", businessType = BusinessType.OTHER)
    @GetMapping("/getDeviceSquareNumber")
    @ApiOperation(value = "物联广场右上角统计数", notes = "物联广场右上角统计数")
    public R getDeviceSquareNumber(@RequestParam(value = "deptId",required = false) Long deptId){
        return centermonitorTMonitoringDeviceService.getDeviceSquareNumber(deptId);
    }

    /**
     * 物联网中台统一入口
     * @param deptId 部门id
     **/
    @Log(title = "物联网中台统一入口", businessType = BusinessType.OTHER)
    @ApiOperation(value = "物联网中台统一入口", notes = "物联网中台统一入口")
    @GetMapping(value = "/getInternetOfThings")
    public R getInternetOfThings(@RequestParam(value = "deptId", required = false) Long deptId) {
        return centermonitorTMonitoringDeviceService.getInternetOfThings(deptId);
    }


    /**
     * 物联网中台传感器坐标详情
     * @param deptId 部门id
     * @param deviceCode 设备编码
     * @param deviceType 设备类型
     **/
    @Log(title = "物联网中台传感器坐标详情", businessType = BusinessType.OTHER)
    @ApiOperation(value = "物联网中台传感器坐标详情", notes = "物联网中台传感器坐标详情")
    @GetMapping(value = "/getIoTEquipmentDetails")
    public R getIoTEquipmentDetails(@RequestParam(value = "deptId", required = false) Long deptId,
                                    @RequestParam(value = "deviceCode") String deviceCode,
                                    @RequestParam(value = "deviceType") String deviceType) {
        return centermonitorTMonitoringDeviceService.getIoTEquipmentDetails(deptId,deviceCode,deviceType);
    }

}
