<template>
  <div class="result-detail-page">
    <div class="detail-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="6" animated />
      </div>

      <!-- 网盘资源详情 -->
      <div v-else-if="result" class="detail-card">
        <div class="detail-header">
          <div class="detail-cover">
            <img :src="result.cover" :alt="result.title" />
            <CloudBadge :cloud_type="result.cloud_type" />
          </div>
          <div class="detail-info">
            <h1>{{ result.title }}</h1>
            <div class="detail-meta">
              <el-tag v-if="result.file_size">📦 {{ result.file_size }}</el-tag>
              <el-tag v-if="result.update_time">🕐 {{ result.update_time }}</el-tag>
              <el-tag v-if="result.source">📂 {{ result.source }}</el-tag>
            </div>
            <p v-if="result.description" class="detail-desc">{{ result.description }}</p>
          </div>
        </div>
        <div class="detail-actions">
          <el-button type="primary" size="large" @click="showSaveDialog">
            📥 保存到网盘
          </el-button>
        </div>
      </div>

      <!-- 视频解析详情 -->
      <div v-else-if="videoResult" class="detail-card">
        <div class="detail-video">
          <div class="video-preview">
            <img :src="videoResult.cover" :alt="videoResult.title" />
            <div class="play-overlay" @click="playVideo">
              <div class="play-btn">▶ 播放</div>
            </div>
          </div>
          <div class="video-info">
            <h1>{{ videoResult.title }}</h1>
            <p v-if="videoResult.author" class="video-author">👤 {{ videoResult.author }}</p>
            <p class="video-platform">📺 {{ videoResult.platform }}</p>
            <p v-if="videoResult.description" class="detail-desc">{{ videoResult.description }}</p>
          </div>
        </div>
        <div class="detail-actions">
          <el-button type="primary" size="large" @click="showSaveDialog">
            📥 保存到云盘
          </el-button>
        </div>

        <!-- 视频播放器 -->
        <div v-if="showPlayer" class="video-player-wrapper">
          <video :src="videoResult.video_url" controls autoplay class="video-player"></video>
        </div>
      </div>

      <!-- 未找到 -->
      <el-empty v-else description="未找到该资源" />
    </div>

    <!-- 保存弹窗 -->
    <el-dialog v-model="saveDialogVisible" title="保存到网盘" width="420px">
      <div class="save-dialog-content">
        <p class="save-file-name">📄 {{ result?.title || videoResult?.title }}</p>
        <CloudSelect @select="onCloudSelected" />
      </div>
      <template #footer>
        <el-button @click="saveDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="confirmSave">确认保存</el-button>
      </template>
    </el-dialog>

    <!-- 保存结果弹窗 -->
    <el-dialog v-model="resultDialogVisible" title="保存成功" width="420px">
      <div class="result-dialog-content">
        <el-alert type="success" :title="saveResult?.message || '保存成功'" show-icon :closable="false" />
        <div class="share-link-box">
          <p class="share-label">分享链接：</p>
          <div class="share-link-row">
            <el-input v-model="shareLink" readonly />
            <el-button @click="copyShareLink">复制</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="resultDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import CloudBadge from '../components/CloudBadge.vue'
import CloudSelect from '../components/CloudSelect.vue'
import { query, saveToCloud, saveVideoToCloud } from '../api'
import { ElMessage } from 'element-plus'
import type { SearchResult, VideoParseResult, SaveResult } from '../types'

const route = useRoute()

const loading = ref(false)
const result = ref<SearchResult | null>(null)
const videoResult = ref<VideoParseResult | null>(null)
const showPlayer = ref(false)

const saveDialogVisible = ref(false)
const saving = ref(false)
const selectedCloud = ref('')
const isVideo = ref(false)

const resultDialogVisible = ref(false)
const saveResult = ref<SaveResult | null>(null)
const shareLink = ref('')

onMounted(async () => {
  const id = route.params.id as string
  if (!id) return

  loading.value = true
  try {
    // 用 id 作为搜索词重新查询具体结果
    const res = await query(id)
    if (res.intent === 'SEARCH' && res.results.length > 0) {
      result.value = (res.results as SearchResult[])[0]
    } else if (res.intent === 'VIDEO_PARSE' && res.results.length > 0) {
      videoResult.value = (res.results as VideoParseResult[])[0]
    }
  } catch (e) {
    console.error('获取详情失败', e)
  } finally {
    loading.value = false
  }
})

function showSaveDialog() {
  isVideo.value = !!videoResult.value
  saveDialogVisible.value = true
}

function playVideo() {
  showPlayer.value = true
}

function onCloudSelected(cloudType: string) {
  selectedCloud.value = cloudType
}

async function confirmSave() {
  if (!selectedCloud.value) {
    ElMessage.warning('请选择目标网盘')
    return
  }
  saving.value = true
  try {
    let res: SaveResult
    if (isVideo.value && videoResult.value) {
      res = await saveVideoToCloud({
        video_url: videoResult.value.video_url,
        title: videoResult.value.title,
        target_cloud: selectedCloud.value,
      })
    } else if (result.value) {
      res = await saveToCloud({
        type: 'search',
        source: result.value,
        target_cloud: selectedCloud.value,
      })
    } else {
      return
    }
    saveResult.value = res
    shareLink.value = res.share_url
    saveDialogVisible.value = false
    resultDialogVisible.value = true
  } catch (e) {
    console.error('保存失败', e)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

async function copyShareLink() {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch {
    ElMessage.warning('复制失败，请手动复制')
  }
}
</script>

<style scoped>
.result-detail-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 40px 24px;
}
.detail-container {
  max-width: 1080px;
  margin: 0 auto;
}
.detail-card {
  background: var(--bg-white);
  border-radius: var(--radius-card);
  box-shadow: var(--shadow-card);
  padding: 32px;
}
.detail-header {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}
.detail-cover {
  position: relative;
  flex-shrink: 0;
  width: 240px;
  height: 180px;
  border-radius: 12px;
  overflow: hidden;
}
.detail-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.detail-info {
  flex: 1;
}
.detail-info h1 {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 12px;
  line-height: 1.4;
}
.detail-meta {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}
.detail-desc {
  font-size: 15px;
  color: #606266;
  line-height: 1.6;
}
.detail-actions {
  border-top: 1px solid var(--border-color);
  padding-top: 20px;
}
.detail-video {
  margin-bottom: 24px;
}
.video-preview {
  position: relative;
  width: 100%;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
}
.video-preview img {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  display: block;
}
.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  cursor: pointer;
  transition: background 0.2s;
}
.play-overlay:hover {
  background: rgba(0, 0, 0, 0.4);
}
.play-btn {
  padding: 12px 32px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 24px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}
.video-info h1 {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 12px;
}
.video-author,
.video-platform {
  font-size: 15px;
  color: var(--text-secondary);
  margin-bottom: 6px;
}
.video-player-wrapper {
  margin-top: 24px;
  border-top: 1px solid var(--border-color);
  padding-top: 24px;
}
.video-player {
  width: 100%;
  border-radius: 8px;
}
.loading-state {
  padding: 40px 0;
}
.save-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.save-file-name {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
}
.result-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.share-link-box {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.share-label {
  font-size: 14px;
  color: #606266;
}
.share-link-row {
  display: flex;
  gap: 8px;
}
</style>
