<script setup>
import { onMounted, onBeforeUnmount, watch } from "vue";

const props = defineProps({
  videoUrl: String
});

const playerContainer = ref(null);
const player = ref(null);

const initPlayer = () => {
  if (!props.videoUrl || !playerContainer.value) return;

  // 彻底清理旧实例（关键修改）
  if (player.value) {
    player.value.JS_StopRealPlayAll();
    player.value.JS_Destroy();
    playerContainer.value.innerHTML = ""; // 清空容器
  }

  // 重新创建容器（避免残留元素）
  const container = document.createElement("div");
  container.id = "player-container";
  container.style.width = "100%";
  container.style.height = "100%";
  playerContainer.value.appendChild(container);

  // 初始化新实例
  player.value = new JSPlugin({
    szId: "player-container", // 必须与创建的容器ID一致
    szBasePath: "js/",
    openDebug: true,
    supportGMProtocol: true, // 启用国密协议支持
    iWidth:"100%",
    iHeight:"100%",
  });

  player.value.JS_Play(props.videoUrl, {
    onError: (err) => console.error("播放失败:", err)
  });
};

// 监听URL变化
watch(() => props.videoUrl, initPlayer);

onMounted(initPlayer);

onBeforeUnmount(() => {
  if (player.value) {
    player.value.JS_StopRealPlayAll();
    player.value.JS_Destroy();
  }
  if (playerContainer.value) {
    playerContainer.value.innerHTML = ""; // 确保清理
  }
});
</script>

<template>
  <!-- 固定结构，不设ID -->
  <div ref="playerContainer" class="video-monitor-container"></div>
</template>

<style scoped>
.video-monitor-container {
  width: 95%;
  height: 100%;
  min-height: 500px; /* 防止折叠 */
}
</style>