<template>
  <view class="page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-btn" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <text class="nav-title">正在播放</text>
      <view class="nav-btn" />
    </view>

    <!-- 封面和标题 -->
    <view class="cover-section">
      <view class="cover">
        <text class="cover-icon">🎵</text>
      </view>
      <text class="title">{{ audio?.title || '未知标题' }}</text>
      <text class="meta">{{ formatDuration(audio?.audioDuration || 0) }} · {{ audio?.wordCount || 0 }}字</text>
    </view>

    <!-- 文本预览 -->
    <view class="text-preview">
      <text class="preview-text">{{ (audio?.text || '').slice(0, 200) }}{{ (audio?.text || '').length > 200 ? '...' : '' }}</text>
    </view>

    <!-- 进度条 -->
    <view class="progress-section">
      <text class="time">{{ formatDuration(currentTime) }}</text>
      <slider
        :value="currentTime"
        :max="duration || 100"
        @change="handleSeek"
        activeColor="#4F46E5"
        backgroundColor="#e5e7eb"
        block-size="16"
        class="progress-slider"
      />
      <text class="time">{{ formatDuration(duration) }}</text>
    </view>

    <!-- 播放控制 -->
    <view class="controls">
      <!-- 播放速度 -->
      <view class="control-btn" @click="showRatePicker = true">
        <text class="control-text">{{ playRate }}x</text>
      </view>

      <!-- 上一首 -->
      <view class="control-btn" :class="{ disabled: !hasPrev }" @click="playPrev">
        <text class="control-icon">⏮</text>
      </view>

      <!-- 播放/暂停 -->
      <view class="play-btn" @click="togglePlay">
        <text class="play-icon">{{ isPlaying ? '⏸' : '▶' }}</text>
      </view>

      <!-- 下一首 -->
      <view class="control-btn" :class="{ disabled: !hasNext }" @click="playNext">
        <text class="control-icon">⏭</text>
      </view>

      <!-- 收藏 -->
      <view class="control-btn" @click="toggleFavorite">
        <text class="control-icon">{{ audio?.isFavorite ? '❤️' : '🤍' }}</text>
      </view>
    </view>

    <!-- 底部操作 -->
    <view class="bottom-actions">
      <button class="action-btn" @click="handleDownload">
        <text class="action-icon">⬇</text>
        <text class="action-text">下载</text>
      </button>
      <button class="action-btn" @click="handleShare">
        <text class="action-icon">↗</text>
        <text class="action-text">分享</text>
      </button>
    </view>

    <!-- 播放速度选择器 -->
    <view v-if="showRatePicker" class="rate-picker" @click="showRatePicker = false">
      <view class="rate-content" @click.stop>
        <text class="rate-title">播放速度</text>
        <view class="rate-options">
          <view
            v-for="rate in [0.5, 0.75, 1, 1.25, 1.5, 2]"
            :key="rate"
            class="rate-item"
            :class="{ active: playRate === rate }"
            @click="handleSetRate(rate)"
          >
            <text>{{ rate }}x</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useAudioStore } from '../../store/audio';
import { get, put } from '../../utils/request';
import type { AudioItem } from '../../types';

const audioStore = useAudioStore();

// 状态
const audioId = ref('');
const audio = ref<AudioItem | null>(null);
const showRatePicker = ref(false);

// 从 store 获取状态
const isPlaying = computed(() => audioStore.isPlaying);
const currentTime = computed(() => audioStore.currentTime);
const duration = computed(() => audioStore.duration);
const playRate = computed(() => audioStore.playRate);
const hasPrev = computed(() => audioStore.hasPrev);
const hasNext = computed(() => audioStore.hasNext);

// 页面加载
onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  audioId.value = currentPage?.options?.id || '';

  if (audioId.value) {
    await fetchAudio();
    // 获取播放列表
    await fetchPlaylist();
  }
});

// 页面卸载
onUnmounted(() => {
  // 不销毁音频上下文，保持后台播放
});

// 获取音频详情
async function fetchAudio() {
  try {
    const result = await get<AudioItem>(`/audio/${audioId.value}`);
    audio.value = result;

    // 开始播放（store 中已初始化 audioContext）
    audioStore.play(result);
  } catch (error: any) {
    console.error('获取音频失败:', error);
    uni.showToast({ title: error.message || '音频不存在', icon: 'none' });
  }
}

// 获取播放列表
async function fetchPlaylist() {
  try {
    const result = await get<{ list: AudioItem[] }>('/audio/list', {
      page: 1,
      pageSize: 100,
    });
    
    // 设置播放列表（不自动播放，因为已经在 fetchAudio 中播放了当前音频）
    const index = result.list.findIndex(item => item._id === audioId.value);
    if (index >= 0) {
      audioStore.setPlaylist(result.list, index, false);
    }
  } catch (error) {
    console.error('获取播放列表失败:', error);
  }
}

// 格式化时长
function formatDuration(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
}

// 返回
function goBack() {
  uni.navigateBack();
}

// 跳转进度
function handleSeek(e: any) {
  audioStore.seek(e.detail.value);
}

// 切换播放/暂停
function togglePlay() {
  audioStore.togglePlay();
}

// 上一首
function playPrev() {
  if (hasPrev.value) {
    audioStore.playPrev();
    audio.value = audioStore.currentAudio;
  }
}

// 下一首
function playNext() {
  if (hasNext.value) {
    audioStore.playNext();
    audio.value = audioStore.currentAudio;
  }
}

// 设置播放速度
function handleSetRate(rate: number) {
  audioStore.setPlayRate(rate);
  showRatePicker.value = false;
}

// 切换收藏
async function toggleFavorite() {
  if (!audio.value) return;

  try {
    const result = await put<{ isFavorite: boolean }>(`/audio/${audio.value._id}/favorite`);
    audio.value.isFavorite = result.isFavorite;
    uni.showToast({
      title: result.isFavorite ? '已收藏' : '已取消收藏',
      icon: 'success',
    });
  } catch (error) {
    console.error('操作失败:', error);
  }
}

// 下载
function handleDownload() {
  if (!audio.value) return;

  uni.showLoading({ title: '下载中...' });
  uni.downloadFile({
    url: audio.value.audioUrl,
    success: (res) => {
      uni.hideLoading();
      if (res.statusCode === 200) {
        // 提示用户文件保存位置
        uni.showModal({
          title: '下载成功',
          content: '文件已下载到临时目录，请在文件管理器中查找',
          showCancel: false,
        });
      }
    },
    fail: (err) => {
      uni.hideLoading();
      console.error('下载失败:', err);
      uni.showToast({ title: '下载失败', icon: 'none' });
    },
  });
}

// 分享
function handleShare() {
  // H5 使用 Web Share API
  if (typeof navigator !== 'undefined' && navigator.share) {
    navigator.share({
      title: audio.value?.title || 'AI 有声书',
      url: window.location.href,
    }).catch(() => {
      // 用户取消或分享失败，降级到复制链接
      copyShareLink();
    });
  } else {
    // 其他平台：复制链接到剪贴板
    copyShareLink();
  }
}

// 复制链接
function copyShareLink() {
  if (!audio.value) return;
  
  const shareUrl = `${window.location.origin}/#/pages/player/index?id=${audio.value._id}`;
  uni.setClipboardData({
    data: shareUrl,
    success: () => {
      uni.showToast({
        title: '链接已复制',
        icon: 'success',
      });
    },
    fail: () => {
      uni.showToast({
        title: '请截图分享',
        icon: 'none',
      });
    },
  });
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(180deg, #1f2937 0%, #111827 100%);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44rpx 32rpx 24rpx;
}

.nav-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-icon {
  font-size: 36rpx;
  color: #ffffff;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}

.cover-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48rpx 0;
}

.cover {
  width: 320rpx;
  height: 320rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32rpx;
  box-shadow: 0 16rpx 48rpx rgba(79, 70, 229, 0.4);
}

.cover-icon {
  font-size: 96rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #ffffff;
  text-align: center;
  margin-bottom: 12rpx;
  max-width: 600rpx;
}

.meta {
  font-size: 24rpx;
  color: #9ca3af;
}

.text-preview {
  margin: 0 32rpx;
  padding: 24rpx;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 16rpx;
}

.preview-text {
  font-size: 26rpx;
  color: #9ca3af;
  line-height: 1.6;
}

.progress-section {
  display: flex;
  align-items: center;
  padding: 32rpx;
}

.time {
  font-size: 22rpx;
  color: #9ca3af;
  width: 80rpx;
  text-align: center;
}

.progress-slider {
  flex: 1;
  margin: 0 16rpx;
}

.controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 32rpx;
  padding: 24rpx;
}

.control-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-btn.disabled {
  opacity: 0.3;
}

.control-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 600;
}

.control-icon {
  font-size: 40rpx;
}

.play-btn {
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(79, 70, 229, 0.5);
}

.play-icon {
  font-size: 48rpx;
  color: #ffffff;
  margin-left: 8rpx;
}

.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 80rpx;
  padding: 48rpx;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: transparent;
  border: none;
  padding: 0;
}

.action-btn::after {
  border: none;
}

.action-icon {
  font-size: 48rpx;
  margin-bottom: 8rpx;
}

.action-text {
  font-size: 24rpx;
  color: #9ca3af;
}

.rate-picker {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.rate-content {
  width: 100%;
  background: #1f2937;
  border-radius: 32rpx 32rpx 0 0;
  padding: 48rpx;
}

.rate-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
  text-align: center;
  margin-bottom: 32rpx;
}

.rate-options {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.rate-item {
  flex: 1;
  min-width: 180rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #374151;
  border-radius: 16rpx;
  border: 2rpx solid transparent;
}

.rate-item.active {
  background: #4f46e5;
  border-color: #6366f1;
}

.rate-item text {
  font-size: 28rpx;
  color: #ffffff;
}
</style>