<template>
  <view class="page">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-inner">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          v-model="searchKeyword"
          placeholder="搜索历史记录..."
          @confirm="handleSearch"
          @clear="handleClearSearch"
        />
        <text v-if="searchKeyword" class="clear-btn" @click="handleClearSearch">✕</text>
      </view>
    </view>

    <!-- 编辑栏 -->
    <view class="edit-bar">
      <view v-if="!isEditing" class="edit-btn" @click="isEditing = true">
        <text>编辑</text>
      </view>
      <view v-else class="edit-actions">
        <view class="action-btn" @click="toggleSelectAll">
          <text>{{ isAllSelected ? '取消全选' : '全选' }}</text>
        </view>
        <view class="action-btn download" @click="handleBatchDownload" :disabled="selectedIds.length === 0">
          <text>下载 ({{ selectedIds.length }})</text>
        </view>
        <view class="action-btn delete" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          <text>删除 ({{ selectedIds.length }})</text>
        </view>
        <view class="action-btn cancel" @click="cancelEdit">
          <text>取消</text>
        </view>
      </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 class="group-toggle" @click="groupByBook = !groupByBook">
        <text class="group-toggle-text">{{ groupByBook ? '📋 列表' : '📚 聚合' }}</text>
      </view>
    </view>

    <!-- 音频列表 -->
    <scroll-view scroll-y class="audio-list" @scrolltolower="loadMore" :scroll-top="scrollTop">
      <!-- 骨架屏加载状态 -->
      <SkeletonList v-if="loading && audioList.length === 0" layout="history" :count="6" />

      <!-- 空状态 -->
      <view v-else-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-if="groupByBook" v-for="group in displayList" :key="group._id" class="group-card">
          <view class="group-header" @click="goToBookDetail(group.bookId)">
            <text class="group-title">{{ group.bookId ? '📖 书籍 #' + group.bookId : '🎵 其他音频' }}</text>
            <text class="group-count">{{ group.items.length }} 个音频 · {{ formatDuration(group.totalDuration) }}</text>
          </view>
          <view
            v-for="item in group.items"
            :key="item._id"
            class="audio-card group-item"
            :class="{ selected: selectedIds.includes(item._id) }"
            @click="isEditing ? toggleSelect(item._id) : playAudio(item)"
          >
            <view v-if="isEditing" class="checkbox">
              <text>{{ selectedIds.includes(item._id) ? '✓' : '' }}</text>
            </view>
            <view class="audio-cover-mini" :style="{ background: getCoverGradient(item.voiceId) }">
              <text class="cover-icon-small">{{ getTitleLetter(item.title) }}</text>
            </view>
            <view class="audio-info">
              <text class="audio-title">{{ item.title }}</text>
              <text class="audio-meta">{{ item.wordCount }}字 · {{ formatDuration(item.audioDuration) }}</text>
            </view>
          </view>
        </view>
        <!-- 列表模式 -->
        <template v-else>
        <view
          v-for="item in audioList"
          :key="item._id"
          class="audio-card"
          :class="{ selected: selectedIds.includes(item._id) }"
          @click="isEditing ? toggleSelect(item._id) : playAudio(item)"
        >
          <view v-if="isEditing" class="checkbox">
            <text>{{ selectedIds.includes(item._id) ? '✓' : '' }}</text>
          </view>
          <view class="audio-cover" :style="{ background: getCoverGradient(item.voiceId) }">
            <text class="cover-letter">{{ getTitleLetter(item.title) }}</text>
            <text class="cover-title-small">{{ item.title }}</text>
            <view class="play-overlay">
              <text class="play-icon">▶</text>
            </view>
          </view>
          <view class="audio-info">
            <text class="audio-title">{{ item.title }}</text>
            <view class="audio-progress-row">
              <view class="mini-progress-bar">
                <view class="mini-progress-fill" :style="{ width: (item.progress || 0) + '%' }"></view>
              </view>
              <text class="audio-meta">{{ item.wordCount }}字 · {{ formatDuration(item.audioDuration) }}</text>
            </view>
            <text class="audio-date">{{ formatDate(item.createdAt) }}</text>
          </view>
          <view class="publish-btn" @click.stop="publishAudio(item)" v-if="!isEditing">
            <text class="publish-icon">🚀</text>
          </view>
        </view>
        </template>
      </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, computed, onMounted, nextTick } from 'vue';
import { useAudioStore } from '../../store/audio';
import { get, post, getFullUrl } from '../../utils/request';
import { getBatchDownloadUrls } from '../../api/download';
import type { AudioItem } from '../../types';
import SkeletonList from '../../components/SkeletonList.vue';
import { getCoverGradient, getTitleLetter, getBookGradient } from '../../composables/useCoverStyle';

const audioStore = useAudioStore();

// 编辑模式状态
const isEditing = ref(false);
const selectedIds = ref<string[]>([]);
const isAllSelected = ref(false);

// 搜索状态
const searchKeyword = ref('');
const isSearching = ref(false);

// scroll-top 用于避免 scrollTop 错误
const scrollTop = ref(0);

// 标签状态
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 groupByBook = ref(false);

// 分组后的列表
const groupedAudioList = computed(() => {
  if (!groupByBook.value) return null;
  const groups: Record<string, { bookId: number; items: AudioItem[]; totalDuration: number }> = {};
  audioList.value.forEach(item => {
    const key = item.bookId ? `book_${item.bookId}` : 'other';
    if (!groups[key]) {
      groups[key] = { bookId: item.bookId || 0, items: [], totalDuration: 0 };
    }
    groups[key].items.push(item);
    groups[key].totalDuration += item.audioDuration || 0;
  });
  return Object.values(groups);
});

// 用于展示的列表（根据分组模式切换）
const displayList = computed(() => {
  if (groupByBook.value && groupedAudioList.value) {
    return groupedAudioList.value.map(g => ({
      _id: `group_${g.bookId || 'other'}`,
      isGroup: true,
      bookId: g.bookId,
      items: g.items,
      totalDuration: g.totalDuration,
      title: g.bookId ? `书籍 #${g.bookId}` : '其他音频',
    } as any));
  }
  return audioList.value;
});



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

// 切换选择
function toggleSelect(id: string) {
  const index = selectedIds.value.indexOf(id);
  if (index > -1) {
    selectedIds.value.splice(index, 1);
  } else {
    selectedIds.value.push(id);
  }
  isAllSelected.value = selectedIds.value.length === audioList.value.length;
}

// 全选/取消全选
function toggleSelectAll() {
  if (isAllSelected.value) {
    selectedIds.value = [];
  } else {
    selectedIds.value = audioList.value.map(item => item._id);
  }
  isAllSelected.value = !isAllSelected.value;
}

// 取消编辑
function cancelEdit() {
  isEditing.value = false;
  selectedIds.value = [];
  isAllSelected.value = false;
}

// 批量删除
async function handleBatchDelete() {
  if (selectedIds.value.length === 0) return;

  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await post('/history/batch-delete', { ids: selectedIds.value });
          uni.showToast({ title: '删除成功', icon: 'success' });
          await fetchHistoryList();
          cancelEdit();
        } catch (error) {
          uni.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    },
  });
}

// 批量下载
async function handleBatchDownload() {
  if (selectedIds.value.length === 0) return;

  try {
    uni.showLoading({ title: '准备下载...', mask: true });
    
    const result = await getBatchDownloadUrls(selectedIds.value);
    
    uni.hideLoading();
    
    if (!result || result.audios.length === 0) {
      uni.showToast({ title: '没有可下载的音频', icon: 'none' });
      return;
    }

    // 确认下载
    uni.showModal({
      title: '确认下载',
      content: `将下载 ${result.audios.length} 个音频文件`,
      success: async (res) => {
        if (res.confirm) {
          // 逐个下载
          let successCount = 0;
          let failCount = 0;
          
          for (const audio of result.audios) {
            try {
              await new Promise<void>((resolve, reject) => {
                uni.downloadFile({
                  url: getFullUrl(audio.downloadUrl),
                  success: (downloadRes) => {
                    if (downloadRes.statusCode === 200) {
                      successCount++;
                      resolve();
                    } else {
                      failCount++;
                      reject(new Error('下载失败'));
                    }
                  },
                  fail: () => {
                    failCount++;
                    reject(new Error('下载失败'));
                  },
                });
              });
            } catch (error) {
              console.error(`下载失败: ${audio.title}`, error);
            }
          }
          
          // 显示结果
          uni.showModal({
            title: '下载完成',
            content: `成功: ${successCount} 个\n失败: ${failCount} 个`,
            showCancel: false,
          });
          
          cancelEdit();
        }
      },
    });
  } catch (error) {
    uni.hideLoading();
    console.error('[BatchDownload] 批量下载失败:', error);
    uni.showToast({ title: '下载失败', icon: 'none' });
  }
}

// 搜索功能
function handleSearch() {
  isSearching.value = true;
  page.value = 1;
  fetchHistoryList();
}

function handleClearSearch() {
  searchKeyword.value = '';
  isSearching.value = false;
  page.value = 1;
  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;
    }
    
    // 添加搜索关键字
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }

    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 & { bookId?: number }) {
  // 独立音频跳转到书籍详情
  if (item.bookId) {
    uni.navigateTo({ url: `/pages/book-generator/detail?id=${item.bookId}` });
  } else {
    // 兜底：跳转到播放器（需要数字ID）
    uni.showToast({ title: '音频信息不完整', icon: 'none' });
  }
}

// 发布音频
function publishAudio(item: AudioItem) {
  uni.navigateTo({ url: `/pages/publish/index?audioId=${item._id}` });
}

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

// 跳转书籍详情
function goToBookDetail(bookId: number) {
  if (bookId) {
    uni.navigateTo({ url: `/pages/book-generator/detail?id=${bookId}` });
  }
}

// 格式化日期
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-input {
  flex: 1;
  font-size: 28rpx;
  color: white;
}

.clear-btn {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.8);
  padding: 0 8rpx;
}

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

.edit-bar {
  position: fixed;
  top: 100rpx;
  left: 0;
  right: 0;
  z-index: 98;
  background: #ffffff;
  padding: 16rpx 24rpx;
  display: flex;
  justify-content: flex-end;
  border-bottom: 1rpx solid #f3f4f6;
}

.edit-btn {
  padding: 12rpx 24rpx;
  background: #4f46e5;
  color: white;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.edit-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  padding: 12rpx 24rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.action-btn.delete {
  background: #ef4444;
  color: white;
}

.action-btn.delete[disabled] {
  opacity: 0.5;
}

.action-btn.download {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.action-btn.download[disabled] {
  opacity: 0.5;
}

.action-btn.cancel {
  background: #f3f4f6;
  color: #374151;
}

.tab-bar {
  position: fixed;
  top: 168rpx;
  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: 240rpx;
  height: calc(100vh - 240rpx);
}

.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);
  position: relative;
}

.audio-card.selected {
  background: #eff6ff;
  border: 2rpx solid #4f46e5;
}

.checkbox {
  position: absolute;
  top: 16rpx;
  left: 16rpx;
  width: 48rpx;
  height: 48rpx;
  background: #4f46e5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28rpx;
  z-index: 10;
}

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

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

/* 文字海报风格封面 */
.cover-letter {
  position: absolute;
  top: -10rpx;
  left: 12rpx;
  font-size: 140rpx;
  font-weight: 900;
  color: rgba(255, 255, 255, 0.12);
  line-height: 1;
  pointer-events: none;
}

.cover-title-small {
  position: absolute;
  bottom: 40rpx;
  left: 16rpx;
  right: 16rpx;
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.85);
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

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

.publish-btn {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  width: 56rpx;
  height: 56rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.4);
  z-index: 10;
}

.publish-icon {
  font-size: 28rpx;
}

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

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

/* 分组切换按钮 */
.group-toggle {
  padding: 12rpx 24rpx;
  display: flex;
  align-items: center;
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(79, 70, 229, 0.08);
  border-radius: 32rpx;
  border: 1rpx solid rgba(79, 70, 229, 0.2);
}

.group-toggle-text {
  font-size: 24rpx;
  color: #4f46e5;
  white-space: nowrap;
}

/* 分组卡片 */
.group-card {
  width: 100%;
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.group-header {
  padding: 24rpx;
  background: linear-gradient(135deg, #f0f0ff 0%, #faf5ff 100%);
  border-bottom: 1rpx solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.group-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
}

.group-count {
  font-size: 22rpx;
  color: #9ca3af;
}

/* 分组内音频卡片 */
.group-item {
  width: 100%;
  border-radius: 0;
  box-shadow: none;
  margin-bottom: 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 16rpx 24rpx;
  border-bottom: 1rpx solid #f3f4f6;
}

.group-item:last-child {
  border-bottom: none;
}

.group-item .checkbox {
  position: relative;
  top: auto;
  left: auto;
  margin-right: 16rpx;
  flex-shrink: 0;
}

/* 分组模式小封面 */
.audio-cover-mini {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-right: 20rpx;
}

.cover-icon-small {
  font-size: 36rpx;
}

/* 进度条样式 */
.audio-progress-row {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  margin-bottom: 4rpx;
}

.mini-progress-bar {
  width: 100%;
  height: 6rpx;
  background: #e5e7eb;
  border-radius: 3rpx;
  overflow: hidden;
}

.mini-progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4f46e5 0%, #7c3aed 100%);
  border-radius: 3rpx;
  transition: width 0.3s ease;
}

/* 日期标签 */
.audio-date {
  font-size: 20rpx;
  color: #9ca3af;
  margin-top: 4rpx;
}

/* 分组模式下音频信息 */
.group-item .audio-info {
  flex: 1;
  min-width: 0;
  padding: 0;
}

.group-item .audio-title {
  font-size: 26rpx;
  margin-bottom: 4rpx;
}
</style>
