<template>
  <div ref="videoRef"></div>
</template>

<script lang="ts">
/*
 * @Author: Liao.xiuli
 * @Date: 2021-09-18 11:18:59
 * @Last Modified by: Liao.xiuli
 * @Last Modified time: 2023-08-28 16:50:58
 */
export default {
  name: "WlVideo",
};
</script>

<script setup lang="ts">
import Player from "xgplayer";
import type { IPlayerOptions } from "xgplayer";
import { ref, onMounted } from "vue";
import { loadImage } from "@mobileUI/utils/index";
type Props = {
  poster?: string;
  videoUrl?: string;
};
const props = withDefaults(defineProps<Props>(), {
  poster: "",
  videoUrl: "",
});

type TimeUpdateProps = {
  duration: number;
  currentTime: number;
};

const emit = defineEmits<{
  (e: "onTimeUpdate", val: TimeUpdateProps);
}>();

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

const initVideo = (videoW?, videoH?) => {
  // 这里的videoRef可以换成video元素的id "videobox"
  let playerOptions: IPlayerOptions = {
    el: videoRef.value,
    url: props.videoUrl,
    videoInit: true,
    poster: props.poster,
    playsinline: true,
    fluid: true,
    width: videoW ?? "600",
    height: videoH ?? "337.5",
    fitVideoSize: "auto",
    "x5-video-player-type": "h5",
    danmu: {
      closeDefaultBtn: true,
      comments: [],
    },
  };
  player.value = new Player(playerOptions);
  player.value.on("timeupdate", function (val) {
    //事件名称可以在上述查询
    if (val.currentTime > 0) {
      const { duration, currentTime } = val;
      emit("onTimeUpdate", {
        duration,
        currentTime,
      });
    }
  });
};

const onPause = () => {
  player.value.pause();
}

const onContinuePlay = () => {
  player.value.play();
}

onMounted(() => {
  loadImage(props.poster)
    .then((img: HTMLImageElement) => {
      const imgW = img.width;
      const imgH = img.height;
      if (imgW > imgH) {
        initVideo();
      } else {
        const winW = window.innerWidth;
        const imgHeight = Math.floor((winW * imgH) / imgW);
        initVideo(winW, imgHeight);
      }
      console.log(imgW, imgH);
    })
    .catch(() => {
      initVideo();
    });
});

defineExpose({
  onPause,
  onContinuePlay
})
</script>
