<template>
  <div ref="container" @dblclick="fullscreenSwitch"
       style="width:100%;height:100%;background-color: #000000;margin:0 auto;">
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'

// 使用组合式API
const route = useRoute()

// 定义 props
const props = defineProps({
  videoUrl: {
    type: String,
    default: undefined
  },
  error: {
    type: [String, Function],
    default: undefined
  },
  hasAudio: {
    type: Boolean,
    default: undefined
  },
  height: {
    type: [String, Number],
    default: undefined
  }
})

// 定义 emits
const emit = defineEmits(['screenshot', 'destroy'])

// refs
const container = ref(null)

// 数据状态
const playing = ref(false)
const isNotMute = ref(false)
const quieting = ref(false)
const fullscreen = ref(false)
const loaded = ref(false)
const speed = ref(0)
const performance = ref("")
const kBps = ref(0)
const btnDom = ref(null)
const videoInfo = ref(null)
const volume = ref(1)
const rotate = ref(0)
const vod = ref(true)
const forceNoOffscreen = ref(false)

// jessibuca player 实例
let jessibucaPlayer = {}

// 生命周期钩子
onMounted(() => {
  window.onerror = (msg) => {
    // console.error(msg)
  }
  
  // 确保DOM已经渲染完毕后再初始化播放器
  nextTick(() => {
    updatePlayerDomSize()
    window.onresize = () => {
      updatePlayerDomSize()
    }
    
    let paramUrl = decodeURIComponent(route.params.url)
    let url = props.videoUrl !== undefined ? props.videoUrl : paramUrl
    console.log("初始化时的地址为: " + url)
    
    // 确保容器已准备就绪
    if (container.value) {
      play(url)
    } else {
      console.error("Container element is not available")
    }
  })
})

onUnmounted(() => {
  if (jessibucaPlayer[route.params._uid]) {
    jessibucaPlayer[route.params._uid].destroy()
  }
  playing.value = false
  loaded.value = false
  performance.value = ""
})

// 监听 videoUrl 变化
watch(
  () => props.videoUrl,
  (newData, oldData) => {
    if (container.value) {
      play(newData)
    }
  },
  { immediate: true }
)

// 更新播放器DOM尺寸
const updatePlayerDomSize = () => {
  if (!container.value) return
  
  let dom = container.value
  let width = dom.parentNode.clientWidth
  let height = (9 / 16) * width
  const clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
  
  if (height > clientHeight) {
    height = clientHeight
    width = (16 / 9) * height
  }
  
  dom.style.width = width + 'px'
  dom.style.height = height + "px"
}

// 创建播放器实例
function create() {
  // 确保容器存在
  if (!container.value) {
    console.error("Cannot create player: container is not ready")
    return
  }
  
  let options = {}
  const uid = route.params._uid || Date.now() // 使用时间戳作为唯一标识
  
  jessibucaPlayer[uid] = new window.JessibucaPro(Object.assign(
    {
      container: container.value, // 确保传递正确的容器元素
      autoWasm: true,
      background: "",
      controlAutoHide: false,
      debug: false,
      debugLevel: "debug",
      decoder: "/js/jessibuca-pro/decoder-pro.js",
      forceNoOffscreen: true,
      hasAudio: props.hasAudio !== undefined ? props.hasAudio : true,
      hasVideo: true,
      heartTimeout: 5,
      heartTimeoutReplay: true,
      heartTimeoutReplayTimes: 3,
      hiddenAutoPause: false,
      hotKey: false,
      isFlv: false,
      isFullResize: false,
      isNotMute: isNotMute.value,
      isResize: false,
      keepScreenOn: false,
      loadingText: "请稍等, 视频加载中......",
      loadingTimeout: 10,
      loadingTimeoutReplay: true,
      loadingTimeoutReplayTimes: 3,
      openWebglAlignment: false,
      operateBtns: {
        fullscreen: true,
        zoom: true,
        ptz: false,
        play: true
      },
      recordType: "webm",
      rotate: 0,
      showBandwidth: false,
      supportDblclickFullscreen: false,
      timeout: 10,
      useMSE: location.hostname !== "localhost" && location.protocol !== "https:",
      useOffscreen: false,
      useWCS: location.hostname === "localhost" || location.protocol === "https",
      useWebFullScreen: false,
      videoBuffer: 0,
      wasmDecodeAudioSyncVideo: true,
      wasmDecodeErrorReplay: true,
      wcsUseVideoRender: true
    },
    options
  ))
  
  let jessibuca = jessibucaPlayer[uid]
  
  jessibuca.on("load", function () {
    console.log("on load init")
  })

  jessibuca.on("log", function (msg) {
    console.log("on log", msg)
  })
  
  jessibuca.on("record", function (msg) {
    console.log("on record:", msg)
  })
  
  jessibuca.on("pause", function () {
    playing.value = false
    loaded.value = true
  })
  
  jessibuca.on("play", function () {
    playing.value = true
    loaded.value = true
  })
  
  jessibuca.on("fullscreen", function (msg) {
    console.log("on fullscreen", msg)
    fullscreen.value = msg
  })

  jessibuca.on("mute", function (msg) {
    console.log("on mute", msg)
    isNotMute.value = !msg
  })
  
  jessibuca.on("audioInfo", function (msg) {
    console.log("audioInfo", msg)
  })
  
  let _ts = 0
  jessibuca.on("timeUpdate", function (ts) {
    // console.log('timeUpdate,old,new,timestamp', _ts, ts, ts - _ts)
    _ts = ts
  })
  
  jessibuca.on("performance", function (perf) {
    let show = "卡顿"
    if (perf === 2) {
      show = "非常流畅"
    } else if (perf === 1) {
      show = "流畅"
    }
    performance.value = show
  })
  
  jessibuca.on('kBps', function (kbps) {
    kBps.value = Math.round(kbps)
  })
}

// 播放视频
function play(url){
  const uid = route.params._uid || Date.now()
  
  // 确保容器已准备就绪
  if (!container.value) {
    console.error("Cannot play: container is not ready")
    return
  }
  
  if (jessibucaPlayer[uid]) {
    destroy().then(() => {
      if (jessibucaPlayer[uid] && jessibucaPlayer[uid].hasLoaded()) {
        jessibucaPlayer[uid].play(url)
      } else {
        jessibucaPlayer[uid].on("load", () => {
          console.log("load 播放")
          jessibucaPlayer[uid].play(url)
        })
      }
    })
  } else {
    create()
    if (jessibucaPlayer[uid] && jessibucaPlayer[uid].hasLoaded()) {
      jessibucaPlayer[uid].play(url)
    } else {
      jessibucaPlayer[uid].on("load", () => {
        console.log("load 播放")
        jessibucaPlayer[uid].play(url)
      })
    }
  }
}

// 暂停播放
const pause = () => {
  const uid = route.params._uid || Date.now()
  
  if (jessibucaPlayer[uid]) {
    jessibucaPlayer[uid].pause()
  }
  playing.value = false
  // err.value = ""
  performance.value = ""
}

// 截图
const screenshot = () => {
  const uid = route.params._uid || Date.now()
  
  if (jessibucaPlayer[uid]) {
    jessibucaPlayer[uid].screenshot()
    emit('screenshot', jessibucaPlayer[uid].screenshot())
  }
}

// 静音
const mute = () => {
  const uid = route.params._uid || Date.now()
  
  if (jessibucaPlayer[uid]) {
    jessibucaPlayer[uid].mute()
  }
}

// 取消静音
const cancelMute = () => {
  const uid = route.params._uid || Date.now()
  
  if (jessibucaPlayer[uid]) {
    jessibucaPlayer[uid].cancelMute()
  }
}

// 销毁播放器
const destroy = async () => {
  const uid = route.params._uid || Date.now()
  
  if (jessibucaPlayer[uid]) {
    await jessibucaPlayer[uid].destroy().then(() => {
      jessibucaPlayer[uid] = null
      playing.value = false
      create()
    })
    emit('destroy', uid)
  }
}

// 全屏切换
const fullscreenSwitch = () => {
  const uid = route.params._uid || Date.now()
  let isFull = isFullscreen()
  jessibucaPlayer[uid].setFullscreen(!isFull)
  fullscreen.value = !isFull
}

// 检查是否全屏
const isFullscreen = () => {
  return document.fullscreenElement ||
    document.msFullscreenElement ||
    document.mozFullScreenElement ||
    document.webkitFullscreenElement || false
}

// 暴露方法给父组件
defineExpose({
  updatePlayerDomSize,
  play,
  pause,
  screenshot,
  mute,
  cancelMute,
  destroy,
  fullscreenSwitch,
  isFullscreen
})
</script>

<style scoped>
@import './css/iconfont.css';

.buttons-box {
  width: 100%;
  height: 28px;
  background-color: rgba(43, 51, 63, 0.7);
  position: absolute;
  display: flex;
  left: 0;
  bottom: 0;
  user-select: none;
  z-index: 10;
}

.jessibuca-btn {
  width: 20px;
  color: rgb(255, 255, 255);
  line-height: 27px;
  margin: 0px 10px;
  padding: 0px 2px;
  cursor: pointer;
  text-align: center;
  font-size: 0.8rem !important;
}

.buttons-box-right {
  position: absolute;
  right: 0;
}
</style>