<template>
  <div class="broadcast-wrapper">
    <div class="broadcast-header">
      <el-button @click="goBack" circle>
        <el-icon><Back /></el-icon>
      </el-button>
      <h2 class="course-title">{{ courseName }}</h2>
      <div class="header-spacer"></div>
    </div>

    <div class="player-container">
      <div class="player-card">
        <div class="player-icon">
          <el-icon :size="80">
            <Microphone />
          </el-icon>
        </div>

        <div class="player-info">
          <h3>播课音频</h3>
          <p class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</p>
        </div>

        <!-- HTML5 Audio 元素 -->
        <audio
          ref="audioPlayer"
          :src="mp3Url"
          @timeupdate="onTimeUpdate"
          @loadedmetadata="onLoadedMetadata"
          @ended="onEnded"
          @error="onError"
        />

        <!-- 进度条 -->
        <div class="progress-container">
          <el-slider
            v-model="sliderValue"
            :max="100"
            :show-tooltip="false"
            @change="seekTo"
          />
        </div>

        <!-- 播放控制栏 -->
        <div class="controls">
          <el-button circle @click="togglePlay" :disabled="!audioReady">
            <el-icon :size="32">
              <VideoPause v-if="isPlaying" />
              <VideoPlay v-else />
            </el-icon>
          </el-button>

          <div class="speed-control">
            <span class="speed-label">播放速度</span>
            <el-button-group>
              <el-button
                v-for="speed in speedOptions"
                :key="speed"
                :type="playbackRate === speed ? 'primary' : ''"
                size="small"
                @click="setSpeed(speed)"
              >
                {{ speed }}x
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Back, Microphone, VideoPlay, VideoPause } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 从路由参数获取数据
const courseName = computed(() => route.query.courseName as string || '播课')
const mp3Url = computed(() => route.query.mp3Url as string)

// 音频播放器引用
const audioPlayer = ref<HTMLAudioElement>()

// 播放状态
const isPlaying = ref(false)
const audioReady = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const playbackRate = ref(1.0)
const sliderValue = ref(0)

// 播放速度选项
const speedOptions = [1.0, 1.25, 1.5, 2.0]

/**
 * 返回
 */
const goBack = () => {
  router.back()
}

/**
 * 切换播放/暂停
 */
const togglePlay = async () => {
  if (!audioPlayer.value) return

  try {
    if (isPlaying.value) {
      audioPlayer.value.pause()
      isPlaying.value = false
    } else {
      await audioPlayer.value.play()
      isPlaying.value = true
    }
  } catch (error) {
    console.error('播放控制失败:', error)
    ElMessage.error('播放失败')
  }
}

/**
 * 设置播放速度
 */
const setSpeed = (speed: number) => {
  if (!audioPlayer.value) return

  audioPlayer.value.playbackRate = speed
  playbackRate.value = speed
}

/**
 * 跳转到指定位置
 */
const seekTo = (value: number) => {
  if (!audioPlayer.value || !duration.value) return

  const newTime = (value / 100) * duration.value
  audioPlayer.value.currentTime = newTime
}

/**
 * 音频时间更新
 */
const onTimeUpdate = () => {
  if (!audioPlayer.value) return

  currentTime.value = audioPlayer.value.currentTime
  
  if (duration.value > 0) {
    sliderValue.value = (currentTime.value / duration.value) * 100
  }
}

/**
 * 音频元数据加载完成
 */
const onLoadedMetadata = () => {
  if (!audioPlayer.value) return

  duration.value = audioPlayer.value.duration
  audioReady.value = true
}

/**
 * 播放结束
 */
const onEnded = () => {
  isPlaying.value = false
  currentTime.value = 0
  sliderValue.value = 0
}

/**
 * 音频加载错误
 */
const onError = (event: Event) => {
  console.error('音频加载失败:', event)
  ElMessage.error('音频加载失败，请检查网络或稍后重试')
  audioReady.value = false
}

/**
 * 格式化时间
 */
const formatTime = (seconds: number): string => {
  if (isNaN(seconds) || seconds === 0) {
    return '00:00'
  }

  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)

  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  } else {
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
}

// 验证必要参数
onMounted(() => {
  if (!mp3Url.value) {
    ElMessage.error('缺少播课音频地址')
    goBack()
  }
})

// 清理
onBeforeUnmount(() => {
  if (audioPlayer.value) {
    audioPlayer.value.pause()
  }
})
</script>

<style scoped lang="scss">
.broadcast-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.broadcast-header {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px 30px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);

  .course-title {
    margin: 0;
    color: #fff;
    font-size: 24px;
    font-weight: 600;
  }

  .header-spacer {
    flex: 1;
  }
}

.player-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.player-card {
  width: 100%;
  max-width: 600px;
  background: #fff;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);

  .player-icon {
    text-align: center;
    margin-bottom: 30px;
    color: #667eea;
  }

  .player-info {
    text-align: center;
    margin-bottom: 30px;

    h3 {
      margin: 0 0 10px 0;
      font-size: 20px;
      color: #333;
    }

    .time-display {
      margin: 0;
      font-size: 14px;
      color: #999;
    }
  }

  .progress-container {
    margin-bottom: 30px;
  }

  .controls {
    display: flex;
    flex-direction: column;
    gap: 20px;
    align-items: center;

    .speed-control {
      display: flex;
      align-items: center;
      gap: 10px;

      .speed-label {
        font-size: 14px;
        color: #666;
      }
    }
  }
}
</style>

