package org.jeecg.modules.jobXxl;

import com.alibaba.fastjson.JSON;
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.IBuDeviceOnlineService;
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.BuFlowOnline;
import org.jeecg.modules.energy.service.IBuAirWaterService;
import org.jeecg.modules.energy.service.IBuFlowOnlineService;
import org.jeecg.modules.job.MqttProductPush;
import org.jeecg.modules.sensor.entity.BuSensor;
import org.jeecg.modules.sensor.service.IBuSensorService;
import org.jeecg.modules.sensor.service.IBuStatusService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class flowsensorJob
{
    @Autowired
    private IBuDeviceService buDeviceService;
    @Autowired
    private IBuSensorService buSensorService;
    @Autowired
    private IBuStatusService buStatusService;
    @Autowired
    private IBuAirWaterService buAirWaterService;
    @Autowired
    private IBuDeviceOnlineService buDeviceOnlineService;
    @Autowired
    private IBuRiskItemService buRiskItemService;
    @Autowired
    private IBuRiskItemValueService buRiskItemValueService;
    @Autowired
    private MqttProductPush mqttProductPush;

    @Autowired
    private IBuFlowOnlineService buFlowOnlineService;


    @XxlJob("flowsensorJob")
    public void executeElectricDetectionJob() throws Exception
    {
        try {

            System.out.println("a555" +  LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            //获取正在运行的传感器id：空气质量表获取状态为1的
            List<BuFlowOnline> buFlowOnlines = buFlowOnlineService.getllcgqByStatus();
            if(buFlowOnlines.size()<=0){
                return;
            }
            for (BuFlowOnline buflow : buFlowOnlines){
                BuSensor buSensor = buSensorService.getById(buflow.getSensorId());
                BuDevice buDevice = buDeviceService.getById(buSensor.getDeviceId());
                waterHigh(buDevice,buflow);
            }
        }catch (Exception ex){
            System.out.println("异常信息：" + ex);
        }
    }
    //地坑积水报警
    public void waterHigh(BuDevice buDevice, BuFlowOnline buFlowOnlines){
        BuRiskItem buRiskItem = buRiskItemService.getById("566706135");
        BuRiskItemValue buRiskItemValue = buRiskItemValueService.getDataByTwoId(buDevice.getId(),buRiskItem.getId());
        if (!Objects.equals(buRiskItemValue.getEnabled(), "0")){
            return;
        }
        if (buFlowOnlines.getDischarge() > buRiskItemValue.getMultiple())
        {
            List<BuDeviceOnline> oldData = buDeviceOnlineService.getLastTimeData(buDevice.getId(),buRiskItem.getRiskName());
            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(6);
                buDeviceOnline.setTestItem(buRiskItem.getRiskName());
                buDeviceOnline.setRemind(buRiskItem.getRiskExplain());
                buDeviceOnline.setStatus(0);
                buDeviceOnline.setRiskExplain(buRiskItem.getRiskExplain());
                buDeviceOnline.setRiskHarm(buRiskItem.getRiskHarm());
                buDeviceOnline.setSuggest(buRiskItem.getDealAdvice());
                buDeviceOnline.setRiskData(JSON.toJSONString(buFlowOnlines));
                //数据推送，并且绑定消息id

                String annId = mqttProductPush.dataPush(buDevice,buDeviceOnline.getRemind());
                buDeviceOnline.setId(annId);
                buDeviceOnlineService.save(buDeviceOnline);
                //推送到mqtt
                mqttProductPush.JobPush(buDeviceOnline);
                //更改风险项
                if (buRiskItemValue.getStatus() == 1){
                    buRiskItemValue.setStatus(0);
                    buRiskItemValueService.updateById(buRiskItemValue);
                }
            }
        }
    }
    /**
     * 数据推送接口
     */
//    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_RISK);
//            obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
//            obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
//            webSocket.sendMessage(userIds, obj.toJSONString());
//        }
//        return sysAnnouncement.getId();
//    }
}
