package org.jeecg.modules.job;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.*;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.constant.WebsocketConst;
import org.jeecg.modules.bigScreen.controller.bigScreenController;
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.BuAirNoise;
import org.jeecg.modules.energy.entity.BuAirWater;
import org.jeecg.modules.energy.entity.BuFlowOnline;
import org.jeecg.modules.energy.service.IBuAirWaterService;
import org.jeecg.modules.message.websocket.WebSocket;
import org.jeecg.modules.sensor.entity.BuSensor;
import org.jeecg.modules.sensor.service.IBuSensorService;
import org.jeecg.modules.sensor.service.IBuStatusService;
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.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;

public class llcgqDetectionJob implements Job {
    @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 ISysUserService sysUserService;


    @Autowired
    private org.jeecg.modules.energy.service.IBuFlowOnlineService buFlowOnlineService;


    @Autowired
    private ISysAnnouncementService sysAnnouncementService;

    @Resource
    private WebSocket webSocket;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            //获取正在运行的传感器id：空气质量表获取状态为1的
            List<BuFlowOnline> buFlowOnline = buFlowOnlineService.getllcgqByStatus();
            if(buFlowOnline.size()<=0){
                return;
            }

            for (BuFlowOnline buflowOnline : buFlowOnline){
                BuSensor buSensor = buSensorService.getById(buflowOnline.getSensorId());
                BuDevice buDevice = buDeviceService.getById(buSensor.getDeviceId());
                waterHigh(buDevice,buflowOnline);
            }
        }catch (Exception ex){
            System.out.println("异常信息：" + ex);
        }
    }

    public class MqttClientService11 {
        private static final String BROKER_URL = "tcp://127.0.0.1:1883";
        private static final String CLIENT_ID = "MQTT_FX_Client";
        private MqttClient client;
        public MqttClientService11() throws MqttException {
            // Initialize the MQTT client and connect to the broker.
            this.client = new MqttClient(BROKER_URL, CLIENT_ID);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);

            try {
                if(client == null)
                {
                    client.connect(options);
                }
                else
                {
//                    System.out.println("已经连接成功");
                }


                client.setCallback(new MqttCallback() {
                    @Override
                    public void connectionLost(Throwable cause) {
                        //当与服务器的连接丢失时调用。
                    }
                    @Override
                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        //当消息从服务器到达时调用。

                        System.out.println("数据送到" + message.toString());
                    }
                    @Override
                    public void deliveryComplete(IMqttDeliveryToken token) {
                        //当传输中的消息成功发送到代理时调用。
                        System.out.println("数据接收" + token);
                    }
                });
            } catch (MqttException e) {
                e.printStackTrace();
                System.out.println("异常信息：" + e);
            }
        }
        public void publishMessage(String topic, String payload) throws MqttException {
            MqttMessage message = new MqttMessage(payload.getBytes());//推送主题
            client.publish(topic, message);
        }

        public void subscribeToTopic(String topic) throws MqttException {//订阅主题
            client.subscribe(topic);
        }
    }



    //地坑积水报警
    public void waterHigh(BuDevice buDevice,BuFlowOnline buFlowOnline){
        BuRiskItem buRiskItem = buRiskItemService.getById("566706136");
        BuRiskItemValue buRiskItemValue = buRiskItemValueService.getDataByTwoId(buDevice.getId(),buRiskItem.getId());

        int sta = buRiskItemValue.getStatus();
        System.out.println("风险状态"+sta);

        if (!Objects.equals(buRiskItemValue.getEnabled(), "0")){
            return;
        }
        if (buFlowOnline.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(7);
                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(buFlowOnline));
                //数据推送，并且绑定消息id
                String annId = dataPush(buDevice,buDeviceOnline.getRemind());
                buDeviceOnline.setId(annId);
                buDeviceOnlineService.save(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();
    }
}
