<template>
  <!-- <el-dialog
    class="dialog"
    v-model="dialogVisible"
    :title="videoTitle"
    :width="width"
    :before-close="handleClose"
  > -->
    <div ref="domRef" class="video" v-if="dialogVisible"></div>
    <!-- <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关 闭</el-button>
      </span>
    </template>
  </el-dialog> -->
</template>

<script setup name="VideoPlay">
import VideoPlayer from "xgplayer";
import "xgplayer/dist/index.min.css";
import {computed, nextTick, onMounted, onUnmounted, ref, watch} from "vue";

const props = defineProps({
  visible: {
    required: true,
    type: Boolean,
    default: false,
  },
  videoTitle: {
    type: String,
    default: "视频播放",
  },
  url: {
    required: true,
    type: String,
    
  },
  width: {
    type: String,
    default: "600px",
  },
  autoplay: {
    type: Boolean,
    default: true,
  },
  loop: {
    type: Boolean,
    default: true,
  },
});
const emit = defineEmits(["update:visible"]);

// dom ref
const domRef = ref();
const player = ref();

// computed
const dialogVisible = computed(() => props.visible);

// 渲染播放器
function renderXgPlayer() {
  if (!domRef.value) return;
  const url = props.url;
  player.value = new VideoPlayer({
    el: domRef.value,
    url,
    playbackRate: [0.5, 0.75, 1, 1.5, 2],
    // 允许自动播放
    loop:props.loop,
    autoplay: props.autoplay,
    muted: props.autoplay,
    autoplayMuted: props.autoplay,
  });
}
// 销毁播放器
function destroyXgPlayer() {
  player.value?.destroy();
}

// 关闭弹窗
function handleClose() {
  emit("update:visible", false);
}

// 监听显示与隐藏 控制播放器播放与销毁
watch(
  () => dialogVisible.value,
  (val) => {
    if (val) {
      nextTick(() => {
        renderXgPlayer();
      });
    } else {
      destroyXgPlayer();
    }
  }
);

onMounted(() => {
  renderXgPlayer();
});
</script>

<style lang="scss" scoped>
.video {
  width: 100% !important;
  height: 100% !important;
  &:deep(.xgplayer-start) {
    width: 50px;
    height: 50px;
  }
}
</style>
