<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 v-if="loading && !album" class="skeleton-container">
      <view class="skeleton-cover"></view>
      <view class="skeleton-info">
        <view class="skeleton-title"></view>
        <view class="skeleton-desc"></view>
      </view>
    </view>

    <!-- 专辑信息 -->
    <view v-else-if="album" class="album-header">
      <view class="album-cover" :style="{ background: getCoverGradient() }">
        <text class="cover-icon">🎵</text>
      </view>
      <view class="album-info">
        <text class="album-title">{{ album.name }}</text>
        <text class="album-meta">{{ album.subscriberCount || 0 }}人订阅 · {{ audioList.length }}个音频</text>
        <text class="album-desc">{{ album.description || '暂无描述' }}</text>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view v-if="album" class="action-bar">
      <button class="action-btn" :class="{ subscribed: isSubscribed }" @click="toggleSubscribe">
        <text>{{ isSubscribed ? '已订阅' : '订阅' }}</text>
      </button>
      <button class="action-btn primary" @click="playAll">
        <text>播放全部</text>
      </button>
    </view>

    <!-- 音频列表 -->
    <view v-if="!loading" class="audio-section">
      <text class="section-title">音频列表</text>
      <view v-if="audioList.length === 0" class="empty">
        <text class="empty-icon">🎵</text>
        <text class="empty-text">暂无音频</text>
      </view>
      <view v-else class="audio-list">
        <view
          v-for="(item, index) in audioList"
          :key="item.id"
          class="audio-item"
          @click="playAudio(item, index)"
        >
          <view class="audio-index">{{ index + 1 }}</view>
          <view class="audio-content">
            <text class="audio-title">{{ item.title }}</text>
            <text class="audio-meta">{{ formatDuration(item.audioDuration) }} · {{ item.wordCount }}字</text>
          </view>
          <view class="audio-play">
            <text class="play-icon">▶</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useAudioStore } from '../../store/audio';
import { get, post, del } from '../../utils/request';

interface Album {
  id: number;
  name: string;
  description?: string;
  coverUrl?: string;
  subscriberCount: number;
}

interface AudioItem {
  id: number;
  title: string;
  audioDuration: number;
  wordCount: number;
  audioUrl: string;
}

const audioStore = useAudioStore();

const albumId = ref('');
const album = ref<Album | null>(null);
const audioList = ref<AudioItem[]>([]);
const loading = ref(false);
const isSubscribed = ref(false);

const userId = 1; // TODO: 从用户 store 获取

// 获取封面渐变色
function getCoverGradient(): string {
  return 'linear-gradient(135deg, #4f46e5 0%, #818cf8 100%)';
}

// 格式化时长
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 goBack() {
  uni.navigateBack();
}

// 加载专辑详情
async function fetchAlbumDetail() {
  loading.value = true;
  try {
    const result = await get<Album>(`/albums/${albumId.value}`);
    album.value = result;

    // 检查是否已订阅
    const subResult = await get<any>(`/albums/${albumId.value}/check-subscribe?userId=${userId}`);
    isSubscribed.value = subResult?.isSubscribed || false;
  } catch (error) {
    console.error('获取专辑详情失败:', error);
    uni.showToast({ title: '获取专辑详情失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

// 加载专辑音频列表
async function fetchAudioList() {
  try {
    const result = await get<AudioItem[]>(`/albums/${albumId.value}/audios`);
    audioList.value = result || [];
  } catch (error) {
    console.error('获取音频列表失败:', error);
  }
}

// 切换订阅状态
async function toggleSubscribe() {
  try {
    if (isSubscribed.value) {
      await del(`/albums/${albumId.value}/subscribe?userId=${userId}`);
      isSubscribed.value = false;
      uni.showToast({ title: '已取消订阅', icon: 'success' });
    } else {
      await post(`/albums/${albumId.value}/subscribe`, { userId });
      isSubscribed.value = true;
      uni.showToast({ title: '订阅成功', icon: 'success' });
    }
  } catch (error) {
    console.error('订阅操作失败:', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
}

// 播放全部
function playAll() {
  if (audioList.value.length > 0) {
    audioStore.setPlaylist(audioList.value as any, 0, true);
    playAudio(audioList.value[0], 0);
  }
}

// 播放音频
function playAudio(item: AudioItem, index: number) {
  audioStore.setPlaylist(audioList.value as any, index, true);
  audioStore.play(item as any);
  uni.navigateTo({ url: `/pages/player/index?id=${item.id}` });
}

// 页面加载
onLoad(async (options: any) => {
  albumId.value = options?.id || '';
  if (albumId.value) {
    await fetchAlbumDetail();
    await fetchAudioList();
  }
});

onMounted(() => {
  if (!albumId.value) {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1] as any;
    albumId.value = currentPage?.options?.id || '';
    if (albumId.value) {
      fetchAlbumDetail();
      fetchAudioList();
    }
  }
});
</script>

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

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44rpx 32rpx 24rpx;
  background: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
}

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

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

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

/* 骨架屏 */
.skeleton-container {
  padding: 32rpx;
}

.skeleton-cover {
  width: 240rpx;
  height: 240rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 16rpx;
  margin: 0 auto 32rpx;
}

.skeleton-info {
  text-align: center;
}

.skeleton-title {
  height: 40rpx;
  width: 60%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8rpx;
  margin: 0 auto 16rpx;
}

.skeleton-desc {
  height: 24rpx;
  width: 80%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8rpx;
  margin: 0 auto;
}

@keyframes shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* 专辑信息 */
.album-header {
  padding: 32rpx;
  background: #ffffff;
  display: flex;
  gap: 32rpx;
}

.album-cover {
  width: 240rpx;
  height: 240rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

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

.album-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}

.album-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 12rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.album-meta {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
}

.album-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 操作按钮 */
.action-bar {
  display: flex;
  gap: 24rpx;
  padding: 24rpx 32rpx;
  background: #ffffff;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 40rpx;
  border: none;
  font-size: 28rpx;
  color: #333;
}

.action-btn.primary {
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  color: #ffffff;
}

.action-btn.subscribed {
  background: #f0f0f0;
  color: #999;
}

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

/* 音频列表 */
.audio-section {
  margin-top: 16rpx;
  padding: 24rpx 32rpx;
  background: #ffffff;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
  display: block;
}

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

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 16rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.audio-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.audio-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx;
  background: #f9f9f9;
  border-radius: 12rpx;
}

.audio-index {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e5e7eb;
  border-radius: 50%;
  font-size: 24rpx;
  color: #666;
  flex-shrink: 0;
}

.audio-content {
  flex: 1;
  min-width: 0;
}

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

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

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

.play-icon {
  font-size: 24rpx;
  color: #ffffff;
  margin-left: 4rpx;
}
</style>
