<template>
  <view class="page">
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack"><text class="back-icon">←</text></view>
        <text class="page-title">视频预览</text>
        <view class="nav-right"></view>
      </view>
    </view>

    <view class="video-container" v-if="project?.outputUrl">
      <video
        :src="baseUrl + project.outputUrl"
        class="video-player"
        controls
        autoplay
        show-fullscreen-btn
      ></video>
    </view>

    <view class="empty-state" v-else>
      <text class="empty-icon">🎥</text>
      <text class="empty-text">暂无视频</text>
    </view>

    <view class="action-buttons">
      <button class="action-btn download" @click="downloadVideo" v-if="project?.outputUrl">
        📥 下载视频
      </button>
      <button class="action-btn share" @click="shareVideo" v-if="project?.outputUrl">
        📤 分享视频
      </button>
      <button class="action-btn publish" @click="goToPublish" v-if="project?.outputUrl">
        🚀 发布到平台
      </button>
      <button class="action-btn regenerate" @click="regenerateVideo">
        🔄 重新生成
      </button>
    </view>

    <view class="video-info" v-if="project">
      <text class="info-title">{{ project.title }}</text>
      <view class="info-meta">
        <text class="meta-item">时长: {{ formatDuration(project.duration) }}</text>
        <text class="meta-item">大小: {{ formatFileSize(project.fileSize) }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { getVideoProject, generateVideo, getGenerateProgress, type VideoProjectResponse } from '@/utils/video-generator-api';

const baseUrl = ''; // 使用相对路径，依赖 Nginx 代理
const project = ref<VideoProjectResponse | null>(null);

function goBack() {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({ url: '/pages/index/index' });
  }
}

function formatDuration(seconds: number | null): string {
  if (!seconds) return '--:--';
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, '0')}`;
}

function formatFileSize(bytes: number | null): string {
  if (!bytes) return '--';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
  return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
}

async function loadProject(id: number) {
  try {
    project.value = await getVideoProject(id);
  } catch (error) {
    console.error('加载项目失败:', error);
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
}

async function downloadVideo() {
  if (!project.value?.outputUrl) return;
  const url = baseUrl + project.value.outputUrl;

  // #ifdef H5
  // H5 平台：打开新窗口下载
  window.open(url, '_blank');
  // #endif

  // #ifndef H5
  // App 平台：下载并保存到相册
  uni.downloadFile({
    url: url,
    success: (res) => {
      if (res.statusCode === 200) {
        uni.saveVideoToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            uni.showToast({ title: '保存成功', icon: 'success' });
          },
          fail: (err) => {
            console.error('保存失败:', err);
            uni.showToast({ title: '保存失败', icon: 'none' });
          }
        });
      } else {
        uni.showToast({ title: '下载失败', icon: 'none' });
      }
    },
    fail: (err) => {
      console.error('下载失败:', err);
      uni.showToast({ title: '下载失败', icon: 'none' });
    }
  });
  // #endif
}

async function shareVideo() {
  if (!project.value?.outputUrl) return;
  const url = baseUrl + project.value.outputUrl;
  uni.share({
    provider: 'weixin',
    scene: 'WXSession',
    title: project.value.title,
    type: 5,
    videoUrl: url,
  });
}

function goToPublish() {
  if (!project.value?.id) return;
  uni.navigateTo({ url: `/pages/publish/index?projectId=${project.value.id}` });
}

async function regenerateVideo() {
  if (!project.value?.id) return;
  try {
    uni.showLoading({ title: '正在重新生成...' });
    await generateVideo(project.value.id);
    const pollInterval = setInterval(async () => {
      const data = await getGenerateProgress(project.value!.id);
      if (data.status === 'completed') {
        clearInterval(pollInterval);
        uni.hideLoading();
        uni.showToast({ title: '重新生成成功', icon: 'success' });
        loadProject(project.value!.id);
      } else if (data.status === 'failed') {
        clearInterval(pollInterval);
        uni.hideLoading();
        uni.showToast({ title: '生成失败', icon: 'none' });
      }
    }, 2000);
  } catch (error) {
    uni.hideLoading();
    console.error('重新生成失败:', error);
    uni.showToast({ title: '重新生成失败', icon: 'none' });
  }
}

let projectIdLoaded = 0;

onLoad((query: any) => {
  if (query?.id) {
    projectIdLoaded = Number(query.id);
    loadProject(projectIdLoaded);
  }
});

onShow(() => {
  // H5 环境下 onLoad 可能不会再次触发，需要在 onShow 中检查并刷新
  if (projectIdLoaded && project.value?.id !== projectIdLoaded) {
    loadProject(projectIdLoaded);
  }
});
</script>

<style scoped>
.page { min-height: 100vh; background: #f5f5f5; }
.nav-bar { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px 15px; }
.nav-content { display: flex; align-items: center; justify-content: space-between; }
.nav-left { width: 40px; }
.back-icon { font-size: 24px; color: white; }
.page-title { font-size: 18px; font-weight: 600; color: white; }
.video-container { padding: 15px; }
.video-player { width: 100%; border-radius: 12px; }
.empty-state { padding: 60px 20px; text-align: center; }
.empty-icon { font-size: 64px; display: block; margin-bottom: 15px; }
.empty-text { font-size: 18px; color: #666; }
.action-buttons { padding: 15px; display: flex; flex-direction: column; gap: 10px; }
.action-btn { border: none; padding: 15px; border-radius: 8px; font-size: 16px; color: white; }
.action-btn.download { background: #67c23a; }
.action-btn.share { background: #409eff; }
.action-btn.regenerate { background: #909399; }
.action-btn.publish { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.video-info { padding: 20px 15px; }
.info-title { font-size: 18px; font-weight: 600; color: #333; display: block; margin-bottom: 10px; }
.info-meta { display: flex; gap: 20px; }
.meta-item { font-size: 14px; color: #666; }
</style>
