<template>
  <div class="page-container">
    <div class="page-header">
      <span class="title">{{ t('视频播放测试') }}</span>
    </div>

    <!-- 播放方式选择 -->
    <div class="config-section">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 方式1: 直接输入 URL -->
        <el-tab-pane :label="t('直接 URL')" name="url">
          <el-form label-width="120px">
            <el-form-item :label="t('视频地址')">
              <el-input v-model="urlConfig.url" placeholder="输入 HLS/MP4/WebM 等视频地址" style="width: 600px" />
            </el-form-item>
            <el-form-item :label="t('播放器类型')">
              <el-select v-model="urlConfig.playerType" style="width: 200px">
                <el-option label="HLS.js (推荐)" value="hls" />
                <el-option label="原生 Video" value="native" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="playUrl">{{ t('播放') }}</el-button>
              <el-button @click="urlConfig.url = ''">{{ t('清空') }}</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 方式2: Cloudflare Stream -->
        <el-tab-pane :label="t('Cloudflare Stream')" name="cloudflare">
          <el-form label-width="120px">
            <el-form-item :label="t('Video ID')">
              <el-input v-model="cfConfig.videoId" placeholder="Cloudflare Stream Video ID" style="width: 400px" />
            </el-form-item>
            <el-form-item :label="t('自定义域名')">
              <el-input
                v-model="cfConfig.customerDomain"
                placeholder="customer-xxx.cloudflarestream.com"
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item :label="t('播放方式')">
              <el-select v-model="cfConfig.playMode" style="width: 200px">
                <el-option label="iframe 嵌入" value="iframe" />
                <el-option label="HLS 播放" value="hls" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="playCloudflare">{{ t('播放') }}</el-button>
              <el-button @click="generateCfUrl">{{ t('生成地址') }}</el-button>
            </el-form-item>
            <el-form-item v-if="cfGeneratedUrl" :label="t('生成的地址')">
              <el-input :value="cfGeneratedUrl" readonly style="width: 600px">
                <template #append>
                  <el-button @click="copyUrl(cfGeneratedUrl)">{{ t('复制') }}</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 方式3: RTSP 转换 -->
        <el-tab-pane :label="t('RTSP 流')" name="rtsp">
          <el-form label-width="120px">
            <el-form-item :label="t('RTSP 地址')">
              <el-input
                v-model="rtspConfig.rtspUrl"
                placeholder="rtsp://username:password@ip:port/stream"
                style="width: 600px"
              />
            </el-form-item>
            <el-form-item :label="t('转换服务地址')">
              <el-input v-model="rtspConfig.proxyUrl" placeholder="http://localhost:8080/stream" style="width: 400px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="playRtsp">{{ t('播放') }}</el-button>
            </el-form-item>
            <el-alert type="info" :closable="false" style="margin-top: 10px">
              {{ t('RTSP 流需要通过服务端转换为 HLS/WebRTC 后才能在浏览器播放') }}
            </el-alert>
          </el-form>
        </el-tab-pane>

        <!-- 方式4: 测试视频 -->
        <el-tab-pane :label="t('测试视频')" name="sample">
          <el-form label-width="120px">
            <el-form-item :label="t('选择测试源')">
              <el-select v-model="sampleConfig.selected" style="width: 400px">
                <el-option v-for="item in sampleVideos" :key="item.url" :label="item.name" :value="item.url" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="playSample">{{ t('播放测试视频') }}</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 播放器区域 -->
    <div class="player-section">
      <div v-if="!currentSrc && !currentVideoId" class="player-placeholder">
        <el-icon :size="60" color="#ddd">
          <VideoPlay />
        </el-icon>
        <p>{{ t('请选择视频源并点击播放') }}</p>
      </div>
      <VideoPlayer
        v-else
        ref="playerRef"
        :player-type="currentPlayerType"
        :video-id="currentVideoId"
        :customer-domain="cfConfig.customerDomain"
        :src="currentSrc"
        :use-iframe="useIframe"
        :autoplay="playConfig.autoplay"
        :muted="playConfig.muted"
        :controls="true"
        @play="onPlay"
        @pause="onPause"
        @error="onError"
        @loadedmetadata="onLoaded"
      />
    </div>

    <!-- 播放控制 -->
    <div class="control-section">
      <el-space wrap>
        <el-button type="primary" @click="handlePlay">{{ t('播放') }}</el-button>
        <el-button @click="handlePause">{{ t('暂停') }}</el-button>
        <el-button type="danger" @click="handleStop">{{ t('停止') }}</el-button>
        <el-button @click="handleScreenshot">{{ t('截图') }}</el-button>
        <el-button @click="handleFullscreen">{{ t('全屏') }}</el-button>

        <el-divider direction="vertical" />

        <el-switch v-model="playConfig.muted" :active-text="t('静音')" :inactive-text="t('有声')" />
        <el-switch v-model="playConfig.autoplay" :active-text="t('自动播放')" :inactive-text="t('手动')" />
      </el-space>
    </div>

    <!-- 当前状态 -->
    <div class="status-section">
      <el-descriptions :title="t('当前状态')" :column="3" border>
        <el-descriptions-item :label="t('播放器类型')">{{ currentPlayerType }}</el-descriptions-item>
        <el-descriptions-item :label="t('iframe 模式')">{{ useIframe ? t('是') : t('否') }}</el-descriptions-item>
        <el-descriptions-item :label="t('Video ID')">{{ currentVideoId || '-' }}</el-descriptions-item>
        <el-descriptions-item :label="t('视频地址')" :span="3">
          <el-text truncated style="max-width: 800px">{{ currentSrc || '-' }}</el-text>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 日志区域 -->
    <div class="log-section">
      <div class="log-header">
        <h4>{{ t('事件日志') }}</h4>
        <el-button size="small" @click="logs = []">{{ t('清空') }}</el-button>
      </div>
      <div class="log-content">
        <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.type">
          <span class="time">{{ log.time }}</span>
          <span class="message">{{ log.message }}</span>
        </div>
        <div v-if="logs.length === 0" class="log-empty">{{ t('暂无日志') }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const playerRef = ref<InstanceType<typeof VideoPlayer>>()
const activeTab = ref('url')

// 直接 URL 配置
const urlConfig = reactive({
  url: '',
  playerType: 'hls' as 'hls' | 'native'
})

// Cloudflare Stream 配置
const cfConfig = reactive({
  videoId: '3c1ae1949e76f200feef94b8f7d093ca',
  customerDomain: 'customer-pj89kn2ke2tcuh19.cloudflarestream.com',
  playMode: 'iframe' as 'iframe' | 'hls'
})
const cfGeneratedUrl = ref('')

// RTSP 配置
const rtspConfig = reactive({
  rtspUrl: '',
  proxyUrl: ''
})

// 测试视频配置
const sampleConfig = reactive({
  selected: ''
})

// 播放配置
const playConfig = reactive({
  autoplay: false,
  muted: true
})

// 当前播放状态
const currentSrc = ref('')
const currentVideoId = ref('')
const currentPlayerType = ref<'hls' | 'native' | 'cloudflare'>('hls')
const useIframe = ref(false)

// 测试视频列表
const sampleVideos = [
  // === 我的直播流 (Cloudflare Stream) ===
  {
    name: '我的摄像头直播',
    url: 'https://customer-pj89kn2ke2tcuh19.cloudflarestream.com/3c1ae1949e76f200feef94b8f7d093ca/manifest/video.m3u8'
  },
  // === 公共测试源 ===
  { name: 'Big Buck Bunny (HLS)', url: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8' },
  { name: 'Sintel (HLS)', url: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8' },
  {
    name: 'Tears of Steel (HLS)',
    url: 'https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.m3u8'
  },
  {
    name: 'Apple HLS 测试流',
    url: 'https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8'
  }
]

// 日志
interface LogItem {
  time: string
  type: 'info' | 'success' | 'error'
  message: string
}
const logs = ref<LogItem[]>([])

function addLog(message: string, type: LogItem['type'] = 'info') {
  const time = new Date().toLocaleTimeString()
  logs.value.unshift({ time, type, message })
  if (logs.value.length > 100) {
    logs.value.pop()
  }
}

// 播放直接 URL
function playUrl() {
  if (!urlConfig.url) {
    ElMessage.warning('请输入视频地址')
    return
  }
  currentSrc.value = urlConfig.url
  currentVideoId.value = ''
  currentPlayerType.value = urlConfig.playerType
  useIframe.value = false
  addLog(`播放 URL: ${urlConfig.url}`, 'success')
}

// 播放 Cloudflare Stream
function playCloudflare() {
  if (!cfConfig.videoId) {
    ElMessage.warning('请输入 Video ID')
    return
  }

  currentVideoId.value = cfConfig.videoId
  useIframe.value = cfConfig.playMode === 'iframe'

  if (cfConfig.playMode === 'hls') {
    const domain = cfConfig.customerDomain || 'customer-xxx.cloudflarestream.com'
    currentSrc.value = `https://${domain}/${cfConfig.videoId}/manifest/video.m3u8`
    currentPlayerType.value = 'hls'
  } else {
    currentSrc.value = ''
    currentPlayerType.value = 'cloudflare'
  }

  addLog(`播放 Cloudflare Stream: ${cfConfig.videoId} (${cfConfig.playMode})`, 'success')
}

// 生成 Cloudflare URL
function generateCfUrl() {
  if (!cfConfig.videoId) {
    ElMessage.warning('请输入 Video ID')
    return
  }
  const domain = cfConfig.customerDomain || 'customer-xxx.cloudflarestream.com'
  if (cfConfig.playMode === 'iframe') {
    cfGeneratedUrl.value = `https://${domain}/${cfConfig.videoId}/iframe`
  } else {
    cfGeneratedUrl.value = `https://${domain}/${cfConfig.videoId}/manifest/video.m3u8`
  }
}

// 播放 RTSP
function playRtsp() {
  if (!rtspConfig.proxyUrl) {
    ElMessage.warning('请输入转换服务地址')
    return
  }
  currentSrc.value = rtspConfig.proxyUrl
  currentVideoId.value = ''
  currentPlayerType.value = 'hls'
  useIframe.value = false
  addLog(`播放 RTSP (via proxy): ${rtspConfig.proxyUrl}`, 'success')
}

// 播放测试视频
function playSample() {
  if (!sampleConfig.selected) {
    ElMessage.warning('请选择测试视频')
    return
  }
  currentSrc.value = sampleConfig.selected
  currentVideoId.value = ''
  currentPlayerType.value = 'hls'
  useIframe.value = false
  const video = sampleVideos.find((v) => v.url === sampleConfig.selected)
  addLog(`播放测试视频: ${video?.name}`, 'success')
}

// 复制 URL
function copyUrl(url: string) {
  navigator.clipboard.writeText(url)
  ElMessage.success('已复制到剪贴板')
}

// 播放控制
function handlePlay() {
  playerRef.value?.play()
  addLog('播放', 'info')
}

function handlePause() {
  playerRef.value?.pause()
  addLog('暂停', 'info')
}

function handleStop() {
  playerRef.value?.stop()
  addLog('停止', 'info')
}

function handleScreenshot() {
  playerRef.value?.screenshot()
  addLog('截图', 'info')
}

function handleFullscreen() {
  playerRef.value?.fullscreen()
  addLog('全屏', 'info')
}

// 事件处理
function onPlay() {
  addLog('视频开始播放', 'success')
}

function onPause() {
  addLog('视频已暂停', 'info')
}

function onLoaded() {
  addLog('视频加载完成', 'success')
}

function onError(error: any) {
  addLog(`播放错误: ${JSON.stringify(error)}`, 'error')
}
</script>

<style lang="scss" scoped>
.page-container {
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #fff;
  border-radius: var(--radius-base);

  .title {
    font-size: 18px;
    font-weight: 600;
  }
}

.config-section {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: var(--radius-base);
}

.player-section {
  height: 500px;
  margin-bottom: 20px;
  border-radius: var(--radius-base);
  overflow: hidden;
  background-color: #000;

  .player-placeholder {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;

    p {
      margin-top: 15px;
      font-size: 14px;
    }
  }
}

.control-section {
  padding: 15px 20px;
  background-color: #fff;
  border-radius: var(--radius-base);
  margin-bottom: 20px;
}

.status-section {
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #fff;
  border-radius: var(--radius-base);
}

.log-section {
  padding: 15px 20px;
  background-color: #fff;
  border-radius: var(--radius-base);

  .log-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;

    h4 {
      font-size: 14px;
      margin: 0;
    }
  }

  .log-content {
    max-height: 200px;
    overflow-y: auto;
    background-color: #fafafa;
    border-radius: var(--radius-base);
    padding: 10px;
  }

  .log-item {
    font-size: 12px;
    padding: 4px 0;
    border-bottom: 1px solid #eee;

    &:last-child {
      border-bottom: none;
    }

    .time {
      color: #999;
      margin-right: 10px;
    }

    &.success .message {
      color: #67c23a;
    }

    &.error .message {
      color: #f56c6c;
    }
  }

  .log-empty {
    text-align: center;
    color: #999;
    font-size: 12px;
    padding: 20px 0;
  }
}
</style>
