<template>
  <div class="aliyun-player-container">
    <!-- 播放器容器 -->
    <div ref="playerContainer" :id="playerDomId" class="player-container" :style="{ width: width, height: height }">
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>正在加载视频...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-overlay">
      <div class="error-icon">
        <svg t="1761113539808" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
          p-id="4776" width="200" height="200">
          <path
            d="M1018.146525 511.98465c0.005117 278.510808-226.653315 503.751921-506.765642 503.603538-279.697876-0.148384-505.875341-226.023964-505.522291-504.84689C6.206526 232.639824 233.417559 7.992245 513.903403 8.416929 792.09186 8.836496 1018.141408 234.579044 1018.146525 511.98465zM512.890301 69.525369c-244.188158-0.281417-445.600919 199.555409-445.703253 442.223914-0.102333 241.634937 200.281977 442.055064 442.648598 442.730465 244.592375 0.680518 446.414471-198.414391 446.982421-440.939629C957.380902 270.56973 756.658892 69.806786 512.890301 69.525369z"
            p-id="4777"></path>
          <path
            d="M769.491511 698.518123c-27.241173 24.841453-50.972308 46.484985-71.561805 65.258062-60.315355-81.416519-120.30836-162.398121-183.079718-247.135362-75.39931 80.541568-136.139349 161.528287-187.423775 251.719902-24.774936-20.44623-48.291171-39.853775-72.92284-60.182321 37.730355-42.309779 74.089442-83.759956 111.221146-124.498916 28.689192-31.477779 57.710968-62.709959 87.878879-92.760186 13.262419-13.211253 11.190166-21.633298-1.361035-33.109999C388.258352 399.295018 324.745076 340.269065 260.812232 281.186829c24.099535-30.817728 28.653375-33.544916 62.300625-9.30723 60.622355 43.675931 119.858092 89.362714 178.213761 136.031899 16.035657 12.822385 25.148454 13.681987 40.344976-0.271184 60.873073-55.899665 126.704202-105.101604 202.456563-143.640394 5.275291 9.12303 9.772848 16.895258 13.380103 23.137601-65.288762 58.033318-129.344406 114.976785-194.346635 172.759386C633.689862 541.46181 701.357877 619.716224 769.491511 698.518123z"
            p-id="4778"></path>
        </svg>
      </div>
      <h3>播放失败</h3>
      <p>{{ error }}</p>
      <button @click="retryPlay" class="retry-btn">重试</button>
    </div>

    <!-- 播放完成提示 -->
    <div v-if="playCompleted" class="completion-overlay">
      <div class="completion-icon"><svg t="1761113568154" class="icon" viewBox="0 0 1024 1024" version="1.1"
          xmlns="http://www.w3.org/2000/svg" p-id="5776" width="200" height="200">
          <path
            d="M774.469857 800.907155q8.947836-24.8551 30.820324-33.305834t42.25367-3.479714 32.31163 22.866692 1.988408 44.73918q-11.930448 32.808732-37.28265 71.582688t-71.582688 69.097178-115.824766 44.73918-168.020477-1.491306q-68.600076-11.930448-129.246521-28.831916t-108.368236-34.300038-79.53632-31.317426-41.756568-18.889876l-3.976816 3.976816-14.91306-384.75695q6.959428-70.588484 15.907264-138.194357 3.976816-28.831916 8.450734-59.155138t9.444938-60.149342 9.94204-57.16673 10.936244-49.213098q12.924652-53.687016 38.773956-74.5653t50.704404-18.392774 42.750772 22.866692 15.907264 49.213098q-1.988408 19.88408-6.959428 58.658036t-11.433346 84.50734-13.421754 92.958074-12.924652 83.016034q10.936244-29.82612 25.849304-68.600076t33.305834-81.524728 39.271058-85.998646 42.25367-81.524728 43.744976-67.605872 43.247874-44.242078q41.756568-27.837712 71.582688-26.346406t46.230486 17.895672 17.895672 40.762364-13.421754 42.25367q-16.901468 17.895672-37.28265 58.658036t-40.265262 82.518932q-22.866692 48.715996-45.733384 105.385624 35.791344-36.785548 73.571096-69.59428 31.814528-28.831916 70.588484-57.663832t74.5653-45.733384q34.79714-16.901468 65.120362-15.907264t47.22469 14.415958 15.410162 35.294242-30.323222 45.733384q-13.918856 11.930448-33.305834 28.831916t-41.259466 36.288446-45.236282 40.762364-45.236282 41.259466q-51.698608 47.721792-108.368236 98.426196 88.484156-22.866692 163.049457-21.872488 31.814528 0 63.629056 5.468122t58.658036 18.889876 46.727588 35.791344 27.837712 57.16673q9.94204 44.73918 1.491306 74.5653t-25.849304 41.756568-38.276854 2.982612-35.791344-42.750772q-13.918856-33.802936-27.34061-46.727588t-28.334814-13.918856-31.317426 5.468122-37.28265 11.433346q-13.918856 2.982612-31.317426 12.924652t-33.305834 24.357998-28.334814 31.317426-15.907264 34.300038 2.982612 32.808732 29.329018 26.346406q33.802936 16.901468 62.13775 28.334814t50.704404 14.415958 38.276854-3.976816 23.860896-27.837712z"
            p-id="5777"></path>
        </svg></div>
      <h3>播放完成</h3>
      <p>正在准备下一个视频...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { getPlayerConfig, getLicenseConfig } from '@/config/aliplayer.js'

// 动态加载阿里云播放器CSS（只加载一次）
if (!document.querySelector('link[href*="aliplayer"]')) {
  const link = document.createElement('link')
  link.rel = 'stylesheet'
  link.href = 'https://g.alicdn.com/de/prismplayer/2.15.2/skins/default/aliplayer-min.css'
  document.head.appendChild(link)
}

// Props
const props = defineProps({
  // 视频ID
  videoId: {
    type: String,
    required: true
  },
  // 课程ID（可选）
  courseId: {
    type: [String, Number],
    required: false
  },
  // 章节ID（可选）
  chapterId: {
    type: [String, Number],
    required: false
  },
  // 工作流ID（可选）
  workflowId: {
    type: [String, Number],
    required: false
  },
  // 播放器宽度
  width: {
    type: String,
    default: '100%'
  },
  // 播放器高度
  height: {
    type: String,
    default: '400px'
  },
  // 是否自动播放
  autoplay: {
    type: Boolean,
    default: false
  },
  // 是否显示控制条
  controls: {
    type: Boolean,
    default: true
  }
})

// Emits
const emit = defineEmits([
  'play',           // 开始播放
  'pause',          // 暂停播放
  'ended',          // 播放结束
  'error',          // 播放错误
  'timeupdate',     // 播放进度更新
  'ready',          // 播放器就绪
  'next-video'      // 请求播放下一个视频
])

// 响应式数据
const playerContainer = ref(null)
const loading = ref(false)
const error = ref('')
const playCompleted = ref(false)
const player = ref(null)
const currentTime = ref(0)
const duration = ref(0)

// 播放器DOM ID
const playerDomId = `aliplayer_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

// 播放器就绪回调
function onPlayerReady() {
  console.log('[AliyunPlayer] 播放器就绪')
  loading.value = false
  emit('ready', player.value)
}

// 开始播放回调
function onPlay() {
  console.log('[AliyunPlayer] 开始播放')
  emit('play', { videoId: props.videoId, currentTime: currentTime.value })
}

// 暂停播放回调
function onPause() {
  console.log('[AliyunPlayer] 暂停播放')
  emit('pause', { videoId: props.videoId, currentTime: currentTime.value })
}

// 播放结束回调
function onEnded() {
  console.log('[AliyunPlayer] 播放结束')
  playCompleted.value = true
  emit('ended', { videoId: props.videoId })

  // 延迟后请求播放下一个视频
  setTimeout(() => {
    emit('next-video', { videoId: props.videoId })
    playCompleted.value = false
  }, 2000)
}

// 播放错误回调
function onError(errorData) {
  console.error('[AliyunPlayer] 播放错误:', errorData)
  error.value = errorData.message || '播放失败，请重试'
  loading.value = false
  emit('error', errorData)
}

// 播放进度更新回调
function onTimeUpdate(timeData) {
  currentTime.value = timeData.currentTime
  duration.value = timeData.duration
  emit('timeupdate', {
    videoId: props.videoId,
    currentTime: timeData.currentTime,
    duration: timeData.duration
  })
}

// 初始化播放器 - 参考CourseDetailModal的实现
async function initPlayer() {
  console.log('[AliyunPlayer] 开始初始化播放器')
  try {
    loading.value = true
    error.value = ''

    // 动态加载阿里云播放器SDK
    if (typeof window.Aliplayer === 'undefined') {
      await loadAliplayerSDK()
    }

    // 使用 nextTick 确保容器已挂载
    await nextTick()

    // 检查DOM容器是否存在
    const container = document.getElementById(playerDomId)
    if (!container) {
      console.error('[AliyunPlayer] Player container not found:', playerDomId)
      throw new Error('播放器容器未找到，请稍后重试')
    }

    // 销毁之前的播放器实例
    disposePlayer()

    console.log('[AliyunPlayer] 播放器容器就绪，等待播放凭证...')
    loading.value = false

  } catch (err) {
    console.error('[AliyunPlayer] 初始化播放器失败:', err)
    error.value = err.message || '播放器初始化失败，请刷新页面重试'
    loading.value = false
  }
}

// 加载阿里云播放器SDK
function loadAliplayerSDK() {
  return new Promise((resolve, reject) => {
    // 检查是否已经加载
    if (window.Aliplayer) {
      resolve()
      return
    }

    // 如果已经有 script 标签，等待加载完成
    const existingScript = document.querySelector('script[src*="aliplayer"]')
    if (existingScript) {
      if (existingScript.dataset.loaded) {
        resolve()
      } else {
        existingScript.addEventListener('load', resolve)
        existingScript.addEventListener('error', reject)
      }
      return
    }

    const script = document.createElement('script')
    script.src = 'https://g.alicdn.com/de/prismplayer/2.15.2/aliplayer-min.js'
    script.onload = () => {
      script.dataset.loaded = 'true'
      resolve()
    }
    script.onerror = reject
    document.head.appendChild(script)
  })
}

// 播放视频 - 参考CourseDetailModal的实现
async function playVideo(playAuth, videoMeta = {}) {
  try {
    console.log('[AliyunPlayer] 开始播放视频:', { playAuth: !!playAuth, videoMeta })

    if (!playAuth) {
      throw new Error('播放凭证缺失')
    }

    const videoId = videoMeta.videoId || props.videoId
    if (!videoId) {
      throw new Error('视频ID缺失')
    }

    loading.value = true
    error.value = ''

    // 销毁现有播放器
    disposePlayer()

    // 等待DOM更新
    await nextTick()

    // 检查容器
    const container = document.getElementById(playerDomId)
    if (!container) {
      throw new Error('播放器容器未找到')
    }

    // 创建播放器配置 - 使用CourseDetailModal的方式
    const baseConfig = getPlayerConfig({
      id: playerDomId,
      vid: videoId,
      playauth: playAuth,
      width: props.width,
      height: props.height,
      autoplay: props.autoplay,
      controls: props.controls,
      format: "mp4",
      defaultDefinition: "defaultDefinition"
    })

    const license = getLicenseConfig()

    // 创建播放器实例
    player.value = new window.Aliplayer(
      { ...baseConfig, license },
      () => {
        console.log('[AliyunPlayer] 播放器创建成功')
        loading.value = false
        emit('ready', player.value)
      }
    )

    // 设置播放器事件监听
    if (player.value) {
      player.value.on('play', onPlay)
      player.value.on('pause', onPause)
      player.value.on('ended', onEnded)
      player.value.on('error', onError)
      player.value.on('timeupdate', onTimeUpdate)
    }

  } catch (err) {
    console.error('[AliyunPlayer] 播放视频失败:', err)
    error.value = err.message || '播放失败，请重试'
    loading.value = false
  }
}

// 重试播放
function retryPlay() {
  error.value = ''
  initPlayer()
}

// 暂停播放
function pause() {
  if (player.value && typeof player.value.pause === 'function') {
    player.value.pause()
  }
}

// 继续播放
function resume() {
  if (player.value && typeof player.value.play === 'function') {
    player.value.play()
  }
}

// 跳转到指定时间
function seekTo(time) {
  if (player.value && typeof player.value.seek === 'function') {
    player.value.seek(time)
  }
}

// 设置播放速度
function setPlaybackRate(rate) {
  if (player.value && typeof player.value.setPlaybackRate === 'function') {
    player.value.setPlaybackRate(rate)
  }
}

// 全屏播放
function requestFullscreen() {
  if (player.value && typeof player.value.requestFullscreen === 'function') {
    player.value.requestFullscreen()
  }
}

// 销毁播放器
function disposePlayer() {
  try {
    if (player.value && typeof player.value.dispose === 'function') {
      player.value.dispose()
      console.log('[AliyunPlayer] Player disposed.')
    }
  } catch (e) {
    console.warn('[AliyunPlayer] Error disposing player:', e)
  }
  player.value = null
}

// 兼容旧的destroy方法名
function destroy() {
  disposePlayer()
}

// 监听视频ID变化，重新初始化播放器
watch(() => props.videoId, (newVideoId, oldVideoId) => {
  if (newVideoId && newVideoId !== oldVideoId) {
    console.log('[AliyunPlayer] 视频ID变化，重新初始化播放器:', newVideoId)
    destroy()
    nextTick(() => {
      initPlayer()
    })
  }
})

// 组件挂载时初始化播放器
onMounted(() => {
  initPlayer()
})

// 组件卸载时销毁播放器
onUnmounted(() => {
  disposePlayer()
})

// 暴露方法给父组件
defineExpose({
  playVideo,
  pause,
  resume,
  seekTo,
  setPlaybackRate,
  requestFullscreen,
  destroy,
  currentTime,
  duration
})
</script>

<style scoped>
.aliyun-player-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.player-container {
  width: 100%;
  height: 100%;
  background: #000;
}

.loading-overlay,
.error-overlay,
.completion-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.error-icon,
.completion-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-overlay h3,
.completion-overlay h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
}

.error-overlay p,
.completion-overlay p {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
}

.retry-btn {
  padding: 8px 16px;
  background: #3b82f6;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.retry-btn:hover {
  background: #2563eb;
}

/* 响应式设计 */
@media (max-width: 768px) {

  .error-overlay h3,
  .completion-overlay h3 {
    font-size: 16px;
  }

  .error-overlay p,
  .completion-overlay p {
    font-size: 12px;
  }

  .retry-btn {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style>