package com.fs.live.controller;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.R;
import com.fs.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 直播行为推送控制器（HTTP转发接口）
 *
 * @author 夏伟
 * @date 2026-01-20
 */
@Slf4j
@RestController
@RequestMapping("/app/live/behavior")
public class LiveBehaviorPushController extends BaseController {

    /**
     * 接收HTTP转发的行为数据并推送到WebSocket
     *
     * @param params 包含liveId和behaviors的参数
     * @return 推送结果
     */
    @PostMapping("/push")
    public R pushBehaviors(@RequestBody Map<String, Object> params) {
        try {
            Long liveId = Long.valueOf(params.get("liveId").toString());
            @SuppressWarnings("unchecked")
            List<String> behaviors = (List<String>) params.get("behaviors");

            log.info("[HTTP转发] 收到推送请求, liveId={}, count={}", liveId, behaviors.size());

            if (behaviors.isEmpty()) {
                return R.error("参数错误");
            }

            if (!SpringUtils.containsBean("webSocketServer")) {
                log.error("[HTTP转发] WebSocketServer不存在");
                return R.error("WebSocketServer不存在");
            }

            Object webSocketServer = SpringUtils.getBean("webSocketServer");
            if (webSocketServer == null) {
                log.error("[HTTP转发] 获取WebSocketServer失败");
                return R.error("获取WebSocketServer失败");
            }

            Object sendMsgVo = buildBatchMessage(liveId, behaviors);
            String message = JSONObject.toJSONString(R.ok().put("data", sendMsgVo));

            Method broadcastMethod = webSocketServer.getClass()
                .getMethod("broadcastMessage", Long.class, String.class);
            broadcastMethod.invoke(webSocketServer, liveId, message);

            log.info("[HTTP转发] 推送成功, liveId={}, count={}", liveId, behaviors.size());

            return R.ok("推送成功");

        } catch (Exception e) {
            log.error("[HTTP转发] 推送失败", e);
            return R.error("推送失败: " + e.getMessage());
        }
    }

    /**
     * 构建批量推送消息
     */
    private Object buildBatchMessage(Long liveId, List<String> behaviorList) {
        try {
            Class<?> sendMsgVoClass = Class.forName("com.fs.live.websocket.bean.SendMsgVo");
            Object sendMsgVo = sendMsgVoClass.newInstance();

            // 解析为对象列表
            List<Map<String, Object>> behaviors = new ArrayList<>();
            for (String behaviorStr : behaviorList) {
                try {
                    Map<String, Object> behavior = JSONObject.parseObject(behaviorStr, Map.class);
                    behaviors.add(behavior);
                } catch (Exception e) {
                    log.warn("[HTTP转发] 解析行为数据失败: {}", behaviorStr);
                }
            }

            sendMsgVoClass.getMethod("setLiveId", Long.class).invoke(sendMsgVo, liveId);
            sendMsgVoClass.getMethod("setCmd", String.class).invoke(sendMsgVo, "behaviorTrackBatch");
            sendMsgVoClass.getMethod("setMsg", String.class).invoke(sendMsgVo, "用户行为实时更新");
            sendMsgVoClass.getMethod("setData", String.class).invoke(sendMsgVo, JSONObject.toJSONString(behaviors));

            return sendMsgVo;
        } catch (Exception e) {
            log.warn("[HTTP转发] 构建消息失败", e);
            // 返回简单的Map作为备用
            Map<String, Object> msg = new HashMap<>();
            msg.put("liveId", liveId);
            msg.put("cmd", "behaviorTrackBatch");
            msg.put("msg", "用户行为实时更新");
            msg.put("data", "[" + String.join(",", behaviorList) + "]");
            return msg;
        }
    }
}
