<template>
  <div id="J_prismPlayer" />
</template>

<script setup>
import { nextTick, onBeforeUnmount, onMounted, watch } from "vue";
import { useDocumentVisibility } from "@vueuse/core";

let player = null;
defineOptions({
  name: "AliPlayer",
});
const props = defineProps({
  source: {
    type: [String, Array],
    default: "",
  },
  vid: {
    type: String,
    default: "",
  },
  playAuth: {
    type: String,
    default: "",
  },
  cover: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "600px",
  },
});
const visibility = useDocumentVisibility();
onMounted(() => {
  watch(
    [() => props.source, () => props.vid, () => props.playAuth],
    () => {
      if (props.source || (props.vid && props.playAuth)) fnCreateAliPlayer();
    },
    {
      immediate: true,
    }
  );
  watch(
    () => visibility.value,
    () => {
      if (visibility.value === "hidden") {
        pause();
      } else {
        play();
      }
    },
    {
      immediate: true,
    }
  );
});
const fnCreateAliPlayer = async () => {
  await nextTick();
  fnDisposeAliPlayer();
  player = new window.Aliplayer(
    {
      id: "J_prismPlayer",
      ...(props.source
        ? { source: props.source }
        : {
            vid: props.vid,
            playauth: props.playAuth,
            qualitySort: "asc",
            format: "m3u8",
            encryptType: 1,
            mediaType: "video",
            autoplay: true,
            isLive: false,
            rePlay: false,
            playsinline: true,
            controlBarVisibility: "hover",
          }),
      cover: props.cover,
      width: props.width,
      height: props.height,
      autoplay: true,
      useH5Prism: true,
    },
    (player) => {
      player.play();
    }
  );
};
const fnDisposeAliPlayer = () => {
  if (!player) return;
  player.dispose();
  player = null;
};
onBeforeUnmount(() => {
  fnDisposeAliPlayer();
});
const play = () => {
  player && player.play();
};
const pause = () => {
  player && player.pause();
};
defineExpose({
  play,
  pause,
});
</script>

<style scoped lang="scss">
#J_prismPlayer {
  width: v-bind(width);
  height: v-bind(height);
}
</style>
