<template>
  <div ref="easyPlayerRef" style="width: 1000px; height: 630px; background-color: #000000"></div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { ptzdirection, ptzscale } from '@/api/pms/video/sipdevice'

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

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

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

// 动态加载 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 play = async (url) => {
  console.log('EasyPlayer 播放视频 url: ', url)
  videoUrl.value = url
  await onDestroy()
  playCreate()
  onPlayer()
}

const pause = () => {
  onPause()
}

const destroy = () => {
  onDestroy()
}

const registercallback = (events, func) => {}

const onUse = (type) => {
  if (type === 'hasAudio') {
    config.hasAudio = !config.hasAudio
  } else {
    config.MSE = false
    config.WCS = false
    if (type === 'MSE') config.MSE = true
    if (type === 'WCS') config.WCS = true
  }
  if (isPlay.value) {
    onDestroy().then(() => {
      playCreate()
      onPlayer()
    })
  }
}

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

const onPause = () => {
  if (playInfo.value) {
    playInfo.value.pause()
  }
}

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

const onPlayer = () => {
  isPlay.value = true
  nextTick(() => {
    if (playInfo.value) {
      playInfo.value
        .play(videoUrl.value)
        .then(() => {})
        .catch((e) => {
          console.error(e)
        })
    }
  })
}

const onPlayerPlayback = () => {
  onDestroy().then(() => {
    playCreate()
    config.isLive = false
    nextTick(() => {
      if (playInfo.value) {
        playInfo.value
          .play(videoUrl.value)
          .then(() => {})
          .catch((e) => {
            console.error(e)
          })
      }
    })
  })
}

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

const onDestroy = () => {
  return new Promise((resolve) => {
    if (playInfo.value) {
      playInfo.value.destroy()
      playInfo.value = null
    }
    setTimeout(() => {
      resolve()
    }, 100)
  })
}

const onReplay = async () => {
  await onDestroy()
  playCreate()
  onPlayer()
}

// 处理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))
    })
  }
}

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

  const easyplayer = 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
    }
  })

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

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

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

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

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

  playInfo.value.playtype = playtype.value
}
watch(
  () => props.playerInfo,
  (newVal, oldVal) => {
    playInfo.value = newVal
    playInfo2.value = newVal
    if (newVal && newVal.playtype !== '') {
      playtype.value = newVal.playtype
    }
  }
)
// 生命周期钩子
onMounted(() => {
  playInfo.value = props.playerInfo
  playInfo2.value = props.playerInfo
  if (playInfo.value && playInfo.value.playtype !== '') {
    playtype.value = playInfo.value.playtype
  }
  playCreate()
})

onBeforeUnmount(() => {
  onDestroy()
})

defineExpose({
  play,
  pause,
  destroy,
  registercallback,
  onUse,
  setFullscreen,
  onPause,
  onMute,
  onPlayer,
  onPlayerPlayback,
  onStop,
  onReplay
})
</script>

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

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