package org.jeecg.modules.bigScreen.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.constant.WebsocketConst;
import org.jeecg.modules.bigScreen.model.ReceiveStatus;
import org.jeecg.modules.bigScreen.model.TableStructure;
import org.jeecg.modules.bigScreen.model.interfaceFaultData;
import org.jeecg.modules.device.entity.*;
import org.jeecg.modules.device.model.DeviceRiskAnalysis;
import org.jeecg.modules.device.service.*;
import org.jeecg.modules.energy.entity.*;
import org.jeecg.modules.energy.service.*;
import org.jeecg.modules.job.ResultJson;
import org.jeecg.modules.message.websocket.WebSocket;
import org.jeecg.modules.sensor.entity.*;
import org.jeecg.modules.sensor.service.*;
import org.jeecg.modules.spare.entity.BuSparePart;
import org.jeecg.modules.spare.service.IBuSparePartService;
import org.jeecg.modules.statistics.entity.BuDeviceStatistics;
import org.jeecg.modules.statistics.service.IBuDeviceEnergyStatisticsService;
import org.jeecg.modules.statistics.service.IBuDeviceStatisticsService;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "大屏信息")
@RestController
@RequestMapping("/bigScreen")
public class bigScreenController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysAnnouncementService sysAnnouncementService;
    @Autowired
    private IBuSensorService buSensorService;
    @Autowired
    private IBuDeviceService buDeviceService;

    @Autowired
    private IBuStatusService buStatusService;

    @Autowired
    private IBuDeviceTypeService buDeviceTypeService;
    @Autowired
    private IBuSensorDeviceDataService buSensorDeviceDataService;
    @Autowired
    private IBuDeviceStatisticsService buDeviceStatisticsService;
    @Autowired
    private IBuAirQualityService buAirQualityService;
    @Autowired
    private IBuAirNoiseService buAirNoiseService;
    @Autowired
    private IBuAirSmokeService buAirSmokeService;
    @Autowired
    private IBuAirWaterService buAirWaterService;
    @Autowired
    private IBuSparePartService buSparePartService;
    @Autowired
    private IBuDeviceOnlineService buDeviceOnlineService;
    @Autowired
    private IBuSensorDataService buSensorDataService;
    @Autowired
    private IBuItemExplainService buItemExplainService;
    @Autowired
    private IBuDeviceEnergyStatisticsService buDeviceEnergyStatisticsService;
    @Autowired
    private IBuVibrationService buVibrationService;
    @Autowired
    private IBuElectricService buElectricService;
    @Autowired
    private IBuSensorTypeService buSensorTypeService;
    @Autowired
    private IAlarmPartService alarmPartService;

    @Autowired
    private IBuRiskItemValueService buRiskItemValueService;
    @Autowired
    private IBuMaintenanceHistoryService buMaintenanceHistoryService;
    @Resource
    private WebSocket webSocket;

    //设备基本信息
    @GetMapping(value = "/getDevice")
    public BuDevice getDeviceByName(String deviceId)
    {
        return buDeviceService.getById(deviceId);
    }

    //所有设备信息
    @GetMapping(value = "/getAllDevice")
    public List<Map<String, Object>> getAllDevice(){
        List<Map<String, Object>> result = new ArrayList<>();
        List<BuDevice> list = buDeviceService.getDevice();
        for (BuDevice buDevice : list){
            Map<String, Object> map = BeanUtil.beanToMap(buDevice);
            List<BuSensor> buSensorElectric = buSensorService.getByCheckName(buDevice.getId(),"%电能%");
            BuStatus buStatus1 = buStatusService.getDataBySensorId(buSensorElectric.get(0).getId());
            if (buStatus1.getSensorStatus() == 0){
                map.put("use_status",0);
            }else {
                map.put("use_status",1);
            }
            result.add(map);
        }
        return result;
    }

    //获取未处理状态下异常信息的列表
    @GetMapping(value = "/getAllFaultData")
    public List<BuDeviceOnline> getAllFaultData(@RequestParam(required = false) String deviceId){
        if (deviceId == null){
            QueryWrapper<BuDeviceOnline> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",0);
            return buDeviceOnlineService.list(queryWrapper);
        }else {
            return buDeviceOnlineService.getAllDataById(deviceId);
        }
    }

    //获取未处理状态下异常信息的个数
    @GetMapping(value = "/getFaultDataNumber")
    public int getFaultDataNumber(@RequestParam(required = false) String deviceId){
        if (deviceId == null){
            QueryWrapper<BuDeviceOnline> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",0);
            return (int) buDeviceOnlineService.count(queryWrapper);
        }else {
            return buDeviceOnlineService.getFaultDataNumber(deviceId);
        }
    }

    @PostMapping(value = "/getTestMethod")
    public ResultJson getTestMethod(@RequestBody ReceiveStatus receiveStatus){
        System.out.println(JSON.toJSONString(receiveStatus));
        ResultJson resultJson = new ResultJson();
        resultJson.setCode(0);
        resultJson.setSuccess(true);
        resultJson.setMessage("成功");
        return resultJson;
    }

    //获取未处理的设备维保消息个数
    @GetMapping(value = "/getMaintenanceNumber")
    public int getMaintenanceNumber(){
        QueryWrapper<BuMaintenanceHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0);
        List<BuMaintenanceHistory> list = buMaintenanceHistoryService.list(queryWrapper);
        return list.size();
    }

    /**
     * 电源电压过、欠压检测
     * @param id
     * @return
     */
    @GetMapping(value = "getVoltage")
    public String[] getVoltage (String id){
        String[] result = new String[6];
        BuSensor buSensor = buSensorService.getValueById(id,"功率因数");
        BuDevice buDevice = buDeviceService.getById(id);
        BuSensorData buSensorData = buSensorDataService.getDataByDeviceId(id);
        DecimalFormat df = new DecimalFormat("0");
        //传感器类型
        BuSensorType buSensorType = buSensorTypeService.getById(buSensor.getTypeId());
        //查询实时表的数据
        BuElectric buSensorDeviceData = buSensorDeviceDataService.getLastVoltage(buSensorType.getTableHead()+"_online",buSensor.getId());
        //获取电压值
        Double[] vols = new Double[3];
        vols[0] = buSensorDeviceData.getUdy();
        vols[1] = buSensorDeviceData.getVdy();
        vols[2] = buSensorDeviceData.getWdy();
        // 返回值为三相电压具体数值和当前状态
        result[0] = df.format(vols[0]);
        result[1] = df.format(vols[1]);
        result[2] = df.format(vols[2]);
        return result;
    }

    /**
     * 电源过流检测
     * @param id
     * @return
     */
    @GetMapping(value = "getElectric")
    public String[] getElectric(String id) {
        String[] result = new String[6];
        BuSensor buSensor = buSensorService.getValueById(id, "功率因数");
        BuDevice buDevice = buDeviceService.getById(id);
        //传感器类型
        BuSensorType buSensorType = buSensorTypeService.getById(buSensor.getTypeId());
        //状态表查询
        BuElectric buSensorDeviceData = buSensorDeviceDataService.getLastVoltage(buSensorType.getTableHead() + "_online", buSensor.getId());
        if (buSensorDeviceData == null) {
            return result;
        }
        result[0] = String.valueOf(buSensorDeviceData.getUdl());
        result[1] = String.valueOf(buSensorDeviceData.getVdl());
        result[2] = String.valueOf(buSensorDeviceData.getWdl());
        return result;
    }


    /**
     *c#端所用接口
     */
    //异常信息上报接口
    @GetMapping(value = "/faultReport")
    public void getFaultReport(@RequestBody @Valid interfaceFaultData params){
        try {
            String response = "";
            if (params.getItem().contains("bu_electric")) {
                Object obj = params.getJsonObj();
                response = JSON.toJSONString(obj);
                BuElectric buElectric = JSONObject.parseObject(response,BuElectric.class);
                String[] fields = buElectric.getStatusname().split(",");//可能存在多个字段同时报警
                int status = buElectric.getStatus();
                //获取报异常检测项的值
                Map<String, Object> valueMap = BeanUtil.beanToMap(buElectric);
                double value = (double) valueMap.get(fields[0]);
                getFaultReportData(fields,status,value,params.getSensorId());
            }else if (params.getItem().contains("bu_vibration")) {
                Object obj = params.getJsonObj();
                response = JSON.toJSONString(obj);
                BuVibration buVibration = JSONObject.parseObject(response,BuVibration.class);
                String[] fields = buVibration.getStatusname().split(",");//可能存在多个字段同时报警
                int status = buVibration.getStatus();
                //获取报异常检测项的值
                Map<String, Object> valueMap = BeanUtil.beanToMap(buVibration);
                double value = (double) valueMap.get(fields[0]);
                getFaultReportData(fields,status,value,params.getSensorId());
            }else {
                Object obj = params.getJsonObj();
                response = JSON.toJSONString(obj);
                BuAirQuality buAirQuality = JSONObject.parseObject(response,BuAirQuality.class);
                String[] fields = buAirQuality.getStatusname().split(",");//可能存在多个字段同时报警
                int status = buAirQuality.getStatus();
                //获取报异常检测项的值
                Map<String, Object> valueMap = BeanUtil.beanToMap(buAirQuality);
                double value = (double) valueMap.get(fields[0]);
                getFaultReportData(fields,status,value,params.getSensorId());
            }
        }catch (Exception ex){
            System.out.println("异常信息上报接口发生异常");
            ex.printStackTrace();
        }finally {
            System.out.println("接口调用完成，传入的传感器id为："+ params.getSensorId() + ",数据表为:" + params.getItem());
        }

    }

    //异常信息上报  数据处理方法
    public void getFaultReportData(String[] fields, int status,double value,String sensorId) {
        try {
            //根据传感器id查出数据表名和数据
            BuSensor buSensor = buSensorService.getById(sensorId);
            BuDevice buDevice = buDeviceService.getById(buSensor.getDeviceId());
            BuSensorType buSensorType = buSensorTypeService.getById(buSensor.getTypeId());//获取数据表 表头
            String tableName = buSensorType.getTableHead() + "_online";//拼接表名
            //判断报异常的字段个数是否大于1，不大于1则状态直接使用，大于1则需要判断每个检测项具体属于预警还是报警
            if (fields.length == 1){
                //根据报警字段和传感器id，在报警上下限表中，获取异常故障类型字段，去判式逻辑表中获取对应的报警信息和处理建议
                AlarmPart alarmPart = alarmPartService.getDataByIdAndName(sensorId, fields[0]);
                if (alarmPart == null) {
                    alarmPart = alarmPartService.getCurrentData(fields[0]);//查询当前检测项通用界限值
                }
                //获取上下限值
                double maxs = alarmPart.getWarningLimit();
                double max = alarmPart.getAlarmLimit();
                double min = alarmPart.getAlarmMin();
                double mins = alarmPart.getWarningMin();
                //调用异常信息构建方法，保存到bu_device_online异常信息表中
                BuItemExplain buItemExplain = buItemExplainService.getByItem(buDevice.getDeviceTypeId(),alarmPart.getFaultType());
                //当前检测项共6+3+9=18种，
                if (fields[0].contains("dy")){//电压异常
                    if (status == 1){
                        if (maxs < value && value < max){//过压预警
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相过压预警");
                            if (oldData.size() == 0){
                                //创建新的异常信息
                                BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                                buDeviceOnline.setDeviceId(buDevice.getId());
                                buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                                buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                                buDeviceOnline.setTime(new Date());
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem(fields[0].charAt(0) + "相过压预警");
                                buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电压过压预警，当前电压为" + value + "V ，预警电压值为" + maxs + "V");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else {//欠压预警
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相欠压预警");
                            if (oldData.size() == 0){
                                //创建新的异常信息
                                BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                                buDeviceOnline.setDeviceId(buDevice.getId());
                                buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                                buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                                buDeviceOnline.setTime(new Date());
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem(fields[0].charAt(0) + "相欠压预警");
                                buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电压欠压预警，当前电压为" + value + "V ，预警电压值为" + mins + "V");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }else if (status == 2){
                        if (value > max){//过压报警
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相过压报警");
                            if (oldData.size() == 0){
                                //创建新的异常信息
                                BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                                buDeviceOnline.setDeviceId(buDevice.getId());
                                buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                                buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                                buDeviceOnline.setTime(new Date());
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem(fields[0].charAt(0) + "相过压报警");
                                buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电压过压报警，当前电压为" + value + "V ，报警电压值为" + max + "V");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else {//欠压报警
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相欠压报警");
                            if (oldData.size() == 0){
                                //创建新的异常信息
                                BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                                buDeviceOnline.setDeviceId(buDevice.getId());
                                buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                                buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                                buDeviceOnline.setTime(new Date());
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem(fields[0].charAt(0) + "相欠压报警");
                                buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电压欠压报警，当前电压为" + value + "V ，报警电压值为" + min + "V");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }
                }else if (fields[0].contains("dl")){
                    if (status == 1){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相过流预警");
                        if (oldData.size() == 0){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            buDeviceOnline.setRemindType(1);
                            buDeviceOnline.setTestItem(fields[0].charAt(0) + "相过流预警");
                            buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电流过流预警，当前电流为" + value + "A ，预警电流值为" + maxs + "A");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }else if (status == 2){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相过流报警");
                        if (oldData.size() == 0){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            buDeviceOnline.setRemindType(2);
                            buDeviceOnline.setTestItem(fields[0].charAt(0) + "相过流报警");
                            buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电流过流报警，当前电流为" + value + "A ，报警电流值为" + max + "A");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }
                }else if (fields[0].contains("ch")){
                    if (status == 1){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"可燃性气体含量过高预警");
                        if (oldData.size() == 0){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            buDeviceOnline.setRemindType(1);
                            buDeviceOnline.setTestItem("可燃性气体含量过高预警");
                            buDeviceOnline.setRemind("可燃性气体含量过高预警，当前含量为" + value + "%LEL ，预警值为" + maxs + "%LEL");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }else if (status == 2){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"可燃性气体含量过高报警");
                        if (oldData.size() == 0){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            buDeviceOnline.setRemindType(2);
                            buDeviceOnline.setTestItem("可燃性气体含量过高报警");
                            buDeviceOnline.setRemind("可燃性气体含量过高报警，当前含量为" + value + "%LEL ，报警值为" + max + "%LEL");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }
                }else if (fields[0].contains("co")){
                    if (status == 1){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"一氧化碳含量过高预警");
                        if (oldData.size() == 0){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            buDeviceOnline.setRemindType(1);
                            buDeviceOnline.setTestItem("一氧化碳含量过高预警");
                            buDeviceOnline.setRemind("一氧化碳含量过高预警，当前含量为" + value + "PPM ，预警值为" + maxs + "PPM");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }else if (status == 2){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"一氧化碳含量过高报警");
                        if (oldData.size() == 0){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            buDeviceOnline.setRemindType(2);
                            buDeviceOnline.setTestItem("一氧化碳含量过高报警");
                            buDeviceOnline.setRemind("一氧化碳含量过高报警，当前含量为" + value + "PPM ，报警值为" + max + "PPM");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }
                }else if (fields[0].contains("o2")){
                    if (status == 1){
                        //创建新的异常信息
                        BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                        buDeviceOnline.setDeviceId(buDevice.getId());
                        buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                        buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                        buDeviceOnline.setTime(new Date());
                        if (maxs < value && value < max) {
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过高预警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem("氧气含量过高预警");
                                buDeviceOnline.setRemind("氧气含量过高预警，当前含量为" + value + "%VOL ，预警值为" + maxs + "%VOL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else {
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过低预警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem("氧气含量过低预警");
                                buDeviceOnline.setRemind("氧气含量过低预警，当前含量为" + value + "%VOL ，预警值为" + mins + "%VOL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }else if (status == 2){
                        //创建新的异常信息
                        BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                        buDeviceOnline.setDeviceId(buDevice.getId());
                        buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                        buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                        buDeviceOnline.setTime(new Date());
                        if (value >= max){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过高报警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem("氧气含量过高报警");
                                buDeviceOnline.setRemind("氧气含量过高报警，当前含量为" + value + "%VOL ，报警值为" + max + "%VOL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else {
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过低报警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem("氧气含量过低报警");
                                buDeviceOnline.setRemind("氧气含量过低报警，当前含量为" + value + "%VOL ，报警值为" + min + "%VOL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }
                }else {//振动异常
                    List<TableStructure> tableStructure = buSensorService.getTableStrutureData(tableName);
                    String faultName = "";
                    for (TableStructure list : tableStructure){
                        if (list.getFieldName().equals(fields[0])){
                            faultName = list.getFieldComment();
                        }
                    }
                    //创建新的异常信息
                    BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                    buDeviceOnline.setDeviceId(buDevice.getId());
                    buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                    buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                    buDeviceOnline.setTime(new Date());
                    if (status == 1){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),faultName + "过高预警");
                        if (oldData.size() == 0){
                            buDeviceOnline.setRemindType(1);
                            buDeviceOnline.setTestItem(faultName + "过高预警");
                            buDeviceOnline.setRemind(faultName + "过高预警，当前为" + value + "%VOL ，预警值为" + max + "%VOL");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }else if (status == 2){
                        // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                        List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),faultName + "过高报警");
                        if (oldData.size() == 0){
                            buDeviceOnline.setRemindType(2);
                            buDeviceOnline.setTestItem(faultName + "过高报警");
                            buDeviceOnline.setRemind(faultName + "过高报警，当前为" + value + "%VOL ，报警值为" + max + "%VOL");
                            buDeviceOnline.setStatus(0);
                            buDeviceOnline.setSuggest(buItemExplain.getRemark());
                            String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                            buDeviceOnline.setId(annId);
                            buDeviceOnlineService.save(buDeviceOnline);
                        }
                    }
                }
            }else {
                //如果是多个检测项同时报异常，需要实际通过阈值判断哪个检测项预警或报警，然后报异常当前采用每个检测项都单独报出
                for (int i = 0; i < fields.length; i++){
                    //根据报警字段和传感器id，在报警上下限表中，获取异常故障类型字段，去判式逻辑表中获取对应的报警信息和处理建议
                    AlarmPart alarmPart = alarmPartService.getDataByIdAndName(sensorId, fields[i]);
                    if (alarmPart == null) {
                        alarmPart = alarmPartService.getCurrentData(fields[0]);//查询当前检测项通用界限值
                    }
                    //获取上下限值
                    double maxs = alarmPart.getWarningLimit();
                    double max = alarmPart.getAlarmLimit();
                    double min = alarmPart.getAlarmMin();
                    double mins = alarmPart.getWarningMin();
                    //调用异常信息构建方法，保存到bu_device_online异常信息表中
                    BuItemExplain buItemExplain = buItemExplainService.getByItem(buDevice.getDeviceTypeId(),alarmPart.getFaultType());
                    //当前检测项共6+3+9=18种，
                    if (fields[i].contains("dy")){//电压异常
                        if (status == 1){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            if (maxs < value && value < max){//过压预警
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[i].charAt(0) + "相过压预警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(1);
                                    buDeviceOnline.setTestItem(fields[i].charAt(0) + "相过压预警");
                                    buDeviceOnline.setRemind("电源" + fields[i].charAt(0) + "相电压过压预警，当前电压为" + value + "V ，预警电压值为" + maxs + "V");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }else {//欠压预警
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[i].charAt(0) + "相欠压预警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(1);
                                    buDeviceOnline.setTestItem(fields[i].charAt(0) + "相欠压预警");
                                    buDeviceOnline.setRemind("电源" + fields[i].charAt(0) + "相电压欠压预警，当前电压为" + value + "V ，预警电压值为" + mins + "V");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }
                        }else if (status == 2){
                            //创建新的异常信息
                            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                            buDeviceOnline.setDeviceId(buDevice.getId());
                            buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                            buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                            buDeviceOnline.setTime(new Date());
                            if (value > max){//过压报警
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[i].charAt(0) + "相过压报警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(2);
                                    buDeviceOnline.setTestItem(fields[i].charAt(0) + "相过压报警");
                                    buDeviceOnline.setRemind("电源" + fields[i].charAt(0) + "相电压过压报警，当前电压为" + value + "V ，报警电压值为" + max + "V");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }else {//欠压报警
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[i].charAt(0) + "相欠压报警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(2);
                                    buDeviceOnline.setTestItem(fields[i].charAt(0) + "相欠压报警");
                                    buDeviceOnline.setRemind("电源" + fields[i].charAt(0) + "相电压欠压报警，当前电压为" + value + "V ，报警电压值为" + min + "V");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }
                        }
                    }else if (fields[0].contains("dl")){
                        //创建新的异常信息
                        BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                        buDeviceOnline.setDeviceId(buDevice.getId());
                        buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                        buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                        buDeviceOnline.setTime(new Date());
                        if (status == 1){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相过流预警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem(fields[0].charAt(0) + "相过流预警");
                                buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电流过流预警，当前电流为" + value + "A ，预警电流值为" + maxs + "A");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else if (status == 2){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),fields[0].charAt(0) + "相过流报警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem(fields[0].charAt(0) + "相过流报警");
                                buDeviceOnline.setRemind("电源" + fields[0].charAt(0) + "相电流过流报警，当前电流为" + value + "A ，报警电流值为" + max + "A");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }else if (fields[0].contains("ch")){
                        //创建新的异常信息
                        BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                        buDeviceOnline.setDeviceId(buDevice.getId());
                        buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                        buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                        buDeviceOnline.setTime(new Date());
                        if (status == 1){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"可燃性气体含量过高预警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem("可燃性气体含量过高预警");
                                buDeviceOnline.setRemind("可燃性气体含量过高预警，当前含量为" + value + "%LEL ，预警值为" + maxs + "%LEL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else if (status == 2){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"可燃性气体含量过高报警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem("可燃性气体含量过高报警");
                                buDeviceOnline.setRemind("可燃性气体含量过高报警，当前含量为" + value + "%LEL ，报警值为" + max + "%LEL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }else if (fields[0].contains("co")){
                        //创建新的异常信息
                        BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                        buDeviceOnline.setDeviceId(buDevice.getId());
                        buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                        buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                        buDeviceOnline.setTime(new Date());
                        if (status == 1){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"一氧化碳含量过高预警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem("一氧化碳含量过高预警");
                                buDeviceOnline.setRemind("一氧化碳含量过高预警，当前含量为" + value + "PPM ，预警值为" + maxs + "PPM");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else if (status == 2){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"一氧化碳含量过高报警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem("一氧化碳含量过高报警");
                                buDeviceOnline.setRemind("一氧化碳含量过高报警，当前含量为" + value + "PPM ，报警值为" + max + "PPM");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }else if (fields[0].contains("o2")){
                        //创建新的异常信息
                        BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                        buDeviceOnline.setDeviceId(buDevice.getId());
                        buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                        buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                        buDeviceOnline.setTime(new Date());
                        if (status == 1){
                            if (maxs < value && value < max) {
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过高预警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(1);
                                    buDeviceOnline.setTestItem("氧气含量过高预警");
                                    buDeviceOnline.setRemind("氧气含量过高预警，当前含量为" + value + "%VOL ，预警值为" + maxs + "%VOL");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }else {
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过低预警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(1);
                                    buDeviceOnline.setTestItem("氧气含量过低预警");
                                    buDeviceOnline.setRemind("氧气含量过低预警，当前含量为" + value + "%VOL ，预警值为" + mins + "%VOL");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }
                        }else if (status == 2){
                            if (value >= max){
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过高报警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(2);
                                    buDeviceOnline.setTestItem("氧气含量过高报警");
                                    buDeviceOnline.setRemind("氧气含量过高报警，当前含量为" + value + "%VOL ，报警值为" + max + "%VOL");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }else {
                                // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),"氧气含量过低报警");
                                if (oldData.size() == 0){
                                    buDeviceOnline.setRemindType(2);
                                    buDeviceOnline.setTestItem("氧气含量过低报警");
                                    buDeviceOnline.setRemind("氧气含量过低报警，当前含量为" + value + "%VOL ，报警值为" + min + "%VOL");
                                    buDeviceOnline.setStatus(0);
                                    buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                    String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                    buDeviceOnline.setId(annId);
                                    buDeviceOnlineService.save(buDeviceOnline);
                                }
                            }
                        }
                    }else {//振动异常
                        List<TableStructure> tableStructure = buSensorService.getTableStrutureData(tableName);
                        String faultName = "";
                        for (TableStructure list : tableStructure){
                            if (list.getFieldName().equals(fields[0])){
                                faultName = list.getFieldComment();
                            }
                        }
                        //创建新的异常信息
                        BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                        buDeviceOnline.setDeviceId(buDevice.getId());
                        buDeviceOnline.setDeviceName(buDevice.getDeviceName());
                        buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
                        buDeviceOnline.setTime(new Date());
                        if (status == 1){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),faultName + "过高预警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(1);
                                buDeviceOnline.setTestItem(faultName + "过高预警");
                                buDeviceOnline.setRemind(faultName + "过高预警，当前为" + value + "%VOL ，预警值为" + max + "%VOL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }else if (status == 2){
                            // 判断当前出现的风险情况是否在半小时内出现过，如果有可以避免相同异常重复报的问题
                            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),faultName + "过高报警");
                            if (oldData.size() == 0){
                                buDeviceOnline.setRemindType(2);
                                buDeviceOnline.setTestItem(faultName + "过高报警");
                                buDeviceOnline.setRemind(faultName + "过高报警，当前为" + value + "%VOL ，报警值为" + max + "%VOL");
                                buDeviceOnline.setStatus(0);
                                buDeviceOnline.setSuggest(buItemExplain.getRemark());
                                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                                buDeviceOnline.setId(annId);
                                buDeviceOnlineService.save(buDeviceOnline);
                            }
                        }
                    }
                }
            }
        }catch (Exception ex){
            System.out.println("异常信息上报接口中的数据处理发生异常");
            ex.printStackTrace();
        }finally {
            System.out.println("数据处理结束");
        }
    }

    /**
     * 状态改变接口
     * @param sensorId
     */
    @GetMapping(value = "/sensorStatusReport")
    public void sensorStatusReport(String sensorId){
        log.info("1111111111111111111111111111111111111111111111"+sensorId);
        try {
            //根据传感器id查出所属设备
            BuSensor buSensor = buSensorService.getById(sensorId);
            BuDevice buDevice = buDeviceService.getById(buSensor.getDeviceId());
            if (buSensor.getName().contains("电能")){
                //根据传感器id查出状态表
                BuStatus buStatus = buStatusService.getDataBySensorId(sensorId);
                BuSensorType buSensorType = buSensorTypeService.getById(buSensor.getTypeId());
                String tableName = buSensorType.getTableHead() + "_online";
//                BuElectric buElectric = buElectricService.getBySensorId(tableName,sensorId);
                System.out.println("设备状态改变时状态"+buStatus.getSensorStatus());
                log.info("设备不在线或在线时候的状态"+buStatus.getSensorStatus());
                //0:不在线;1:在线;2:设备运行
                if (buStatus.getSensorStatus() != 2){
                    //统计开关机时间
                    QueryWrapper<BuDeviceStatistics> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("device_id",buDevice.getId());
                    queryWrapper.orderByDesc("create_time");
                    queryWrapper.last("limit 1");
                    BuDeviceStatistics buDeviceStatistics = buDeviceStatisticsService.getOne(queryWrapper);
//                    BuDeviceStatistics buDeviceStatistics = new BuDeviceStatistics();
//                    buDeviceStatistics.setDeviceId(buSensor.getDeviceId());
//                    buDeviceStatistics.setOpenTime(buStatus.getStartTime());
                    buDeviceStatistics.setCloseTime(buStatus.getSensorStatusTime());

                    log.info("关闭时间：" + buStatus.getSensorStatusTime());
                    System.out.println("关闭时间：" + buStatus.getSensorStatusTime());

                    long startTime = buDeviceStatistics.getOpenTime().getTime();
                    long endTime = buStatus.getSensorStatusTime().getTime();
                    Double totalOpenTime = (double) ((endTime - startTime) / 1000 / 60);
                    buDeviceStatistics.setTotalOpenTime(totalOpenTime);
                    buDeviceStatisticsService.updateById(buDeviceStatistics);
                    //根据当前实时电能，计算实际运行时间
//                    BuDeviceRunTime buDeviceRunTime = buDeviceRunTimeService.getByIdLimit(buSensor.getDeviceId());
//                    buDeviceRunTime.setEndPower(buElectric.getEng());
//                    double power = buElectric.getEng() - buDeviceRunTime.getStartPower();
//                    buDeviceRunTime.setPower(Double.parseDouble(String.format("%.2f",power)));
//                    if (buElectric.getActivePower() != 0){
//                        buDeviceRunTime.setRunTime((int)(power / buElectric.getActivePower() * 60 * 60));
//                    }else {
//                        buDeviceRunTime.setRunTime(0);
//                    }
//                    buDeviceRunTimeService.updateById(buDeviceRunTime);
                }
                if (buStatus.getSensorStatus() == 2)
                {
                    BuDeviceStatistics buDeviceStatistics = new BuDeviceStatistics();
                    buDeviceStatistics.setDeviceId(buSensor.getDeviceId());
                    buDeviceStatistics.setOpenTime(new Date());
                    buDeviceStatistics.setCreateTime(new Date());

                    log.info("关闭时间：" + buDeviceStatistics.getOpenTime());
                    System.out.println("关闭时间：" + buDeviceStatistics.getOpenTime());

                    buDeviceStatisticsService.save(buDeviceStatistics);
//                    //查询实时数据表，拿到当前电能保存
//                    BuDeviceRunTime buDeviceRunTime = new BuDeviceRunTime();
//                    buDeviceRunTime.setDeviceId(buSensor.getDeviceId());
//                    buDeviceRunTime.setStartPower(buElectric.getEng());
//                    buDeviceRunTime.setDeviceTypeId(buDevice.getDeviceTypeId());
//                    buDeviceRunTimeService.save(buDeviceRunTime);
                }
            }
        }catch (Exception ex){
            System.out.println("状态改变接口发生异常");
            ex.printStackTrace();
        }finally {
            System.out.println("接口调用完成，检查传入的sensorId："+ sensorId);
        }
    }



    /**
     * 数据单页接口
     * 电能数据查询展示
     */
    @GetMapping(value = "/getElectricData")
    public Result<?> getElectricData(String deviceId) throws InterruptedException{
        List<BuSensor> buSensors = buSensorService.getByCheckName(deviceId,"%电能%");
        List<BuElectric> result = new ArrayList<>();
        for (BuSensor list : buSensors) {
        BuSensorType buSensorType = buSensorTypeService.getById(list.getTypeId());
        String tableName = buSensorType.getTableHead() + "_online";
            for (int i = 0;i<3;i++){
                List<BuElectric> buElectricList = buElectricService.getBySensorId(tableName,list.getId());
                TimeUnit.MILLISECONDS.sleep(100);
                if(buElectricList.size()>0){
                    return Result.OK(buElectricList);
                }
            }
            result.add(new BuElectric());
        }
        return Result.OK(result);
    }

    /**
     * 空气质量数据查询展示
     */
    @GetMapping(value = "/getAirQuality")
    public Result<?> getAirQuality(String deviceId) throws InterruptedException {
        List<BuSensor> buSensors = buSensorService.getByCheckName(deviceId,"%空气%");
        List<BuAirQuality> result = new ArrayList<>();
//        for (BuSensor list : buSensors){
            BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
            String tableName = buSensorType.getTableHead() + "_online";
                for (int i = 0;i<3;i++) {
                    List<BuAirQuality> buAirQuality = buAirQualityService.getBySensorId(tableName,buSensors.get(0).getId());
                    TimeUnit.MILLISECONDS.sleep(100);
                    if(buAirQuality.size()>0){
                        return Result.OK(buAirQuality);
                    }
                }
                result.add(new BuAirQuality());
//        }
        return Result.OK(result);
    }
    /**
     * 噪声质量数据查询展示
     */
    @GetMapping(value = "/getAirNoise")
    public Result<?> getAirNoise(String deviceId) throws InterruptedException {
        List<BuSensor> buSensors = buSensorService.getByCheckName(deviceId,"%噪声%");
        List<BuAirNoise> result = new ArrayList<>();
//        for (BuSensor list : buSensors){
            BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
            String tableName = buSensorType.getTableHead() + "_online";
            for (int i = 0;i<3;i++) {
                List<BuAirNoise> buAirNoises = buAirNoiseService.getBySensorId(tableName,buSensors.get(0).getId());
                TimeUnit.MILLISECONDS.sleep(100);
                if(buAirNoises.size()>0){
                    return Result.OK(buAirNoises);
                }
            }
            result.add(new BuAirNoise());
//        }
        return Result.OK(result);
    }
    /**
     * 烟雾质量数据查询展示
     */
    @GetMapping(value = "/getAirSmoke")
    public Result<?> getAirSmoke(String deviceId) throws InterruptedException {
        List<BuSensor> buSensors = buSensorService.getByCheckName(deviceId,"%烟雾%");
        List<BuAirSmoke> result = new ArrayList<>();
//        for (BuSensor list : buSensors){
        BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
        String tableName = buSensorType.getTableHead() + "_online";
        for (int i = 0;i<3;i++) {
            List<BuAirSmoke> buAirSmokes = buAirSmokeService.getBySensorId(tableName,buSensors.get(0).getId());
            TimeUnit.MILLISECONDS.sleep(100);
            if(buAirSmokes.size()>0){
                return Result.OK(buAirSmokes);
            }
        }
        result.add(new BuAirSmoke());
//        }
        return Result.OK(result);
    }
    /**
     * 烟雾质量数据查询展示
     */
    @GetMapping(value = "/getAirWater")
    public Result<?> getAirWater(String deviceId) throws InterruptedException {
        List<BuSensor> buSensors = buSensorService.getByCheckName(deviceId,"%烟雾%");
        List<BuAirWater> result = new ArrayList<>();
//        for (BuSensor list : buSensors){
        BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
        String tableName = buSensorType.getTableHead() + "_online";
        for (int i = 0;i<3;i++) {
            List<BuAirWater> buAirWaters = buAirWaterService.getBySensorId(tableName,buSensors.get(0).getId());
            TimeUnit.MILLISECONDS.sleep(100);
            if(buAirWaters.size()>0){
                return Result.OK(buAirWaters);
            }
        }
        result.add(new BuAirWater());
//        }
        return Result.OK(result);
    }
    /**
     * 实时振动值查询
     */
    @GetMapping(value = "/getVibrationValue")
    public Result<?> getVibrationValue(String deviceId) throws InterruptedException{
        List<BuSensor> buSensors = buSensorService.getByCheckName(deviceId,"%振动%");
        List<BuVibration> result = new ArrayList<>();
        for (BuSensor list : buSensors){
            BuSensorType buSensorType = buSensorTypeService.getById(list.getTypeId());
            String tableName = buSensorType.getTableHead() + "_online";
            for (int i = 0;i<3;i++) {
                List<BuVibration> buVibrations = buVibrationService.getBySensorId(tableName,list.getId());
                TimeUnit.MILLISECONDS.sleep(100);
                if(buVibrations.size()>0){
                    return Result.OK(buVibrations);
                }
            }
            result.add(new BuVibration());
        }
        return Result.OK(result);
    }

    /**
     * 单页风险项状态查询
     */
    @GetMapping(value = "/getDeviceItemStatus")
    public Result<?> getDeviceItemStatus(String deviceId){
        List<BuRiskItemValue> buRiskItemValue = buRiskItemValueService.getDeviceItemStatus(deviceId);
        return Result.OK(buRiskItemValue);
    }

    /**
     * 最新的历史振动曲线查询
     */
    @GetMapping(value = "/getVibrationCurve")
    public JSONObject getVibrationCurve(String deviceId){
        BuDevice buDevice = buDeviceService.getById(deviceId);
        List<BuSensor> buSensors = buSensorService.getByCheckName(deviceId,"%振动%");
        JSONObject obj = new JSONObject();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        LocalDateTime now = LocalDateTime.now();
        String formattedDate = now.format(formatter);
        for (BuSensor list : buSensors){
            BuSensorType buSensorType = buSensorTypeService.getById(list.getTypeId());
            String tableName = buSensorType.getTableHead() + "_history_" + buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + formattedDate;
            List<BuVibration> buVibrations = buVibrationService.getBySensorIdLimit(tableName,list.getId());
            obj.put(list.getName(),buVibrations);
        }
        return obj;
    }

    /**
     * 忽略异常调用接口
     */
    @GetMapping(value = "/faultIgnore")
    public void getFaultIgnore(String id){
        BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getById(id);
        buDeviceOnline.setStatus(2);
        buDeviceOnline.setUser("大屏操作员");
        buDeviceOnline.setProcessingTime(new Date());
        buDeviceOnlineService.updateById(buDeviceOnline);
    }

    /**
     * 数据推送接口
     */
    public String dataPush(BuDevice buDevice,String item){
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getUserByName("admin");
        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        sysAnnouncement.setTitile("您有一个新的风险提示");
        sysAnnouncement.setMsgContent(buDevice.getDeviceName() + "的" + item + ",请及时处理！");
        sysAnnouncement.setSender("admin");
        sysAnnouncement.setPriority("L");
        sysAnnouncement.setMsgCategory("1");
        sysAnnouncement.setMsgType("USER");
        sysAnnouncement.setSendStatus("0");
        sysAnnouncement.setSendTime(new Date());
        sysAnnouncement.setDelFlag("0");
        sysAnnouncement.setStartTime(new Date());
        sysAnnouncement.setEndTime(new Date());
        sysAnnouncement.setUserIds(sysUser.getId()+",");
        sysAnnouncement.setMsgAbstract("计划派送");
        sysAnnouncementService.saveAnnouncement(sysAnnouncement);
        sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_1);//发布中
        sysAnnouncement.setSendTime(new Date());
        boolean ok = sysAnnouncementService.updateById(sysAnnouncement);
        if(ok) {
            // 2.插入用户通告阅读标记表记录
            String userId = sysAnnouncement.getUserIds();
            String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
            JSONObject obj = new JSONObject();
            obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
            obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
            obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
            webSocket.sendMessage(userIds, obj.toJSONString());
        }
        return sysAnnouncement.getId();
    }

    /**
     * 首页右上角设备监测数据接口
     */
    @GetMapping(value = "/homeDeviceStatusData")
    public JSONObject homeDeviceStatusData(){
        JSONObject obj = new JSONObject();
        List<String> deviceName = new ArrayList<>();
        List<String> deviceCode = new ArrayList<>();
        List<String> statusOne = new ArrayList<>();
        List<String> statusTwo = new ArrayList<>();
        List<BuDevice> buDevices = buDeviceService.list();
        List<BuAirQuality> buAirQualities = buAirQualityService.getByTableName("bu_air_quality_online");
        for (BuDevice list : buDevices){
            deviceName.add(list.getDeviceName());
            deviceCode.add(list.getDeviceCode());
            List<BuSensor> buSensorElectric = buSensorService.getByCheckName(list.getId(),"%电能%");
            //获取电能表状态
            BuStatus buStatus1 = buStatusService.getDataBySensorId(buSensorElectric.get(0).getId());
            if (buStatus1.getSensorStatus() == 0){
                statusOne.add("0");
            }else if (buStatus1.getSensorStatus() == 1){//判断处于待机状态还是运行状态
//                BuSensorType buSensorType = buSensorTypeService.getById(buSensorElectric.get(0).getTypeId());
//                String tableName = buSensorType.getTableHead() + "_online";
//                BuElectric buElectric = buElectricService.getBySensorId(tableName,buSensorElectric.get(0).getId());
//                if (buElectric.getUdl() > 0.05 && buElectric.getVdl() > 0.05 && buElectric.getWdl() > 0.05){
//                    statusOne.add("2");//运行状态
//                }else {
                    statusOne.add("1");//待机状态
//                }
            }else {
                statusOne.add("2");
            }
            List<BuSensor> buSensorAirQuality = buSensorService.getByCheckName(list.getId(),"%空气%");
            if (buSensorAirQuality.size() == 0){
                statusTwo.add("0");
            }else {
                BuStatus buStatus2 = buStatusService.getDataBySensorId(buSensorAirQuality.get(0).getId());
                if (buStatus2.getSensorStatus() == 0){//未运行
                    statusTwo.add("0");
                }else {//处在运行状态，判断是否超标
//                    BuSensorType buSensorType = buSensorTypeService.getById(buSensorAirQuality.get(0).getTypeId());
//                    String tableName = buSensorType.getTableHead() + "_online";
//                    BuAirQuality buAirQuality = buAirQualityService.getBySensorId(tableName,buSensorAirQuality.get(0).getId());
                    for (BuAirQuality buAirQuality : buAirQualities){
                        if (buSensorAirQuality.get(0).getId().equals(buAirQuality.getSensorId())){
                            if (buAirQuality.getStatus() == 0){
                                statusTwo.add("1");
                            }else {
                                statusTwo.add("2");
                            }
                        }
                    }

                }
            }
        }
        obj.put("name",deviceName);
        obj.put("code",deviceCode);
        obj.put("one",statusOne);
        obj.put("two",statusTwo);
        return obj;
    }


    //调用第三方接口
    @GetMapping(value = "getTextMethodNow")
    public Result<?> getTextMethodNow(){
        //第三方接口api地址
        String path = "https://free-api.heweather.net/s6/weather/now?location=130203&key=db86a5196f304e52a4369818c5182e60";
        //需要传送的数据
        String data = "";
        interfaceDemo(path, data);
        System.out.println("成功");
        return Result.OK(true);
    }

    public static void interfaceDemo(String path, String data) {
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            //请求方式
            //conn.setRequestMethod("POST");
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                JSONObject json_test = JSONObject.parseObject(str);
                System.out.println(json_test);
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //所有设备按时间段查询功耗
    @GetMapping(value = "/getDeviceEnergy")
    public List<JSONObject> getDeviceEnergy(String beginTime){
        List<JSONObject> result = new ArrayList<>();
        List<BuDevice> buDevice = buDeviceService.getDevice();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = sdf.format(new Date());
        for (BuDevice list : buDevice){
            JSONObject obj = new JSONObject();
            String power = buDeviceEnergyStatisticsService.getDevicePower(list.getId(),beginTime,endTime);
            obj.put("name",list.getDeviceName());
            obj.put("value",power);
            result.add(obj);
        }
        return result;
    }
    //设备下传感器在线状态查询
    @GetMapping(value = "/getSensorOnline")
    public List<JSONObject> getSensorOnline(){
        List<JSONObject> result = new ArrayList<>();
        List<BuSensorData> buSensorData = buSensorDataService.getSensorData();
        for (BuSensorData list : buSensorData){
            JSONObject obj = new JSONObject();
            obj.put("name",list.getDeviceName());
            obj.put("hengjian",list.getHjhx());
            obj.put("shiyi",list.getSyq());
            result.add(obj);
        }
        return result;
    }
    //按时间段统计设备使用总时长
    @GetMapping(value = "/getDeviceUseTime")
    public List<JSONObject> getDeviceUseTime(String beginTime){
        List<JSONObject> result = new LinkedList<>();
        List<BuDevice> buDevice = buDeviceService.getDevice();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = sdf.format(new Date());
        for (BuDevice list : buDevice) {
            JSONObject obj = new JSONObject();
            int value = 0;
            String time = buDeviceStatisticsService.getDeviceUseTime(list.getDeviceName(),beginTime,endTime);
            if (time != null){
                value = Integer.parseInt(time);
            }
            obj.put("name",list.getDeviceName());
            obj.put("time",value);
            result.add(obj);
        }
        return result;
    }
    //按时间段展示设备使用次数
    @GetMapping(value = "/getDeviceUse")
    public List<JSONObject> getDeviceUse(String beginTime){
        List<JSONObject> result = new ArrayList<>();
        List<BuDevice> buDevice = buDeviceService.getDevice();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = sdf.format(new Date());
        for (BuDevice list : buDevice){
            JSONObject obj = new JSONObject();
            int value = 0;
            String times = buDeviceStatisticsService.getDeviceUseTimes(list.getDeviceName(),beginTime,endTime);
            if (times != null){
                value = Integer.parseInt(times);
            }
            obj.put("name",list.getDeviceName());
            obj.put("time",value);
            result.add(obj);
        }
        return result;
    }

    //按时间展示设备日历
//    @GetMapping(value = "/getDeviceCalendar")
//    public List<JSONObject> getDeviceCalendar(String deviceName,String date) throws ParseException {
//        List<JSONObject> result = new ArrayList<>();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//        Date dates = sdf.parse(date);
//        String year = String.format("%tY", dates);
//        String month = String.format("%tm", dates);
//        Calendar cal = Calendar.getInstance();
//        cal.setTime(dates);
//        int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//        for (int i=1; i<max+1; i++) {
//            JSONObject obj = new JSONObject();
//            BuDeviceStatistics buDeviceStatistics = buDeviceStatisticsService.getTimeData(deviceName,year,month,i);
//            obj.put("date",i);
//            if (buDeviceStatistics == null){
//                obj.put("status",-1);
//            }else {
//                BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getTimeData(deviceName,year,month,i);
//                if (buDeviceOnline == null){
//                    obj.put("status",0);
//                }else {
//                    if (buDeviceOnline.getRemindType() == 1){
//                        obj.put("status",1);
//                    }else {
//                        obj.put("status",2);
//                    }
//                }
//
//            }
//            result.add(obj);
//        }
//        return result;
//    }

    //传感器主板温度检测
//    @GetMapping(value = "/getMainBoard")
//    public List<String> getMainBoard(){
//        List<String> result = new ArrayList<>();
//        List<BuSensor> value = buSensorService.getBoardData();
//        if (value.size() == 0){
//            return result;
//        }
//        for (BuSensor buSensor : value) {
//            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
//            buDeviceOnline.setDeviceId(buSensor.getDeviceId());
//            buDeviceOnline.setDeviceName(buSensor.getDeviceName());
//            BuItemExplain buItemExplain = buItemExplainService.getByItem(buSensor.getDeviceName(),"9");
//            buDeviceOnline.setTime(new Date());
//            buDeviceOnline.setStatus(0);
//            buDeviceOnline.setSuggest(buItemExplain.getRemark());
//            double wd = Double.parseDouble(buSensor.getBatwd());
//            if (wd < 80 && wd > 70) {
//                String data = buSensor.getDeviceName() + "的" + buSensor.getName() + "位置温度过高预警，当前温度为" + wd + "℃。";
//                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buSensor.getDeviceId(),buSensor.getName() + "位置温度过高预警");
//                if (oldData.size() == 0){
//                    buDeviceOnline.setTestItem(buSensor.getName() + "传感器位置温度过高预警");
//                    buDeviceOnline.setRemind(data);
//                    buDeviceOnline.setRemindType(1);
//                    buDeviceOnlineService.save(buDeviceOnline);
//                    result.add(data);
//                }
//            } else if (wd >= 80) {
//                String data = buSensor.getDeviceName() + "的" + buSensor.getName() + "位置主板温度过高报警，当前温度为" + wd + "℃。";
//                List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buSensor.getDeviceId(),buSensor.getName() + "位置温度过高报警");
//                if (oldData.size() == 0){
//                    buDeviceOnline.setTestItem(buSensor.getName() + "传感器位置温度过高报警");
//                    buDeviceOnline.setRemind(data);
//                    buDeviceOnline.setRemindType(2);
//                    buDeviceOnlineService.save(buDeviceOnline);
//                    result.add(data);
//                }
//            }
//        }
//        return result;
//    }




    //获取当前试验台四种状态数量
    @GetMapping(value = "/getDeviceStatus")
    public Result<?> getDeviceStatus(){
        int[] result = new int[4];
        QueryWrapper<BuDevice> queryWrapper = new QueryWrapper<>();
        List<BuDevice> buDevice = buDeviceService.list(queryWrapper);
        zhuangtai(result, buDevice);
        return Result.OK(result);
    }

    public static void zhuangtai(int[] result, List<BuDevice> buDevice) {
        for (BuDevice list : buDevice) {
            if (list.getRepairLine().equals("0")){
                result[0] += 1;
            }else if (list.getRepairLine().equals("1")){
                result[1] += 1;
            }else if (list.getRepairLine().equals("2")){
                result[2] += 1;
            }else {
                result[3] += 1;
            }
        }
    }

    //按时间获取所有设备合格率
//    @PostMapping(value = "postAllPassRate")
//    public List<JSONObject> postAllPassRate() {
//        List<JSONObject> result = new ArrayList<>();
//        List<String> table = buDeviceService.getTableName();
//        int year =  gettimer();
//
////        int year =  2023;
//
//        for (int i = 1; i < 13; i++) {
//            JSONObject obj = new JSONObject();
//            int a = 0;
//            int b = 0;
//            for (String name : table) {
////                int x = buDeviceService.getPassRate(i, name, "合格");
////                int y = buDeviceService.getPassRate(i, name, "不合格");
//                int x = buDeviceService.getPassRate(year,i, name, "合格");
//                int y = buDeviceService.getPassRate(year,i, name, "不合格");
//                a = a + x;
//                b = b + y;
//            }
//            obj.put("合格", a);
//            obj.put("不合格", b);
//            result.add(obj);
//        }
//        return result;
//    }
//    public int gettimer()
//    {
//        Calendar cal= Calendar.getInstance();
//        int yy=cal.get(Calendar.YEAR);
//        int m=cal.get(Calendar.MONTH);
//        int d=cal.get(Calendar.DATE);
//        int h=cal.get(Calendar.HOUR_OF_DAY);
//        int mi=cal.get(Calendar.MINUTE);
//        int s=cal.get(Calendar.SECOND);
//        System.out.println("现在时刻是"+yy+"年"+m+"月"+d+"日"+h+"时"+mi+"分"+s+"秒");
//
//        return yy;
//    }


    // 大屏上振动传感器测量温度显示
    @GetMapping(value = "/getVibrateTemperature")
    public double[] getVibrateTemperature(String deviceName) {
        double[] result = new double[4];
        List<String> list = buSensorService.getIpByName(deviceName);
        for (int i=0; i<list.size(); i++) {
            String tableName = "vib_" + list.get(i) + "wendu_dto";
            result[i] = buSensorService.getTemperature(tableName);
        }
        return result;
    }
    // 大屏上异常信息数据简单显示
    @GetMapping(value = "/getUnusual")
    public List<BuDeviceOnline> getUnusual(String deviceName,String item) {
        switch (item) {
            case "未读预警数":
                return buDeviceOnlineService.getAlarmStatusUnusual(deviceName);
            case "未读报警数":
                return buDeviceOnlineService.getWarningStatusUnusual(deviceName);
            case "电机故障数":
                return buDeviceOnlineService.getFaultStatusUnusual(deviceName);
            case "轴承故障数":
                return buDeviceOnlineService.getBearingStatusUnusual(deviceName);
            default:
                return new ArrayList<>();
        }
    }
    // 大屏上设备日历简单显示异常
    @GetMapping(value = "/getCalendarUnusual")
    public List<BuDeviceOnline> getCalendarUnusual(String deviceName,String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dates = sdf.parse(date);
        String year = String.format("%tY", dates);
        String month = String.format("%tm", dates);
        String day = String.format("%td", dates);
        return buDeviceOnlineService.getCalendarRemind(deviceName,year,month,day);
    }
    //传感器电池电压显示
    @GetMapping(value = "/getBatteryVoltage")
    public String[] getBatteryVoltage(String deviceName){
        List<String> list = buSensorService.getBatteryVoltage(deviceName);
        String[] result = new String[list.size()];
        for (int i=0; i<list.size(); i++){
            double x = Double.parseDouble(list.get(i));
            int y = (int)(400 * x / 3 - 380);
            result[i] = y + "%";
        }
        return result;
    }
    //设备使用时长、次数
//    @GetMapping(value = "/getDeviceData")
//    public String[] getDeviceData(String deviceName){
//        String[] result = new String[2];
//        double time = 0;
//        DecimalFormat df = new DecimalFormat("0.00");
//        BuDevice buDevice = buDeviceService.getDeviceByName(deviceName);
//        List<BuDeviceStatistics> list = buDeviceStatisticsService.getDataById(buDevice.getId());
//        int count = list.size();
//        for (BuDeviceStatistics buDeviceStatistics : list) {
//            time = time + Double.parseDouble(buDeviceStatistics.getTotalOpenTime());
//        }
//        result[0] = df.format(time / 3600);
//        result[1] = String.valueOf(count);
//        return result;
//    }


    //查询传感器电池电压，低于3V通知更换
//    @GetMapping(value = "/powerRemind")
//    public List<String> powerRemind() {
//        List<BuSensor> buSensor = buSensorService.getPowerData();
//        List<String> deviceId = buSensor.stream().map(BuSensor::getDeviceId).collect(Collectors.toList());
//        List<String> deviceName = buSensor.stream().map(BuSensor::getDeviceName).collect(Collectors.toList());
//        List<String> name = buSensor.stream().map(BuSensor::getName).collect(Collectors.toList());
////        List<String> power = buSensor.stream().map(BuSensor::getPower).collect(Collectors.toList());
//        List<String> result = new ArrayList<>();
//        if (buSensor.size() == 0){
//            return result;
//        }
////        List<String> fault = new ArrayList<>();
//        for (int i = 0; i < buSensor.size(); i++) {
////            String data = deviceName.get(i) + "的" + name.get(i) + "电池电压低，请及时更换电池，当前电池电压为" + power.get(i) + "V。";
//            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(deviceId.get(i),name.get(i) + "电池电压低");
//            if (oldData.size() == 0){
//                BuItemExplain buItemExplain = buItemExplainService.getByItem(deviceName.get(i),"9");
//                BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
//                buDeviceOnline.setDeviceId(deviceId.get(i));
//                buDeviceOnline.setDeviceName(deviceName.get(i));
//                buDeviceOnline.setTime(new Date());
//                buDeviceOnline.setTestItem(name.get(i) + "电池电压低");
//                buDeviceOnline.setRemindType(0);
////                buDeviceOnline.setRemind(data);
//                buDeviceOnline.setStatus(0);
//                buDeviceOnline.setSuggest(buItemExplain.getRemark());
//                buDeviceOnlineService.save(buDeviceOnline);
////                result.add(data);
//            }
//        }
//        return result;
//    }

    //开关机信息查询
    @GetMapping(value = "/getOpenTime")
    public List<JSONObject> getOpenTime(String deviceName){
        List<JSONObject> result = new ArrayList<>();
        BuDevice buDevice = buDeviceService.getDeviceByName(deviceName);
        List<BuDeviceStatistics> buDeviceStatistics = buDeviceStatisticsService.getLastTime(buDevice.getId());
        for (BuDeviceStatistics list : buDeviceStatistics) {
            JSONObject obj = new JSONObject();
            obj.put("begin", list.getOpenTime());
            obj.put("end", list.getCloseTime());
            result.add(obj);
        }
        return result;
    }

    //预警报警信息状态查询
    @GetMapping(value = "getRemindStatus")
    public Integer[] getRemindStatus(String deviceName){
        Integer[] result = new Integer[4];
        int alarm = buDeviceOnlineService.getAlarmStatus(deviceName);
        int warning = buDeviceOnlineService.getWarningStatus(deviceName);
        int em = buDeviceOnlineService.getFaultStatus(deviceName);
        int bearing = buDeviceOnlineService.getBearingStatus(deviceName);
        result[0] = alarm;
        result[1] = warning;
        result[2] = em;
        result[3] = bearing;
        return result;
    }


    //网关在线监测
//    @GetMapping(value = "getGatewayOnline")
//    public List<String> getGatewayOnline(String deviceName) {
//        List<String> result = new ArrayList<>();
//        BuDevice buDevice = buDeviceService.getDeviceByName(deviceName);
//        //状态表查询
//        LambdaQueryWrapper<BuStatus> LambdaQueryWrapper = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper.eq(BuStatus::getSensorId,buDevice.getId());
//        BuStatus buStatus = buStatusService.list(LambdaQueryWrapper).get(0);
//
//        if (buStatus.getDeviceStatus()==1){
//            QueryWrapper<BuGateway> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("online_status","False");
//            queryWrapper.eq("device_name",deviceName);
//            List<BuGateway> buGateway = buGatewayService.list(queryWrapper);
//            if (buGateway.size() == 0){
//                return result;
//            }else {
//                for (BuGateway list : buGateway){
//                    BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
//                    buDeviceOnline.setDeviceId(buDevice.getId());
//                    buDeviceOnline.setDeviceName(buDevice.getDeviceName());
//                    buDeviceOnline.setTime(new Date());
//                    buDeviceOnline.setRemindType(1);
//                    buDeviceOnline.setTestItem("断网异常");
//                    buDeviceOnline.setRemind(deviceName + "的" + list.getName() + "处于离线状态，请检查。");
//                    buDeviceOnline.setStatus(0);
//                    buDeviceOnlineService.save(buDeviceOnline);
//
//                    result.add(deviceName + "的" + list.getName() + "处于离线状态，请检查。");
//                }
//            }
//        }
//        return result;
//    }


    //零部件更换提醒
    @GetMapping(value = "getSpareReplace")
    public List<String> getSpareReplace(){
        List<String> result = new ArrayList<>();
        List<BuSparePart> buSparePart = buSparePartService.getSpareData();
        Date nowTime = new Date();//格式需要修改
        for (BuSparePart sparePart : buSparePart) {//循环获取所有零部件的信息，再判断是否需要更换
            Date time = sparePart.getMinStock();
            long count = Integer.parseInt(sparePart.getUnit());
            long difference = nowTime.getTime() - time.getTime();
            long value = count * 24 * 3600 * 1000;
            if (difference > value) {
                result.add(sparePart.getRemind());
                LocalDate localDate = nowTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                Date newTime = java.sql.Date.valueOf(localDate);
                sparePart.setMinStock(newTime);
                buSparePartService.updateById(sparePart);

                BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
                buDeviceOnline.setDeviceName(sparePart.getName());
                buDeviceOnline.setTime(new Date());
                buDeviceOnline.setRemindType(5);
                buDeviceOnline.setRemind(sparePart.getRemind());
                buDeviceOnline.setStatus(0);
                buDeviceOnlineService.save(buDeviceOnline);
            }
        }
        return result;
    }

    @PostMapping(value = "getTest1")
    public ResultJson  getTest1(@RequestBody ReceiveStatus receiveStatus){
        ResultJson resultJson = new ResultJson();
        resultJson.setCode(0);
        resultJson.setSuccess(true);
        resultJson.setMessage("");
        System.out.println("11111111111111111"+receiveStatus);
        return resultJson;
    }

    // 获取频谱倍频峰值数组,只针对电机的振动传感器振动频谱数据
    public double[] AlgorithmPEAKfd(double[] Pinpu, double[] Bearing_Frequency, double[] SetHzRange) {
        double[] PEAK = new double[10];
        //1.获取包络频域原始数据
        // 理论基频Hz
        double outer = Bearing_Frequency[0];
        //***** 故障频率的计算公式：外圈（frequency_outer_ring）、内圈（frequency_inner_ring）、滚子（frequency_roller）、保持架（frequency_holder）
        double outer_position = outer * 0.4;
        try
        {
            double MSR_noise = 0; // 包络频域均方根
            for (double v : Pinpu) {
                MSR_noise += v * v;
            }
            // 获取门限值:频域均方根
            MSR_noise = java.lang.Math.sqrt(MSR_noise / Pinpu.length);
            //二、计算各个频点区域内符合故障特征基频的最大值
            //在指定范围内(2Hz)大于2* MSR_noise的区域，获取各个区域的最大值和频率Hz
            double threshold_value = 2.5 * MSR_noise;//2倍的均方根是个关键值
            if (threshold_value > 0.05){
                int start_flag = 0, end_flag = 0, start_position = 0, end_position = 0;
                // 创建键值，保存各个区域的最大值（值）及频点（键）
//              Dictionary<int, double> keyDic = new Dictionary<uint, double>();
                List<Double> keyDic = new LinkedList<>();
                // 设定的特征频率查找范围（Hz）
                double span_in_axis_outer = SetHzRange[0] * 0.4;
                double span_in_axis_fd = SetHzRange[1] * 0.4;
                // 2.2 外圈、内圈、滚子(滚单、滚双)、保持架、齿轮、临齿故障定位，及参数值确定  V2019.1.18_wyj
//            double unit_max = 0;
                for (int m = (int)Math.abs(outer_position - span_in_axis_outer); m <= (int)Math.abs(outer_position + span_in_axis_outer); m++)
                {
                    if ((Pinpu[m] >= threshold_value) && (Pinpu[m - 1] < threshold_value) && (start_flag == 0) && (end_flag == 0))  // 确定＞=阈值区域的起始位置
                    {
                        start_flag = 1;
                        start_position = m;
                    }
                    if (Pinpu[m] >= threshold_value && Pinpu[m + 1] < threshold_value && start_flag == 1)   // 确定＞=阈值区域的结束位置
                    {
                        end_flag = 1;
                        end_position = m;
                    }
                    else if ((m == (int)Math.abs(outer_position + span_in_axis_outer + 10)) && (Pinpu[m + 1] >= threshold_value))
                    {
                        end_flag = 1;
                        end_position = m;
                    }
                    //2.1、获取大于2倍的均方根的区域内的最大值和最大值所在的频点
                    //***** 获取gE值在[临界值，正无穷]间的频点，获取此区间频点的最大gE值
                    if ((start_flag == 1) && (end_flag == 1))    // 存在符合要求的区域，再证明2倍频是否存在
                    {
                        //2.1.1 将区域内所有的峰值区域划分出来
//                    int position = 0;
                        double max_value = 0;   // 峰值区域内最大值
                        //2.1.2 获取区域内的最大值，及对应频点
                        for (int i = start_position; i < end_position + 1; i++)
                        {
                            // 获取峰值区域内的最大值
                            if (max_value < Pinpu[i])
                            {
                                max_value = Pinpu[i];
//                            position = i;
                            }
                        }
                        keyDic.add(max_value);
                        start_flag = 0;
                        end_flag = 0;
                        end_position = 0;
                        start_position = 0;
                        PEAK[0] = max_value;
                    }
                }
                //2.2 键值排序：从大至小。排序基频区域
                if (keyDic.size() > 0)
                {
//                var list = keyDic.OrderBy(s => s.Value);   //升序排列
                    // 2.3 计算2倍频  从value高值向低值计算
                    for (int i = 0; i > -1; i--)
                    {
                        int key = 20;
//                    double value = keyDic.get(0);
                        for (int n=1; n< 10; n++)
                        {
                            double max = 0;
                            // 在1Hz范围内查找2倍频判断幅值是否大于n*RMS
                            for (int j = (int)Math.abs(key * (n+1) - span_in_axis_fd); j < (int)Math.abs(key * (n + 1) + span_in_axis_fd); j++)
                            {
                                if (Pinpu[j] >= threshold_value)
                                {
                                    double num = Pinpu[j];
                                    if (max < num)
                                    {
                                        max = num;
                                    }
                                }
                            }
                            PEAK[n] = max;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            log.error("振动分析异常");
            throw ex;
        }
        return PEAK;
    }
    /// 1. 算法运算，得到轴承的故障等级和参数数值
    /// <param name="Pinyu">包络频域数值</param>
    /// <param name="ShiYu">加速度时域数值</param>
    /// <param name="Base_Frequency">轴承的故障特征基频</param>
    /// <param name="SetHzRange">允许故障特征基频的偏移范围</param>
    /// <param name="Speed">检测时的机车轮对转速</param>
    /// <param name="dt">SQL中设定的轴承阈值</param>应为时域均方根故障等级上下限，有三行，九列数据
    public double[] Get_Bearing_AlarmClassAndValue(double[] Pinyu, double[] ShiYu, double[] Base_Frequency, double[] SetHzRange, int[] SetFrequencyNumber,double[] dt)
    {
        // 等级
        double rms_alert_class;//均方根报警级别， 输出值。
        double kv_alert_class;//翘度报警级别， 输出值。
        double outer_ring_alert_class;//外圈报警级别，  输出值。
        double inner_ring_alert_class;//内圈报警级别，输出值。
        double roller_alert_class;//滚子报警级别，    输出值。
        double holder_alert_class;//保持架报警级别， 输出值。

        double gear_alert_class;//齿轮报警级别， 输出值。
        double teeth_alert_class;//临齿报警级别， 输出值。

        // 数值
        double rms_diagnosis_value;//时域均方根诊断值，输出值。
        double kv_diagnosis_value;//时域峭度指标诊断值，输出值。
        double outer_ring_diagnosis_value;//外圈诊断值，输出值。
        double inner_ring_diagnosis_value;//内圈诊断值，输出值。
        double roller_diagnosis_value;//滚子诊断值，输出值。
        double holder_diagnosis_value;//保持架诊断值，输出值。

        double gear_diagnosis_value;//齿轮诊断值，输出值。
        double teeth_diagnosis_value;//临齿诊断值，输出值。

        // 获取轴承报警数值
        double rms_normal = dt[0];
        double rms_alarm1 = dt[1];
        double rms_alarm2 = dt[2];
//        DataRow[] dr = dt.Select(" GradeType='预警'");
//        double rms_normal = double.Parse(dr[0]["RMS"].ToString());
//        double kv_normal = double.Parse(dr[0]["KV"].ToString());
//
//        dr = dt.Select(" GradeType='二级'");
//        double rms_alarm2 = double.Parse(dr[0]["RMS"].ToString());
//        double kv_alarm2 = double.Parse(dr[0]["KV"].ToString());
//
//        dr = dt.Select(" GradeType='一级'");
//        double rms_alarm1 = double.Parse(dr[0]["RMS"].ToString());
//        double kv_alarm1 = double.Parse(dr[0]["KV"].ToString());

        // 得到均方根+翘度系数
        double[] RMS_KV = Get_RMS_KV(ShiYu);
        double rms = RMS_KV[0];
        double kv = RMS_KV[1];

        BigDecimal bd = new BigDecimal(rms);
        BigDecimal bds = new BigDecimal(kv);
        rms_diagnosis_value = bd.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();
        kv_diagnosis_value = bds.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();
        if (rms < rms_normal)
        {
            // 界面故障等级：显示无
            rms_alert_class = 0.0;
            kv_alert_class = 0.0;

            // 界面数值：外、内、滚、保持架0.0 0.0 0.0 0.0 ；时域均方根值
            outer_ring_alert_class = 0.0;
            inner_ring_alert_class = 0.0;
            roller_alert_class = 0.0;//滚单代表滚子
            holder_alert_class = 0.0;//保内代表保持架
            gear_alert_class = 0.0;//齿轮报警级别， 输出值。
            teeth_alert_class = 0.0;//临齿报警级别， 输出值。

            outer_ring_diagnosis_value = 0.0;
            inner_ring_diagnosis_value = 0.0;
            roller_diagnosis_value = 0.0;//滚单代表滚子
            holder_diagnosis_value = 0.0;//保内代表保持架

            gear_diagnosis_value = 0.0;//齿轮诊断值，输出值。
            teeth_diagnosis_value = 0.0;//临齿诊断值，输出值。
        }
        else if (rms >= rms_normal && rms < rms_alarm2)
        {
            //确定均方根报警级别
            double rms_class = rms / rms_alarm1;
            if (rms_class >= 1)
            {
                rms_alert_class = 2;  //均方根为一级级别
            }
            else
            {
                rms_alert_class = 1;  //均方根为预警级别
            }
            kv_alert_class = 0;
//            double kv_class = kv / kv_alarm1;
//            if (kv_class >= 1)
//            {
//                kv_alert_class = 2;  //均方根为一级级别
//            }
//            else
//            {
//                kv_alert_class = 1;  //均方根为预警级别
//            }

            // 算法
            double[] peak = Algorithm(Pinyu, Base_Frequency, SetHzRange, SetFrequencyNumber);         //算法３，先计算基频
            double[] valueClass = algorithmClassPEAKfd(peak, dt);

            // 获取报警数值+等级
            outer_ring_diagnosis_value = valueClass[0];
            outer_ring_alert_class = valueClass[6];

            inner_ring_diagnosis_value = valueClass[1];
            inner_ring_alert_class = valueClass[7];

            roller_diagnosis_value = valueClass[2];
            roller_alert_class = valueClass[8];

            holder_diagnosis_value = valueClass[3];
            holder_alert_class = valueClass[9];

            gear_diagnosis_value = valueClass[4];
            gear_alert_class = valueClass[10];

            teeth_diagnosis_value = valueClass[5];
            teeth_alert_class = valueClass[11];
        }
        else
        {
            //界面显示故障：外、内、滚、保持架无；均方根二级
            rms_alert_class = 3;
            kv_alert_class = 0.0;

            outer_ring_alert_class = 0.0;
            inner_ring_alert_class = 0.0;
            roller_alert_class = 0.0;//滚单代表滚子
            holder_alert_class = 0.0;//保内代表保持架
            gear_alert_class = 0.0;
            teeth_alert_class = 0.0;

            outer_ring_diagnosis_value = 0.0;
            inner_ring_diagnosis_value = 0.0;
            roller_diagnosis_value = 0.0;//滚单代表滚子
            holder_diagnosis_value = 0.0;//保内代表保持架
            gear_diagnosis_value = 0.0;
            teeth_diagnosis_value = 0.0;
        }
//        double[] para = new double[] { rms_alert_class, kv_alert_class, outer_ring_alert_class, inner_ring_alert_class, roller_alert_class, holder_alert_class,gear_alert_class,teeth_alert_class,
//                rms_diagnosis_value,kv_diagnosis_value,outer_ring_diagnosis_value,inner_ring_diagnosis_value,roller_diagnosis_value,holder_diagnosis_value,gear_diagnosis_value,teeth_diagnosis_value};
        return new double[] { rms_alert_class, kv_alert_class, outer_ring_alert_class, inner_ring_alert_class, roller_alert_class, holder_alert_class,gear_alert_class,teeth_alert_class,
                rms_diagnosis_value,kv_diagnosis_value,outer_ring_diagnosis_value,inner_ring_diagnosis_value,roller_diagnosis_value,holder_diagnosis_value,gear_diagnosis_value,teeth_diagnosis_value};
    }
    // 获取频谱倍频峰值数组,只针对轴承的分析
    public double[] Algorithm(double[] Pinpu, double[] Bearing_Frequency, double[] SetHzRange, int[] SetFrequencyNumber) {
        double[] PEAK = new double[6];
        // 理论基频Hz
        double outer = Bearing_Frequency[0];
        double inner = Bearing_Frequency[1];
        double rolling = Bearing_Frequency[2];
        double holder_single = Bearing_Frequency[3];
        double gear = Bearing_Frequency[4];
        double teeth = Bearing_Frequency[5];
        //***** 故障频率的计算公式：外圈（frequency_outer_ring）、内圈（frequency_inner_ring）、滚子（frequency_roller）、保持架（frequency_holder）
        double outer_position = outer * 0.4;
        double inner_position = inner * 0.4;
        double rolling_position = rolling * 0.4;
        double holder_single_position = holder_single * 0.4;
        double gear_position = gear * 0.4;
        double teeth_position = teeth * 0.4;
        try
        {
            double MSR_noise = 0; // 包络频域均方根
            for (double v : Pinpu) {
                MSR_noise += v * v;
            }
            // 获取门限值:频域均方根
            MSR_noise = java.lang.Math.sqrt(MSR_noise / Pinpu.length);
            //二、计算各个频点区域内符合故障特征基频的最大值
            double threshold_value = 1.8 * MSR_noise;//2倍的均方根是个关键值
//            int start_flag = 0, end_flag = 0, start_position = 0, end_position = 0;
            // 创建键值，保存各个区域的最大值（值）及频点（键）
//              Dictionary<int, double> keyDic = new Dictionary<uint, double>();
            List<JSONObject> keyDic = new ArrayList<>();
            // 2.1 计算内、外、滚子基频的距离差； 获取外圈、内圈、滚子的设定范围
            double Diff_IO = Math.abs(inner_position - outer_position);  // 内圈外圈的基频差值
            double Diff_OR = Math.abs(outer_position - rolling_position);// 外圈滚子的基频差值
            double Diff_HZ = Math.abs(holder_single_position / 2);       // 因为保持架基频很小，所以无需取与滚子的差值
            // 设定的特征频率查找范围（Hz）
            double span_in_axis_outer = SetHzRange[0] * 0.4;
            double span_in_axis_inner = SetHzRange[1] * 0.4;
            double span_in_axis_rolling = SetHzRange[2] * 0.4;
            double span_in_axis_holder_single = SetHzRange[3] * 0.4;
            double span_in_axis_gear = SetHzRange[4] * 0.4;
            double span_in_axis_teeth = SetHzRange[5] * 0.4;
            double span_in_axis_fd = SetHzRange[6] * 0.4;
            //以最小距离差确定查找范围
            if (span_in_axis_outer > Diff_IO / 2)  // 外圈取值范围
            {
                span_in_axis_outer = Diff_IO / 2;
            }
            if (span_in_axis_inner > Diff_IO / 2)  // 内圈取值范围
            {
                span_in_axis_inner = Diff_IO / 2;
            }
            if (span_in_axis_rolling > Diff_OR / 2)  // 滚子取值范围
            {
                span_in_axis_rolling = Diff_OR / 2;
            }
            if (span_in_axis_rolling > Diff_HZ)
            {
                span_in_axis_holder_single = Diff_HZ;
            }
            // 2.2 外圈、内圈、滚子(滚单、滚双)、保持架、齿轮、临齿故障定位，及参数值确定
            double[] position_units = new double[] { outer_position, inner_position, rolling_position, holder_single_position, gear_position, teeth_position };
            double[] span_in_axis_units = new double[] { span_in_axis_outer, span_in_axis_inner, span_in_axis_rolling, span_in_axis_holder_single, span_in_axis_gear, span_in_axis_teeth };

            for (int k = 0; k < PEAK.length; k++)
            {
                double position_unit = position_units[k];
                double span_in_axis_unit = span_in_axis_units[k];
                double unit_max = 0;
                keyDic.clear();
                keyDic = GetPeakAreas(Pinpu, position_unit, span_in_axis_unit, threshold_value);
                //2.2 键值排序：从大至小。排序基频区域
                if (keyDic.size() > 0)
                {
                    for (int i = keyDic.size() - 1; i > -1; i--)
                    {
                        int key = (int)keyDic.get(i).get("x");
                        // 在1Hz范围内查找2倍频判断幅值是否大于n*RMS
                        double value_max = (double)keyDic.get(i).get("y");  //倍频中最大的幅值,先赋值-基频幅值
                        int fn = 1;  //实际连续倍频个数
                        for (int m = 2; m <= SetFrequencyNumber[k]; m++)
                        {
                            double startPosition = key * m;
                            List<JSONObject> dict = GetPeakAreas(Pinpu, startPosition, span_in_axis_fd, threshold_value);
                            if (dict.size() > 0)
                            {
                                //所有峰值中最大的幅值+最大幅值所在位置
                                double maxPeakValue = (double)(dict.get(0).get("y"));
//                                double maxPeakPosition = (double)dict.get(0).get("x");
                                fn++;
                                if (value_max < maxPeakValue)
                                {
                                    value_max = maxPeakValue;
                                }
                            }
                            if (fn < m)
                            {
                                break;
                            }
                        }
                        // 判断连续倍频数与设置的倍频数之间是否相同，相同，说明故障成立；不相同，说明无故障
                        if (fn >= SetFrequencyNumber[k])
                        {
                            //unit_max = value;
                            unit_max = value_max;
                            break;
                        }
                    }
                }
                PEAK[k] = unit_max;
            }
            //滚子-滚双-增加滚双诊断
            if (PEAK[2] == 0)
            {
                keyDic.clear();
                double position_unit = rolling_position * 2;

                keyDic = GetPeakAreas(Pinpu, position_unit, span_in_axis_rolling, threshold_value);
                //2.2 键值排序：从大至小。排序基频区域
                if (keyDic.size() > 0)
                {
                    // 2.3 计算2倍频  从value高值向低值计算
                    for (int i = keyDic.size() - 1; i > -1; i--)
                    {
                        int key = (int)keyDic.get(i).get("x");
                        // 在1Hz范围内查找2倍频判断幅值是否大于5*RMS
                        double value_max = (double)keyDic.get(i).get("y");  //倍频中最大的幅值,先赋值-基频幅值
                        int fn = 1;  //实际连续倍频个数
                        for (int m = 2; m <= SetFrequencyNumber[2]; m++)
                        {
                            double startPosition = key * m;
                            List<JSONObject> dict = GetPeakAreas(Pinpu, startPosition, span_in_axis_fd, threshold_value);
                            //所有峰值中最大的幅值+最大幅值所在位置
                            double maxPeakValue = (double)dict.get(0).get("y");
//                            double maxPeakPosition = (double)dict.get(i).get("x");
                            if (dict.size() > 0)
                            {
                                fn++;
                                if (value_max < maxPeakValue)
                                {
                                    value_max = maxPeakValue;
                                }
                            }
                            // 倍频个数小于设置的循环倍频，说明倍频不是连续的，因此退出计算
                            if (fn < m)
                            {
                                break;
                            }
                        }
                        // 判断连续倍频数与设置的倍频数之间是否相同，相同，说明故障成立；不相同，说明无故障
                        if (fn >= SetFrequencyNumber[2])
                        {
                            PEAK[2] = value_max;
                            break;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            log.error("轴承倍频分析异常");
            throw ex;
        }
        return PEAK;
    }
    /// 获取筛选区域内，各个峰值区域的峰值+位置，所有峰值中最大峰值+位置
    /// </summary>
    /// <param name="Pinpu">数组</param>
    /// <param name="StartPosition">起始位置</param>
    /// <param name="Range">查找范围</param>
    /// <param name="ThresholdValue">门限值</param>
    /// <returns></returns>
    private List<JSONObject> GetPeakAreas(double[] Pinpu, double StartPosition, double Range, double ThresholdValue)
    {
        int start_flag = 0, end_flag = 0, start_position = 0, end_position = 0;

        List<JSONObject> keyDic = new ArrayList<>();
        for (int m = (int)Math.abs(StartPosition - Range); m <= (int)Math.abs(StartPosition + Range); m++)
        {
            JSONObject obj = new JSONObject();
            if (Pinpu[m] >= ThresholdValue && Pinpu[m - 1] < ThresholdValue && start_flag == 0)  // 确定＞=阈值区域的起始位置
            {
                start_flag = 1;
                start_position = m;
            }
            if (Pinpu[m] >= ThresholdValue && Pinpu[m + 1] < ThresholdValue && start_flag == 1)   // 确定＞=阈值区域的结束位置
            {
                end_flag = 1;
                end_position = m;
            }
            //获取大于1.8倍的均方根的区域内的最大值和最大值所在的频点
            if ((start_flag == 1) && (end_flag == 1))    // 存在符合要求的区域，再证明2倍频是否存在
            {
                //2.1.1 将区域内所有的峰值区域划分出来
//                int start = 0;
//                int end = 0;
                int position = 0;
                double max_value = 0;   // 峰值区域内最大值
                //2.1.2 获取区域内的最大值，及对应频点
                for (int i = start_position; i < end_position + 1; i++)
                {
                    // 获取峰值区域内的最大值
                    if (max_value < Pinpu[i])
                    {
                        max_value = Pinpu[i];
                        position = i;
                    }
                }
                obj.put("x",position);
                obj.put("y",max_value);

                start_flag = 0;
                end_flag = 0;
                end_position = 0;
                start_position = 0;
                keyDic.add(obj);
            }
        }
        return keyDic;
    }
    /// 1.1 由时域得到均方根值和峭度系数
    /// </summary>
    /// <param name="ShiYu">时域数值</param>
    /// <returns>均方根值和峭度系数</returns>
    public double[] Get_RMS_KV(double[] ShiYu)
    {
        double[] rmsKv = new double[2];
        double kv = 0;
        double rms = 0;
        int shiyuLength = ShiYu.length;
        if (shiyuLength == 1 && ShiYu[0] == 0)
        {
            return rmsKv;
        }
        for (double v : ShiYu) {
            kv += Math.pow(v, 4);
            rms += Math.pow(v, 2);
        }
        kv = kv / shiyuLength;      // 峭度值
        rms = Math.sqrt(rms / shiyuLength); // 均方根

        double rms4 = Math.pow(rms, 4);
        rmsKv[0] = rms; // 均方根
        rmsKv[1] = kv / rms4;                  // 峭度指标
        return rmsKv;
    }
    /// 算法2
    /// </summary>
    /// <param name="PEAK">等到的指标数值</param>
    /// <param name="dt"></param>
    /// <returns></returns>
    public double[] algorithmClassPEAKfd(double[] PEAK, double[] dt)
    {
//         数值：0外圈、1内圈、2滚子、3保持架、4齿轮、5临齿；等级：6外圈、7内圈、8滚子、9保持架、10齿轮、11临齿
        double[] valueTemp = new double[12];
        for (int i = 0; i < PEAK.length; i++)
        {
            if (PEAK[i] > 0)
            {
                valueTemp[i] = PEAK[i];   // 将幅值赋值给此故障轴承部件
                // 划分等级
//                int count = dt.length;
                double[] alarm_Value = new double[3];
                alarm_Value[0] = dt[3];
                alarm_Value[1] = dt[4];
                alarm_Value[2] = dt[5];
                for (int j = 1; j < 3; j++)
                {
                    // 等级计算
                    if (PEAK[i] >= alarm_Value[j - 1] && PEAK[i] < alarm_Value[j])
                    {
                        valueTemp[valueTemp.length / 2 + i] = j;//lcz这里有问题，valueTemp.Length / 2 + i - 1应该去掉-1
                        break;
                    }
                    else if (PEAK[i] >= alarm_Value[2])
                    {
                        valueTemp[valueTemp.length / 2 + i] = 3;
                        break;
                    }
                }
            }
        }
        return valueTemp;  // 获取报警数值+等级 外圈、内圈、滚子、保持架、齿轮、临齿
    }

    @ApiOperation(value="本月设备类型的能耗", notes="本月设备类型运行时间")
    @GetMapping(value = "/getDeviceTypeEnergy")
    public Result<?> getDeviceTypeEnergy() {
        Date date = new Date();
        int year = date.getYear() + 1900;
        int month = date.getMonth() + 1;
        List<DeviceRiskAnalysis> deviceTypeEnergys = buDeviceOnlineService.getDeviceTypeEnergy(String.valueOf(year),String.valueOf(month));
//        List<BuDeviceType> buDeviceTypes = buDeviceTypeService.list();
        List<String> collectList = new ArrayList<>();
        List<String> powerList = new ArrayList<>();
        List<String> runTimeList = new ArrayList<>();
//        for (BuDeviceType list : buDeviceTypes){

            for (DeviceRiskAnalysis deviceRiskAnalysis : deviceTypeEnergys){
//                if (list.getId().equals(deviceRiskAnalysis.getDeviceId())){
                    collectList.add(deviceRiskAnalysis.getDeviceId());
                    powerList.add(deviceRiskAnalysis.getPower());
                    runTimeList.add(deviceRiskAnalysis.getRunTime());
//                }
//                else {
//                    powerList.add("0");
//                    runTimeList.add("0");
//                }
            }
//        }
        JSONObject obj = new JSONObject();
        obj.put("typeName",collectList);
        obj.put("power",powerList);
        obj.put("runTime",runTimeList);
        return Result.OK(obj);
    }
    @ApiOperation(value="设备年/月/日运行时间", notes="设备年/月/日运行时间")
    @GetMapping(value = "/getDeviceYearMonthDayTimes")
    public Result<?> getDeviceYearMonthDayTimes(String deviceId) {
        Date date = new Date();
        int year = date.getYear() + 1900;
        int month = date.getMonth() + 1;
        int day = date.getDate();
        DeviceRiskAnalysis yearRunTime = buDeviceOnlineService.getYearRunTime(String.valueOf(year), deviceId);
        DeviceRiskAnalysis monthRunTime = buDeviceOnlineService.getMonthRunTime(String.valueOf(year),String.valueOf(month), deviceId);
        DeviceRiskAnalysis dayRunTime = buDeviceOnlineService.getDayRunTime(String.valueOf(year),String.valueOf(month),String.valueOf(day), deviceId);
        Integer[] i = new Integer[3];
        if(yearRunTime!=null){
            i[0] = Integer.valueOf(yearRunTime.getRunTime());
        }else {
            i[0] = 0;
        }
        if(monthRunTime!=null){
            i[1] = Integer.valueOf(monthRunTime.getRunTime());
        }else{
            i[1] = 0;
        }
        if(dayRunTime!=null){
            i[2] = Integer.valueOf(dayRunTime.getRunTime());
        }else {
            i[2] = 0;
        }
        return Result.OK(i);
    }
    @ApiOperation(value="设备年/月/日风险次数", notes="设备年/月/日风险次数")
    @GetMapping(value = "/getDeviceYearMonthDayRisks")
    public Result<?> getDeviceYearMonthDayRisks(String deviceId) {
        Date date = new Date();
        int year = date.getYear() + 1900;
        int month = date.getMonth() + 1;
        int day = date.getDate();
        DeviceRiskAnalysis yearRunRisk = buDeviceOnlineService.getYearRiskCount(String.valueOf(year), deviceId);
        DeviceRiskAnalysis monthRunRisk = buDeviceOnlineService.getMonthRiskCount(String.valueOf(year),String.valueOf(month), deviceId);
        DeviceRiskAnalysis dayRunRisk = buDeviceOnlineService.getDayRiskCount(String.valueOf(year),String.valueOf(month),String.valueOf(day), deviceId);
        Integer[] i = new Integer[3];
        if(yearRunRisk!=null){
            i[0] = Integer.valueOf(yearRunRisk.getCount());
        }else {
            i[0] = 0;
        }
        if(monthRunRisk!=null){
            i[1] = Integer.valueOf(monthRunRisk.getCount());
        }else{
            i[1] = 0;
        }
        if(dayRunRisk!=null){
            i[2] = Integer.valueOf(dayRunRisk.getCount());
        }else {
            i[2] = 0;
        }
        return Result.OK(i);
    }
}
