package org.jeecg.modules.job;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.constant.WebsocketConst;
import org.jeecg.config.mqtt.MqttGateway;
import org.jeecg.modules.buzzer.entity.BuBuzzer;
import org.jeecg.modules.buzzer.entity.BuBuzzerOnline;
import org.jeecg.modules.buzzer.service.IBuBuzzerOnlineService;
import org.jeecg.modules.buzzer.service.IBuBuzzerService;
import org.jeecg.modules.device.entity.BuDevice;
import org.jeecg.modules.device.entity.BuDeviceOnline;
import org.jeecg.modules.device.service.IBuDeviceOnlineService;
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.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.stereotype.Component;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Component
public class MqttProductPush  {
    @Autowired
    private MqttGateway mqttGateway;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysAnnouncementService sysAnnouncementService;
    @Resource
    private WebSocket webSocket;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private IBuDeviceOnlineService buDeviceOnlineService;

    @Autowired
    private IBuBuzzerOnlineService ibBuzzerOnlineService;

    @Autowired
    private IBuSensorService iBuSensorService;

    public void start(String name)
    {
        if( name.equals(null) || name.equals("架车机") || name.equals("洗车机") || name.equals("不落轮镟床"))
        {
            writeField(1,name);
            try {
                Thread.sleep(10000); // 保证主线程至少运行10秒，以便给定的任务有机会执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            writeField(0,name);
        }
        if(name == "" || name == null)
        {
            return;
        }
    }

    private void writeField(int value , String name) {

        QueryWrapper<BuBuzzerOnline> queryWrapper = new QueryWrapper<>();
        BuBuzzerOnline updateInfo = new BuBuzzerOnline();

//        if(name.equals("架车机"))
//        {
//            queryWrapper.eq("sensor_id", "1911661573062443010"); // 假设'id'是你想更新的记录的ID
//        }
//        if(name.equals("洗车机"))
//        {
//            queryWrapper.eq("sensor_id", "1933912151969300496");
//        }
//        if(name.equals("不落轮镟床"))
//        {
//            queryWrapper.eq("sensor_id", "202504101641465246204");
//        }

        updateInfo.setOnOff(value);

        QueryWrapper<BuSensor> bsq = new QueryWrapper<>();
        bsq.eq("device_name",name);
        bsq.eq("type_id","HJ-ALERT-485"); //报警灯协议编号
        BuSensor buSensor = iBuSensorService.getOne(bsq);
        queryWrapper.eq("sensor_id",buSensor.getId());

//        boolean updateResult = ibBuzzerOnlineService.update(updateInfo, queryWrapper);
//        if (updateResult) {
//            System.out.println("Field value updated successfully.");
//        } else {
//            System.out.println("Failed to update field value.");
//        }
    }


    /**
     * mqtt推送
     * @param buDeviceOnline
     */
    public void JobPush(BuDeviceOnline buDeviceOnline){
        JSONObject obj = new JSONObject();
        obj.put("deviceId",buDeviceOnline.getDeviceId());//设备ID
        obj.put("deviceName",buDeviceOnline.getDeviceName());//设备名称
        obj.put("deviceCode",buDeviceOnline.getDeviceCode());//设备编码
        obj.put("testItem",buDeviceOnline.getTestItem());//风险名称
        obj.put("riskExplain",buDeviceOnline.getRiskExplain());//风险说明
        obj.put("riskHarm",buDeviceOnline.getRiskHarm());//风险危害
        obj.put("suggest",buDeviceOnline.getSuggest());//处理建议

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateStr = dateFormat.format(buDeviceOnline.getTime());
        obj.put("time",dateStr);//发生时间

        start(buDeviceOnline.getDeviceName());
        System.out.println("推送数据：" + obj.toJSONString());
        mqttGateway.sendToMqtt("data_producer", obj.toJSONString());
    }

    /**
     * 系统数据推送接口
     */
    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(buDevice.getDeviceName() + "的" + "风险推送");
        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();
    }
    /**
     * 数据推送接口
     */
    public void dataPushBattery(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.setUserIds(sysUser.getId() + ",");
        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.setMsgAbstract(buDevice.getDeviceName() + "的" + "电池电压提醒");
        sysAnnouncementService.saveAnnouncement(sysAnnouncement);
        sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_1);//发布中
        sysAnnouncement.setSendTime(new Date());
        boolean ok = sysAnnouncementService.updateById(sysAnnouncement);
        if (ok) {
            String userId = sysAnnouncement.getUserIds();
            String[] userIds = userId.substring(0, (userId.length() - 1)).split(",");
            JSONObject obj = new JSONObject();
            obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_VOLTAGE);
            obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
            obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
            obj.put(WebsocketConst.MSG_CHAT, sysAnnouncement.getMsgContent());
            webSocket.sendMessage(userIds, obj.toJSONString());
        }
    }

    /**
     * 地坑驾车机报警提示
     *
     * @param value
     * @return
     */
    public String dataPushJCJ(String value) {
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getUserByName("admin");
        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        sysAnnouncement.setTitile("架车机报警提示");
        sysAnnouncement.setMsgContent(value + ",请及时处理！");
        sysAnnouncement.setSender("admin");
        sysAnnouncement.setUserIds(sysUser.getId() + ",");
        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.setMsgAbstract("架车机报警:"+value);

        sysAnnouncementService.saveAnnouncement(sysAnnouncement);
        sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_1);//发布中
        sysAnnouncement.setSendTime(new Date());
        boolean ok = sysAnnouncementService.updateById(sysAnnouncement);
        if (ok) {
            String userId = sysAnnouncement.getUserIds();
            String[] userIds = userId.substring(0, (userId.length() - 1)).split(",");
            JSONObject obj = new JSONObject();
            obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_JCJ);
            obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
            obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
            obj.put(WebsocketConst.MSG_CHAT, sysAnnouncement.getMsgContent());
            webSocket.sendMessage(userIds, obj.toJSONString());
        }
        return sysAnnouncement.getId();
    }

}
