<script setup lang="ts">
import { Events } from 'xgplayer'
import { useLog, LogType, useAudio, XMessage, debounce } from '@/hooks'
import { userStore, globalStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { $XXL } from '@/utils'
import 'xgplayer/dist/index.min.css'

interface TVideo {
  id: any
  url?: string
  videoUrl?: string
  videoName?: string
  playDuration?: string | number
  videoDuration?: string | number
}

const props = defineProps<{
  video?: TVideo
  videoDomId?: string // video挂载dom id
  videoList?: TVideo[]
  data?: {
    subjectId: string | number
    resourceType: 0 | 1 | 2 | 3
    origin: 1 | 2
  }
  playIcon?: string // 播放icon
  resource?: 0 | 1 // 0-菁优网   1-九学王(不需要上报)
}>()

const emit = defineEmits(['onPause', 'onPlay', 'onEnded'])
// const OSS_URL = `${import.meta.env.VITE_OSS_URL}`;

const { getUserInfo } = userStore()
const { userInfo } = storeToRefs(userStore())

const { system } = toRefs(globalStore())

let player: any = null

// 正在播放的视频idx
let currentIdx = 0

watch(
  () => props.video?.id,
  () => {
    player && (player.src = props.video?.url || props.video?.videoUrl)
    initLog()
  },
)
watch(
  () => props.videoList,
  () => {
    player && (player.src = props.videoList?.[0]?.url || props.videoList?.[0]?.videoUrl)
    initLog()
  },
)
// watch(()=>currentIdx,()=>{
// player && (player.src = props.video?.url);
// })

// 从上次播放的时间继续播放
async function play() {
  await player.play()
  const { playDuration, videoDuration } = props.video ? props.video : props.videoList![0]
  if (Number(playDuration) + 10 < Number(videoDuration)) {
    player.seek(Number(playDuration))
  }
}

// 渲染上一集按钮
function renderPre() {
  if (props.videoList && props.videoList?.length > 1) {
    const el: any = document.querySelector('.xgplayer-playnext')?.cloneNode(true)
    if (el) {
      el.className = 'xgplayer-playpre'
      el.onclick = () => {
        if (currentIdx <= 0) return XMessage.info('没有更多了')
        player.pause()
        setTimeout(async () => {
          initLog()
          currentIdx--
          player.src = props.videoList![currentIdx].url || props.videoList![currentIdx].videoUrl
          await player.play()
          const { playDuration, videoDuration } = props.videoList![currentIdx]
          if (Number(playDuration) + 10 < Number(videoDuration)) {
            player.seek(Number(playDuration))
          }
        })
      }
    }
    document.querySelector('.xg-left-grid')?.appendChild(el)
  }
}

interface logType {
  isSeek: boolean
  startTime: number | '' // 开始时间
  startFrame: number // 开始帧
  endTime: number | '' // 结束时间
  endFrame: number // 结束帧
}

const log: logType = {
  isSeek: false,
  startTime: 0, // 开始时间
  startFrame: 0, // 开始帧
  endTime: 0, // 结束时间
  endFrame: 0, // 结束帧
}
const initLog = () => {
  log.isSeek = false
  log.startTime = 0
  log.startFrame = 0
  log.endTime = 0
  log.endFrame = 0
}
const logFun = debounce(async (data: anyObj, flag: boolean) => {
  if (props.resource) return
  if (log.startFrame >= log.endFrame) return
  const params = {
    ...log,
    resourceType: props.data?.resourceType,
    origin: props.data?.origin,
    subjectId: props.data?.subjectId,
    playDuration: data.currentTime,
    userId: userInfo.value.userId,
    videoId: '',
    videoName: '',
  }
  if (flag) {
    params.startTime = ''
    params.endTime = ''
  }
  if (props.video) {
    params.videoId = props.video.id
    params.videoName = props.video.videoName || ''
  } else if (props.videoList!.length === 1) {
    params.videoId = props.videoList![0].id
    params.videoName = props.videoList![0].videoName || ''
  } else if (props.videoList!.length > 1) {
    params.videoId = props.videoList![currentIdx].id
    params.videoName = props.videoList![currentIdx].videoName || ''
    // emit('onPause', currentIdx, item.currentTime);
  }
  await useLog(LogType.VideoPlayTime, params as any)
  // const { data: res } = await useLog(LogType.VideoPlayTime, params)
  // console.log('上报结果', res.data);
  // TODO 暂时把奖励的弹框去掉
  // if (res.data.diamond || res.data.experience) {
  //     const rewardList: anyObj[] = []

  //     res.data.diamond && rewardList.push({ rewardCode: 'diamond', count: res.data.diamond })
  //     res.data.experience &&
  //         rewardList.push({
  //             rewardCode: 'experience',
  //             count: res.data.experience
  //         })
  //     useReward({ rewardList })
  // }
}, 500)

onMounted(() => {
  if (!userInfo.value.userId) {
    getUserInfo()
  }
  player = useAudio({
    id: props.videoDomId ?? 'x-video',
    url: props.videoList?.length
      ? props.videoList?.[0]?.url || props.videoList?.[0]?.videoUrl
      : props.video?.url || props.video?.videoUrl,
    autoplay: false,
    lang: 'zh-cn', // 设置中文
    videoInit: true,
    rotateFullscreen: true,
    playNext: {
      urlList: Number(props.videoList?.length) > 1 ? [undefined] : [],
    },
  })
  renderPre()

  // 开始播放
  player.on('play', () => {
    emit('onPlay')
    log.startTime = new Date().getTime() // 记录开始播放的时间
  })

  // 下一集
  player.on(Events.PLAYNEXT, async (_currentIdx: number) => {
    if (currentIdx >= props.videoList!.length - 1) return XMessage.info('没有更多了')
    player.pause()
    setTimeout(async () => {
      initLog()
      currentIdx++
      player.src = props.videoList![currentIdx].url || props.videoList![currentIdx].videoUrl
      await player.play()
      const { playDuration, videoDuration } = props.videoList![currentIdx]
      if (Number(playDuration) + 10 < Number(videoDuration)) {
        player.seek(Number(playDuration))
      }
    })
  })

  // 暂停播放时埋点(自动结束播放也会触发暂停事件)
  player.on('pause', (item: anyObj) => {
    log.endTime = new Date().getTime() // 记录结束
    log.endFrame = item.currentTime

    if (props.videoList && props.videoList.length > 1) {
      emit('onPause', currentIdx, item.currentTime)
    }
    if (props.data) logFun(item)
  })

  // 自动连播
  player.on('ended', () => {
    emit('onEnded')
    if (props.videoList?.length && currentIdx < props.videoList!.length - 1) {
      player.emit(Events.PLAYNEXT)
    }
  })

  player.on(Events.PLAYING, (data: anyObj) => {
    log.startFrame = data.currentTime // 记录进度条拉动时播放帧
  })
  player.on(Events.SEEKING, (_data: anyObj) => {
    // console.log('开始拉动 seeking', data.currentTime);
    log.isSeek = true
  })
  player.on(Events.SEEKED, (data: anyObj) => {
    // console.log('拉动结束 seeked', data.currentTime);
    log.isSeek = false
    log.startFrame = data.currentTime
  })
  player.on(Events.TIME_UPDATE, (data: anyObj) => {
    // console.log('进度条变化 timeupdate', data.currentTime);
    if (log.isSeek) {
      if (props.data) logFun(data, true)
    } else {
      log.endFrame = data.currentTime
    }
  })

  // 全屏状态改变
  player.on(Events.FULLSCREEN_CHANGE, (fullScreen: boolean) => {
    system.value.fullPlay = fullScreen
  })
  // player.on(Events.CSS_FULLSCREEN_CHANGE, (fullScreen: boolean) => {
  //     system.value.fullPlay = fullScreen;
  // });
})

watch(
  () => system.value.fullPlay,
  nv => {
    if (!nv) {
      player.exitCssFullscreen?.()
      player.exitFullscreen?.()
    }
  },
)

// 屏幕常亮
onActivated(() => {
  $XXL.setScreenOn(1)
})

onUnmounted(() => {
  player?.pause?.()
})

onDeactivated(() => {
  player?.pause?.()
})

defineExpose({
  player: () => player,
  play,
})
</script>
<template>
  <div :id="props.videoDomId ?? 'x-video'" class="x-video"></div>
</template>
<style scoped lang="scss">
.x-video {
  width: 100% !important;
  height: 100% !important;
  :deep(.xgplayer-controls) {
    font-size: 2.33vh;
    z-index: 1;
    .xgplayer-time {
      font-size: 2.33vh !important;
    }
    .btn-text {
      background-color: transparent !important;
    }
    .icon-text {
      font-size: 2.33vh !important;
    }
  }
  :deep(.xg-options-list) {
    .option-item span {
      font-size: 2.33vh !important;
    }
  }
  :deep(.xg-left-grid) {
    padding-left: 48px;
    position: relative;
  }
  :deep(.xgplayer-icon) {
    svg {
      width: 48px;
      height: 4vh;
    }
  }

  :deep(.xgplayer-playpre) {
    position: absolute;
    left: 0;
    top: 0.17vh;
    margin-left: 0;
    .xgplayer-icon {
      svg {
        transform: rotate(180deg);
      }
    }
  }
  :deep(.xgplayer-playnext) {
    margin-left: 0;
    .xgplayer-icon {
      margin-left: 0;
    }
  }
  &.xgplayer-is-cssfullscreen {
    // width: 100vw !important;
    // height: 100% !important;
  }
}
</style>
