package org.jeecg.modules.jobXxl;

import com.xxl.job.core.handler.annotation.XxlJob;
import org.jeecg.modules.device.entity.BuDevice;
import org.jeecg.modules.device.entity.BuDeviceOnline;
import org.jeecg.modules.device.entity.BuRiskItem;
import org.jeecg.modules.device.entity.BuRiskItemValue;
import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.device.service.IBuRiskItemService;
import org.jeecg.modules.device.service.IBuRiskItemValueService;
import org.jeecg.modules.energy.entity.BuVibration;
import org.jeecg.modules.energy.service.IBuVibrationService;
import org.jeecg.modules.job.MqttProductPush;
import org.jeecg.modules.sensor.entity.BuSensor;
import org.jeecg.modules.sensor.service.IBuSensorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
public class BatteryVoltageJob {

    @Autowired
    private IBuDeviceService buDeviceService;
    @Autowired
    private IBuSensorService buSensorService;
    @Autowired
    private IBuVibrationService buVibrationService;
    @Autowired
    private IBuRiskItemService buRiskItemService;
    @Autowired
    private IBuRiskItemValueService buRiskItemValueService;
    @Autowired
    private MqttProductPush mqttProductPush;

    @XxlJob("BatteryVoltageJob")
    public void executeBatteryVoltageJob() throws Exception {
        try {
            //获取正在运行的传感器id：振动表获取状态为1的
            List<BuVibration> buVibrations = buVibrationService.getVibrationByStatus();
            if(buVibrations.size()<=0){
                return ;
            }
            for (BuVibration buVibration : buVibrations){
                BuSensor buSensor = buSensorService.getById(buVibration.getSensorId());
                BuDevice buDevice = buDeviceService.getById(buSensor.getDeviceId());
                batteryVoltage(buDevice,buVibration);
            }
        }catch (Exception ex){
            System.out.println("异常信息：" + ex);
            throw new Exception("电池实时监测失败："+ex.getMessage());
        }
    }

    //电池欠压检测
    public void batteryVoltage(BuDevice buDevice, BuVibration buVibration){
        BuRiskItem buRiskItem = buRiskItemService.getById("566706131");
        BuRiskItemValue buRiskItemValue = buRiskItemValueService.getDataByTwoId(buDevice.getId(),buRiskItem.getId());
        if (!Objects.equals(buRiskItemValue.getEnabled(), "0")){
            return;
        }
        if (buVibration.getVoltage() < buRiskItemValue.getMultiple()){
            //创建新的风险信息
            BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
            buDeviceOnline.setRemind(buRiskItem.getRiskExplain());
            //数据推送，并且绑定消息id
            mqttProductPush.dataPushBattery(buDevice,buDeviceOnline.getRemind());
        }
    }
}
