package com.dcs.hnyz.task;

import com.alibaba.fastjson2.JSON;
import com.dcs.equipment.server.EquipmentListWebSocketServer;
import com.dcs.equipment.task.ModbusTcpTask;
import com.dcs.hnyz.cache.CacheCenter;
import com.dcs.hnyz.domain.AlarmEvent;
import com.dcs.hnyz.domain.dto.AlarmBroadcastPayload;
import com.dcs.hnyz.domain.vo.EquipmentParamFormVO;
import com.dcs.hnyz.domain.vo.PageDeviceRealtimeVO;
import com.dcs.hnyz.service.IActionConfigService;
import com.dcs.hnyz.service.IDeviceDataService;
import com.dcs.hnyz.service.impl.ActionConfigServiceImpl;
import com.dcs.hnyz.service.impl.AlarmConfigServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * WebSocketPushTask
 * 定时推送任务
 * @author: hmy
 * @date: 2025/5/30 16:06
 */
@Component("WebSocketPushTask")
public class WebSocketPushTask {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    private EquipmentListWebSocketServer equipmentListWebSocketServer;

    @Autowired
    private IDeviceDataService deviceDataService;

    @Autowired
    private AlarmConfigServiceImpl alarmConfigService;

    @Autowired
    private ActionConfigServiceImpl actionConfigService;

    @Autowired
    private ModbusTcpTask modbusTcpTask;
    /**
     * 每1秒推送一次组态页面所需实时数据
     */
    public void pushData() {
        modbusTcpTask.updateDataToEquipmentParamFormVOList();
        CacheCenter.pageDeviceGroupMap.forEach((pageCode, deviceGroupMap) -> {
            Map<String, List<PageDeviceRealtimeVO>> data = deviceDataService.buildRealtimeData(deviceGroupMap);
            messagingTemplate.convertAndSend("/topic/page/" + pageCode, data);
        });
    }


    /**
     * 告警信息信息检测推送
     */
    public void pushAlarmInfo(){
        List<AlarmEvent> alarms = alarmConfigService.checkAlarms();
        if (!alarms.isEmpty()) {
//            System.out.println("有告警信息");
            AlarmBroadcastPayload payload = new AlarmBroadcastPayload();
            payload.setAlarms(alarms);
            String json = JSON.toJSONString(payload);
            equipmentListWebSocketServer.broadCastInfo(json);
        }
    }

    /**
     * 动作配置扫描执行
     */
    public void actionConfig(){
        actionConfigService.checkActions();
    }
}

