<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <text class="logo">AI有声书</text>
        <view class="nav-right" @click="handleUserClick">
          <image v-if="userStore.userInfo?.avatar" :src="userStore.userInfo.avatar" class="avatar" mode="aspectFill" />
          <view v-else class="avatar-placeholder">
            <text class="avatar-text">登</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 音频列表 -->
    <scroll-view scroll-y class="audio-list" @scrolltolower="loadMore">
      <view v-if="audioList.length === 0 && !loading" class="empty">
        <text class="empty-icon">🎵</text>
        <text class="empty-text">暂无音频</text>
        <text class="empty-hint">点击下方按钮生成第一个音频</text>
      </view>

      <view v-else class="audio-grid">
        <view
          v-for="item in audioList"
          :key="item._id"
          class="audio-card"
          @click="playAudio(item)"
        >
          <view class="audio-cover" :style="{ background: getCoverGradient(item.voiceId) }">
            <text class="cover-icon">🎵</text>
            <view class="play-overlay">
              <text class="play-icon">▶</text>
            </view>
            <text class="audio-duration-badge">{{ formatDuration(item.audioDuration) }}</text>
          </view>
          <view class="audio-info">
            <text class="audio-title">{{ item.title }}</text>
            <text class="audio-meta">{{ item.wordCount }}字 · {{ formatDate(item.createdAt) }}</text>
          </view>
        </view>
      </view>

      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>

      <view v-if="!hasMore && audioList.length > 0" class="no-more">
        <text>没有更多了</text>
      </view>
    </scroll-view>

    <!-- 底部生成按钮 -->
    <view class="bottom-bar">
      <button class="generate-btn" @click="handleGenerate">
        <text class="btn-icon">+</text>
        <text class="btn-text">新建生成</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useUserStore } from '../../store/user';
import { useAudioStore } from '../../store/audio';
import { get } from '../../utils/request';
import type { AudioItem } from '../../types';

const userStore = useUserStore();
const audioStore = useAudioStore();

// 音色封面颜色映射
const voiceColors: Record<string, string[]> = {
  cherry: ['#667eea', '#764ba2'],
  ethan: ['#f093fb', '#f5576c'],
  serena: ['#4facfe', '#00f2fe'],
  chelsie: ['#43e97b', '#38f9d7'],
  momo: ['#fa709a', '#fee140'],
  vivian: ['#a8edea', '#fed6e3'],
  moon: ['#5ee7df', '#b490ca'],
  maia: ['#d299c2', '#fef9d7'],
  kai: ['#89f7fe', '#66a6ff'],
  nofish: ['#cd9cf2', '#f6f3ff'],
};

// 音频列表状态
const audioList = ref<AudioItem[]>([]);
const page = ref(1);
const pageSize = 20;
const total = ref(0);
const loading = ref(false);
const hasMore = ref(true);

// 获取封面渐变色
function getCoverGradient(voiceId: string): string {
  const colors = voiceColors[voiceId] || ['#667eea', '#764ba2'];
  return `linear-gradient(135deg, ${colors[0]} 0%, ${colors[1]} 100%)`;
}

// 获取音频列表
async function fetchAudioList(isLoadMore = false) {
  if (loading.value) return;
  if (!isLoadMore) {
    page.value = 1;
  }

  loading.value = true;
  try {
    const result = await get<{ list: AudioItem[]; total: number; totalPages: number }>('/audio/list', {
      page: page.value,
      pageSize,
    });
    
    if (isLoadMore) {
      audioList.value.push(...result.list);
    } else {
      audioList.value = result.list;
    }
    total.value = result.total;
    hasMore.value = page.value < result.totalPages;
  } catch (error) {
    console.error('获取音频列表失败:', error);
  } finally {
    loading.value = false;
  }
}

// 加载更多
function loadMore() {
  if (hasMore.value && !loading.value) {
    page.value++;
    fetchAudioList(true);
  }
}

// 播放音频
function playAudio(item: AudioItem) {
  audioStore.play(item);
  uni.navigateTo({ url: `/pages/player/index?id=${item._id}` });
}

// 格式化时长
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 formatDate(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) return '今天';
  if (days === 1) return '昨天';
  if (days < 7) return `${days}天前`;

  return `${date.getMonth() + 1}/${date.getDate()}`;
}

// 点击用户头像
function handleUserClick() {
  uni.navigateTo({ url: '/pages/mine/index' });
}

// 生成新音频（跳转到历史页面）
function handleGenerate() {
  uni.navigateTo({ url: '/pages/history/index' });
}

// 初始化
onMounted(async () => {
  await fetchAudioList();
});

// 页面显示时刷新
onShow(() => {
  fetchAudioList();
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 180rpx;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: #ffffff;
  z-index: 100;
  padding-top: 44rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  height: 88rpx;
}

.logo {
  font-size: 36rpx;
  font-weight: 600;
  color: #4f46e5;
}

.nav-right {
  display: flex;
  align-items: center;
}

.avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
}

.avatar-placeholder {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  font-size: 24rpx;
  color: #ffffff;
}

.audio-list {
  padding-top: 132rpx;
  height: calc(100vh - 140rpx);
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty .login-btn {
  margin-top: 32rpx;
  padding: 16rpx 48rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 44rpx;
  border: none;
  font-size: 28rpx;
  color: #ffffff;
}

.empty .login-btn::after {
  border: none;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #6b7280;
  margin-bottom: 12rpx;
}

.empty-hint {
  font-size: 26rpx;
  color: #9ca3af;
}

.audio-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 24rpx;
  gap: 20rpx;
}

.audio-card {
  width: calc(50% - 10rpx);
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.audio-cover {
  position: relative;
  width: 100%;
  height: 240rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-icon {
  font-size: 80rpx;
  opacity: 0.6;
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.audio-card:active .play-overlay {
  opacity: 1;
}

.play-icon {
  width: 80rpx;
  height: 80rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #4f46e5;
  padding-left: 8rpx;
}

.audio-duration-badge {
  position: absolute;
  bottom: 12rpx;
  right: 12rpx;
  background: rgba(0, 0, 0, 0.6);
  color: #ffffff;
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.audio-info {
  padding: 20rpx;
}

.audio-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #1f2937;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 8rpx;
}

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

.loading,
.no-more {
  text-align: center;
  padding: 32rpx;
}

.loading text,
.no-more text {
  font-size: 24rpx;
  color: #9ca3af;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #ffffff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.generate-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 44rpx;
  border: none;
}

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

.btn-icon {
  font-size: 36rpx;
  color: #ffffff;
  margin-right: 8rpx;
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}
</style>
