<template>
  <view class="page">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-inner">
        <text class="search-icon">🔍</text>
        <text class="search-placeholder">搜索历史记录...</text>
      </view>
    </view>

    <!-- 标签栏 -->
    <view class="tab-bar">
      <scroll-view class="tab-scroll" scroll-x="true" :show-scrollbar="false">
        <view class="tab-list">
          <view
            v-for="tab in tabs"
            :key="tab.id"
            class="tab-item"
            :class="{ active: selectedTab === tab.id }"
            @click="selectTab(tab.id)"
          >
            <text>{{ tab.name }}</text>
          </view>
        </view>
      </scroll-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>
</template>

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

const audioStore = useAudioStore();

// 标签状态
const tabs = ref([
  { id: 1, name: '全部' },
  { id: 2, name: '今天' },
  { id: 3, name: '本周' },
  { id: 4, name: '本月' },
]);
const selectedTab = ref(1);

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

// 音色封面颜色映射
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'],
};

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

// 选择标签
async function selectTab(tabId: number) {
  selectedTab.value = tabId;
  page.value = 1;
  await fetchHistoryList();
}

// 获取历史列表
async function fetchHistoryList(isLoadMore = false) {
  if (loading.value) return;
  if (!isLoadMore) {
    page.value = 1;
  }

  loading.value = true;
  try {
    // 按时间过滤
    let startDate = '';
    const now = new Date();
    
    switch (selectedTab.value) {
      case 2: // 今天
        startDate = new Date(now.setHours(0, 0, 0, 0)).toISOString();
        break;
      case 3: // 本周
        const weekAgo = new Date(now);
        weekAgo.setDate(weekAgo.getDate() - 7);
        startDate = weekAgo.toISOString();
        break;
      case 4: // 本月
        const monthAgo = new Date(now);
        monthAgo.setMonth(monthAgo.getMonth() - 1);
        startDate = monthAgo.toISOString();
        break;
    }

    const params: any = { page: page.value, pageSize };
    if (startDate) {
      params.startDate = startDate;
    }

    const result = await get<{ list: AudioItem[]; total: number; totalPages: number }>('/history', params);

    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++;
    fetchHistoryList(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()}`;
}

// 初始化
onMounted(async () => {
  await fetchHistoryList();
});
</script>

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

.search-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  padding-top: env(safe-area-inset-top);
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  display: flex;
  align-items: center;
  padding-left: 24rpx;
  padding-right: 24rpx;
  z-index: 100;
}

.search-inner {
  flex: 1;
  height: 64rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
}

.search-icon {
  font-size: 28rpx;
  margin-right: 12rpx;
}

.search-placeholder {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
}

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

.tab-scroll {
  width: 100%;
  white-space: nowrap;
}

.tab-list {
  display: inline-flex;
  gap: 16rpx;
  padding: 16rpx 24rpx;
}

.tab-item {
  padding: 12rpx 32rpx;
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
  position: relative;
}

.tab-item.active {
  color: #4f46e5;
  font-weight: 600;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background: #4f46e5;
  border-radius: 3rpx;
}

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

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

.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;
}
</style>
