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

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { ptzdirection, ptzscale } from '@/api/pms/video/sipdevice'
import { useRoute } from 'vue-router'
const route = useRoute()

// 响应式数据
const easyPlayerRef = ref(null)
const playInfo = ref({})
const playInfo2 = ref({})
const playtype = ref('play')
const props = defineProps({
  videourl: {
    type: String,
    default: ''
  },
  playerInfo: {
    type: Object,
    default: null
  },
  width: {
    type: String,
    default: '1000px'
  },
  height: {
    type: String,
    default: '630px'
  },
  uid: {
    type: String,
    default: ''
  }
})
const playing = ref(false)

let videoUrl = ref('')
const isPlay = ref(false)

let easyplayer = {}

const emit = defineEmits(['screenshot', 'destroy'])

const config = reactive({
  hasAudio: true,
  isLive: true,
  MSE: false,
  WCS: true
})

// 动态加载 EasyPlayer
function loadEasyPlayer() {
  return new Promise((resolve, reject) => {
    if (window.EasyPlayerPro) {
      resolve(window.EasyPlayerPro)
      return
    }

    const script = document.createElement('script')
    script.src = '/js/EasyPlayer/EasyPlayer-pro.js'
    script.onload = () => resolve(window.EasyPlayerPro)
    script.onerror = reject
    document.head.appendChild(script)
  })
}

const playCreate = async () => {
  const container = easyPlayerRef.value
  if (!container) return

  const uid = props.uid || route.params._uid || Date.now() // 使用时间戳作为唯一标识

  easyplayer[uid] = new EasyPlayerPro(container, {
    isLive: config.isLive,
    bufferTime: 0.2,
    stretch: false,
    MSE: config.MSE,
    WCS: config.WCS,
    hasAudio: config.hasAudio,
    watermark: { text: { content: '' }, right: 10, top: 10 },
    isBand: true,
    btns: {
      play: true,
      audio: true,
      record: true,
      zoom: true,
      ptz: true,
      quality: true,
      stretch: false,
      screenshot: true,
      fullscreen: true
    }
  })

  let easyplay = easyplayer[uid]

  easyplay.on('fullscreen', function (flag) {
    console.log('is fullscreen', flag)
  })

  easyplay.on('ptz', (direction) => {
    handlePtz(direction)
  })

  easyplay.on('playbackRate', (rate) => {
    easyplay.setRate(rate)
  })

  easyplay.on('playbackSeek', (data) => {
    console.log('playbackSeek', data)
  })

  playInfo.value = easyplayer
  if (playInfo2.value && playInfo2.value.id && playInfo2.value.deviceId) {
    playInfo.value.channelId = playInfo2.value.id
    playInfo.value.deviceId = playInfo2.value.deviceId
  }

  playInfo.value.playtype = playtype.value
}

// 播放视频
async function play(url) {
  await loadEasyPlayer()
  const uid = props.uid || route.params._uid || Date.now() // 使用时间戳作为唯一标识

  // 确保容器已准备就绪
  if (!easyPlayerRef.value) {
    console.error('Cannot play: container is not ready')
    return
  }

  if (easyplayer[uid]) {
    destroy().then(() => {
      if (easyplayer[uid]) {
        easyplayer[uid].play(url)
      } else {
        easyplayer[uid].on('load', () => {
          console.log('load 播放')
          easyplayer[uid].play(url)
        })
      }
    })
  } else {
    playCreate()

    if (easyplayer[uid]) {
      easyplayer[uid].play(url)
    } else {
      easyplayer[uid].on('load', () => {
        console.log('load 播放')
        easyplayer[uid].play(url)
      })
    }
  }
}

const pause = () => {
  const uid = props.uid || route.params._uid || Date.now() // 使用时间戳作为唯一标识

  if (easyplayer[uid]) {
    easyplayer[uid].pause()
  }
  playing.value = false
}

// 截图
const screenshot = () => {
  const uid = props.uid || route.params._uid || Date.now() // 使用时间戳作为唯一标识

  if (easyplayer[uid]) {
    easyplayer[uid].screenshot()
    emit('screenshot', easyplayer[uid].screenshot())
  }
}

const destroy = async () => {
  const uid = props.uid || route.params._uid || Date.now() // 使用时间戳作为唯一标识

  if (easyplayer[uid]) {
    await easyplayer[uid].destroy().then(() => {
      easyplayer[uid] = null
      playing.value = false
      playCreate()
    })
    emit('destroy', uid)
  }
}

const setFullscreen = () => {
  if (playInfo.value) {
    playInfo.value.setFullscreen(true)
  }
}

const onMute = () => {
  // if (playInfo.value) {
  //   playInfo.value.setMute(true)
  // }

  const uid = props.uid || route.params._uid || Date.now() // 使用时间戳作为唯一标识

  if (easyplayer[uid]) {
    easyplayer[uid].setMute(true)
  }
}

const onStop = async () => {
  isPlay.value = false
  await onDestroy()
  playCreate()
}

// 处理PTZ控制
const handlePtz = (arrow) => {
  let leftRight = 0
  let upDown = 0
  if (arrow === 'left') {
    leftRight = 2
  } else if (arrow === 'right') {
    leftRight = 1
  } else if (arrow === 'up') {
    upDown = 1
  } else if (arrow === 'down') {
    upDown = 2
  }

  const data = {
    leftRight: leftRight,
    upDown: upDown,
    moveSpeed: 125
  }

  if (playInfo.value && playInfo.value.playtype !== '') {
    ptzdirection(playInfo.value.deviceId, playInfo.value.channelId, data).then(async (response) => {
      //console.log("云台方向控制：" + JSON.stringify(response))
    })
  }
}

watch(
  () => props.videourl,
  (newData, oldData) => {
    if (easyPlayerRef.value) {
      play(newData)
    }
  },
  { immediate: true }
)

// 更新播放器DOM尺寸
const updatePlayerDomSize = () => {
  if (!easyPlayerRef.value) return

  let dom = easyPlayerRef.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'
}
// 生命周期钩子
onMounted(() => {
  console.log('####################', props.playerInfo)
  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 (easyPlayerRef.value) {
      play(url)
    } else {
      console.error('Container element is not available')
    }
  })
  playInfo.value = props.playerInfo
  playInfo2.value = props.playerInfo
  videoUrl.value = props.videourl

  if (playInfo.value && playInfo.value.playtype !== '') {
    playtype.value = playInfo.value.playtype
  }
})

onUnmounted(() => {
  if (easyplayer[props.uid || route.params._uid || Date.now()]) {
    easyplayer[props.uid || route.params._uid || Date.now()].destroy()
  }
  playing.value = false
})

defineExpose({
  play,
  pause,
  destroy,
  setFullscreen,
  onMute,
  onStop,
  updatePlayerDomSize
})
</script>

<style>
.LoadingTitle {
  min-width: 70px;
}

/* 隐藏logo */
.iconqingxiLOGO {
  display: none !important;
}
</style>
