<script lang="ts" setup>
import FlvJs from 'flv.js'
import { nanoid } from 'nanoid'
import Toast from '@/components/toast'

const show = ref(false)
const fullscreen = ref(false)
// 0-->未初始化、1-->播放中、2-->暂停
const status = ref(0)
const video = ref<HTMLVideoElement | null>(null)
const containerElement = ref<HTMLElement | null>(null)
let videoUrl: string = ''
const header = ref<string>('视频监控')
// http://localhost:8888/live?port=1935&app=live&stream=stream1
// ffmpeg -re -i "C:\Users\24955\Downloads\1.mp4" -c:v libx264 -c:a aac -f flv rtmp://localhost:1935/live/stream1
const id = nanoid()
let flvPlayer: FlvJs.Player | null = null

/* const logListener = (type: any, str: any) => {
 console.log(type, str)
 } */

function toggleScreen() {
  if (fullscreen.value) {
    fullscreen.value = false
    document.exitFullscreen()
  } else {
    fullscreen.value = true
    containerElement.value!.requestFullscreen()
  }
}

function flvErrorHandler(type: string, message: string) {
  switch (type) {
    case FlvJs.ErrorTypes.NETWORK_ERROR:
      console.log(message)
      Toast.error('网络异常，播放失败')
      break
    case FlvJs.ErrorTypes.MEDIA_ERROR:
      console.log(message)
      // Toast.error('视频格式错误，播放失败')
      break
    default:
      console.log(message)
      Toast.error('视频播放失败')
  }
}

function createPlayer() {
  if (FlvJs.isSupported()) {
    flvPlayer = FlvJs.createPlayer({
      type: 'flv',
      hasAudio: false,
      hasVideo: true,
      isLive: true,
      url: 'https://admin.njzscloud.com/proxy/sms/local/live/P2zUwoEQF541F_01.flv?expired=20570510211616'
    }, {
      enableStashBuffer: true,
      isLive: true,
    })

    flvPlayer.on(FlvJs.Events.ERROR, flvErrorHandler)
    flvPlayer.attachMediaElement(video.value!)

    flvPlayer?.load()
    play()
  } else {
    Toast.error('当前浏览器不支持视频播放')
  }
}

function play() {
  flvPlayer?.play()
  status.value = 1
}

function destroy() {
  // FlvJs.LoggingControl.removeLogListener(logListener)
  flvPlayer?.off(FlvJs.Events.ERROR, flvErrorHandler)
  flvPlayer?.pause()
  flvPlayer?.unload()
  flvPlayer?.detachMediaElement()
  flvPlayer?.destroy()
  flvPlayer = null
  status.value = 0
}

function reload() {
  destroy()
  createPlayer()
  play()
}

function pauseOrPlay() {
  if (status.value === 1) {
    flvPlayer?.pause()
    status.value = 2
  } else {
    play()
  }
}

function closeHandler() {
  destroy()
  containerElement.value!.style!.width = '0'
  containerElement.value!.style!.height = '0'
  videoUrl = ''
  if (fullscreen.value) toggleScreen()
  show.value = false
}

function handleFullscreenChange() {
  fullscreen.value = document.fullscreenElement === containerElement.value
}

onMounted(() => {
  document.addEventListener('fullscreenchange', handleFullscreenChange)
})

onBeforeUnmount(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
})


defineExpose({
  open(url: string, title?: string) {
    status.value = 0
    videoUrl = url
    header.value = title ?? '视频监控'
    show.value = true
    containerElement.value!.style!.width = '100%'
    containerElement.value!.style!.height = '100%'
  }
})

</script>

<template>
  <div :id="id" ref="containerElement" class="ix_modal-container">
    <IxModal v-model:visible="show" :container="containerElement!"
        :header="header" :mask="false"
        :on-after-open="createPlayer"
        :on-before-close="closeHandler"
        type="default" width="100%">
      <video ref="video" class="video-element" controls></video>

      <template #footer>
        <IxTooltip placement="top" title="刷新">
          <IxButton icon="sync" @click="reload"/>
        </IxTooltip>
        <IxTooltip :title="status === 1?'暂停':'播放'" placement="top">
          <IxButton :icon="status === 1?'pause':'play'" mode="primary" @click="pauseOrPlay"/>
        </IxTooltip>
        <IxTooltip :title="fullscreen?'退出全屏':'全屏'" placement="top">
          <IxButton :icon="fullscreen?'fullscreen-exit':'fullscreen'" @click="toggleScreen"/>
        </IxTooltip>
      </template>
    </IxModal>
  </div>
</template>

<style lang="stylus" scoped>
.ix_modal-container {
  position absolute
  top 0
  left 0

  :deep(.ix-modal) {
    width 100%
    height 100%

    .ix-modal-body {
      width 100%
      overflow hidden
      border-top: 1px dashed #E1E5EB;
      border-bottom: 1px dashed #E1E5EB;

      .video-element {
        width 100%
        height 100%
      }
    }

    .ix-modal-footer {
      justify-content center
    }
  }
}

/* 隐藏全屏按钮 */
video::-webkit-media-controls-fullscreen-button {
  display: none;
}

/* 隐藏播放按钮 */
video::-webkit-media-controls-play-button {
  display: none;
}

/* 隐藏进度条 */
video::-webkit-media-controls-timeline {
  display: none;
}

/* 隐藏当前时间显示 */
video::-webkit-media-controls-current-time-display {
  display: none;
}

/* 隐藏剩余时间显示 */
video::-webkit-media-controls-time-remaining-display {
  display: none;
}

/* 隐藏音量按钮 */
video::-webkit-media-controls-mute-button {
  display: none;
}

/* 隐藏音量控制条 */
video::-webkit-media-controls-volume-slider {
  display: none;
}

/* 隐藏所有控件 */
video::-webkit-media-controls-enclosure {
  display: none;
}
</style>
