package com.ruoyi.websocket.listener;

import com.ruoyi.common.event.BroadcastStartedEvent;
import com.ruoyi.common.event.PlayPlanChangedEvent;
import com.ruoyi.common.event.PlayPlanDisabledEvent;
import com.ruoyi.websocket.service.WebSocketPushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 屏幕端 WebSocket 事件监听器
 * 负责将业务事件推送到 WebSocket 客户端
 *
 * @author ruoyi
 */
@Component
public class ScreenWebSocketEventListener {

    private static final Logger log = LoggerFactory.getLogger(ScreenWebSocketEventListener.class);

    @Autowired(required = false)
    private WebSocketPushService webSocketPushService;

    /**
     * 处理播放方案变化事件
     */
    @Async
    @EventListener
    public void onPlayPlanChanged(PlayPlanChangedEvent event) {
        if (webSocketPushService == null) {
            log.warn("[ScreenEvent] WebSocketPushService 未配置，忽略播放方案变化事件");
            return;
        }
        try {
            log.info("[ScreenEvent] 收到播放方案变化事件，推送 WebSocket");
            webSocketPushService.pushPlayPlanChanged(event.getPlanData());
        } catch (Exception e) {
            log.error("[ScreenEvent] 推送播放方案变化失败", e);
        }
    }

    /**
     * 处理播放方案禁用事件
     */
    @Async
    @EventListener
    public void onPlayPlanDisabled(PlayPlanDisabledEvent event) {
        if (webSocketPushService == null) {
            log.warn("[ScreenEvent] WebSocketPushService 未配置，忽略播放方案禁用事件");
            return;
        }
        try {
            log.info("[ScreenEvent] 收到播放方案禁用事件，推送 WebSocket: planId={}", event.getPlanId());
            webSocketPushService.pushPlayPlanDisabled(event.getPlanId());
        } catch (Exception e) {
            log.error("[ScreenEvent] 推送播放方案禁用失败", e);
        }
    }

    /**
     * 处理播报开始事件
     */
    @Async
    @EventListener
    public void onBroadcastStarted(BroadcastStartedEvent event) {
        if (webSocketPushService == null) {
            log.warn("[ScreenEvent] WebSocketPushService 未配置，忽略播报开始事件");
            return;
        }
        try {
            log.info("[ScreenEvent] 收到播报开始事件，推送 WebSocket: taskId={}", event.getTaskId());
            webSocketPushService.pushBroadcastStarted(
                    event.getTaskId(),
                    event.getContentId(),
                    event.getTaskName(),
                    event.getTitle(),
                    event.getContent(),
                    event.getContentType(),
                    event.getAudioUrl(),
                    event.getAudioDuration()
            );
        } catch (Exception e) {
            log.error("[ScreenEvent] 推送播报开始失败", e);
        }
    }
}
