<script lang="ts" setup>
  import { isNumber } from 'lodash';
  import videoJs, { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js';
  import 'video.js/dist/video-js.css';
  import { computed, CSSProperties, onMounted, onUnmounted, ref, unref } from 'vue';
  import { useDesign } from '/@/hooks/web/useDesign';

  const { prefixCls } = useDesign('basic-video-play');

  const props = defineProps<{
    options?: VideoJsPlayerOptions;
  }>();

  const emit = defineEmits<{
    (event: 'ready', instance?: Nullable<VideoJsPlayer>): void;
  }>();

  const videoPlayEl = ref<HTMLVideoElement>();

  const videoPlayInstance = ref<Nullable<VideoJsPlayer>>();

  const getOptions = computed(() => {
    const { options } = props;
    const defaultOptions: VideoJsPlayerOptions = {
      language: 'zh',
      muted: true,
      liveui: true,
      controls: true,
    };
    return { ...defaultOptions, ...options };
  });

  const getWidthHeight = computed(() => {
    let { width = 300, height = 150 } = unref(getOptions);
    width = isNumber(width) ? (`${width}px` as unknown as number) : width;
    height = isNumber(height) ? (`${height}px` as unknown as number) : height;
    return { width, height } as CSSProperties;
  });

  const init = () => {
    videoPlayInstance.value = videoJs(unref(videoPlayEl)!, unref(getOptions), () => {
      emit('ready', unref(videoPlayInstance));
    });
  };

  onMounted(() => {
    init();
  });

  onUnmounted(() => {
    unref(videoPlayInstance)?.dispose();
    videoPlayInstance.value = null;
  });
</script>

<template>
  <div :class="prefixCls" class="w-full h-full" :style="getWidthHeight">
    <video
      ref="videoPlayEl"
      class="video-js vjs-big-play-centered vjs-show-big-play-button-on-pause !w-full !h-full"
    ></video>
  </div>
</template>

<style lang="less">
  @prefix-cls: ~'@{namespace}-basic-video-play';

  .@{prefix-cls} {
    .vjs-error-display {
      .vjs-modal-dialog-content::after {
        content: '无法加载视频,原因可能是服务器或网络故障,也可能是格式不支持.';
      }
    }
  }
</style>
