<template>
  <view class="page">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-info">
        <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 class="user-text">
          <text class="nickname">{{ userStore.userInfo?.nickname || '未登录' }}</text>
          <view class="member-badge" :class="memberClass">
            <text class="member-text">{{ memberText }}</text>
          </view>
        </view>
      </view>

      <!-- 使用统计 -->
      <view class="stats-row" v-if="userStore.memberStatus">
        <view class="stat-item">
          <text class="stat-value">{{ userStore.memberStatus.quota.dailyRemaining }}</text>
          <text class="stat-label">今日剩余次数</text>
        </view>
        <view class="stat-divider" />
        <view class="stat-item">
          <text class="stat-value">{{ userStore.memberStatus.quota.wordLimit === 0 ? '∞' : userStore.memberStatus.quota.wordLimit }}</text>
          <text class="stat-label">单次字数上限</text>
        </view>
      </view>
    </view>

    <!-- 今日创作概况 -->
    <view class="today-card" v-if="userStore.isLoggedIn">
      <view class="today-header">
        <text class="today-title">今日创作概况</text>
        <text class="today-date">{{ todayDate }}</text>
      </view>
      <view class="today-stats">
        <view class="today-stat-item">
          <text class="today-stat-value">{{ todayStats.audioCount }}</text>
          <text class="today-stat-label">生成音频</text>
        </view>
        <view class="today-stat-divider" />
        <view class="today-stat-item">
          <text class="today-stat-value">{{ todayStats.bookCount }}</text>
          <text class="today-stat-label">生成书籍</text>
        </view>
        <view class="today-stat-divider" />
        <view class="today-stat-item">
          <text class="today-stat-value">{{ todayStats.usageQuota }}</text>
          <text class="today-stat-label">使用额度</text>
        </view>
      </view>
    </view>

    <!-- 最近的创作 -->
    <view class="recent-card" v-if="recentCreations.length > 0">
      <view class="recent-header">
        <text class="recent-title">最近的创作</text>
        <text class="recent-more" @click="goHistory">查看更多 ›</text>
      </view>
      <view class="recent-list">
        <view
          v-for="item in recentCreations"
          :key="item._id"
          class="recent-item"
          hover-class="recent-item-hover"
          @click="goToDetail(item)"
        >
          <view class="recent-cover" :style="{ background: getCoverGradient(item.voiceId) }">
            <text class="cover-letter">{{ getTitleLetter(item.title) }}</text>
            <text class="cover-title-small">{{ item.title }}</text>
          </view>
          <view class="recent-info">
            <text class="recent-title-text">{{ item.title }}</text>
            <text class="recent-meta">{{ item.wordCount }}字 · {{ formatDate(item.createdAt) }}</text>
          </view>
          <text class="recent-arrow">›</text>
        </view>
      </view>
    </view>

    <!-- 升级会员推广卡片 -->
    <view class="upgrade-card" v-if="userStore.isLoggedIn && !userStore.isMember" @click="goMember">
      <view class="upgrade-left">
        <text class="upgrade-icon">👑</text>
        <view class="upgrade-text">
          <text class="upgrade-title">升级会员</text>
          <text class="upgrade-desc">解锁更多创作次数和高级音色</text>
        </view>
      </view>
      <text class="upgrade-btn">立即开通</text>
    </view>

    <!-- 功能入口 -->
    <view class="menu-section">
      <view class="menu-item" @click="goBookGenerator">
        <text class="menu-icon">📖</text>
        <text class="menu-text">书籍生成</text>
        <text class="menu-tag">新功能</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goMember">
        <text class="menu-icon">👑</text>
        <text class="menu-text">会员中心</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goSettings">
        <text class="menu-icon">⚙️</text>
        <text class="menu-text">设置</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goTokenPacks">
        <text class="menu-icon">🎁</text>
        <text class="menu-text">购买 Token 包</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goInvite">
        <text class="menu-icon">🎁</text>
        <text class="menu-text">邀请好友 · 双方得10分钟</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goBilling">
        <text class="menu-icon">💰</text>
        <text class="menu-text">消费账单</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goHistory">
        <text class="menu-icon">📜</text>
        <text class="menu-text">历史记录</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="showAbout">
        <text class="menu-icon">ℹ️</text>
        <text class="menu-text">关于我们</text>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="showFeedback">
        <text class="menu-icon">💬</text>
        <text class="menu-text">意见反馈</text>
        <text class="menu-arrow">›</text>
      </view>
    </view>

    <!-- 退出登录 -->
    <view class="logout-section" v-if="userStore.isLoggedIn">
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>
  </view>
</template>

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

const userStore = useUserStore();

// 今日创作概况
const todayStats = ref({
  audioCount: 0,
  bookCount: 0,
  usageQuota: 0
});

// 最近的创作
const recentCreations = ref<AudioItem[]>([]);

// 今日日期
const todayDate = computed(() => {
  const now = new Date();
  return `${now.getMonth() + 1}月${now.getDate()}日`;
});

// 计算属性
const memberClass = computed(() => {
  const level = userStore.memberStatus?.level || 0;
  return `level-${level}`;
});

const memberText = computed(() => {
  return userStore.memberStatus?.levelName || '免费用户';
});

// 获取今日创作概况
async function fetchTodayStats() {
  try {
    const now = new Date();
    const startDate = new Date(now.setHours(0, 0, 0, 0)).toISOString();

    // 获取今日音频数
    const audioResult = await get<{ list: AudioItem[]; total: number }>('/history', {
      startDate,
      pageSize: 100
    });

    // 获取今日书籍数（从书籍生成记录获取）
    let bookCount = 0;
    try {
      const bookResult = await get<{ list: any[]; total: number }>('/book-generator/list', {
        startDate,
        pageSize: 100
      });
      bookCount = bookResult.total || 0;
    } catch (e) {
      // 书籍接口可能不存在
      console.log('[Mine] 书籍接口不存在', e);
    }

    todayStats.value = {
      audioCount: audioResult.total || 0,
      bookCount,
      usageQuota: userStore.memberStatus?.quota.dailyRemaining || 0
    };
  } catch (error) {
    console.log('[Mine] 获取今日概况失败', error);
  }
}

// 获取最近的创作
async function fetchRecentCreations() {
  try {
    const result = await get<{ list: AudioItem[]; total: number }>('/history', {
      pageSize: 3,
      sortBy: 'createdAt',
      sortOrder: 'desc'
    });
    recentCreations.value = (result.list || []).slice(0, 3);
  } catch (error) {
    console.log('[Mine] 获取最近创作失败', error);
  }
}


// 格式化日期
function formatDate(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const oneDay = 24 * 60 * 60 * 1000;

  if (diff < oneDay) return '今天';
  if (diff < 2 * oneDay) return '昨天';
  return `${date.getMonth() + 1}/${date.getDate()}`;
}

// 跳转到历史记录页
function goToDetail(item: AudioItem) {
  uni.navigateTo({ url: '/pages/history/index' });
}

// 页面显示
onShow(() => {
  if (userStore.isLoggedIn) {
    userStore.fetchMemberStatus();
    fetchTodayStats();
    fetchRecentCreations();
  } else {
    // 未登录，跳转到登录页
    uni.navigateTo({ url: '/pages/login/index' });
  }
});

// 跳转会员页
function goMember() {
  uni.navigateTo({ url: '/pages/member/index' });
}

// 跳转设置页
function goSettings() {
  uni.navigateTo({ url: '/pages/settings/index' });
}

// 跳转日志监控页
function goLogs() {
  uni.navigateTo({ url: '/pages/logs/index' });
}

// 跳转 Token 包购买
function goTokenPacks() {
  uni.navigateTo({ url: '/pages/token-packs/index' });
}

// 跳转邀请页
function goInvite() {
  uni.navigateTo({ url: '/pages/invite/index' });
}

// 跳转消费账单
function goBilling() {
  uni.navigateTo({ url: '/pages/billing/index' });
}

// 跳转历史页
function goHistory() {
  uni.switchTab({ url: '/pages/history/index' });
}

// 跳转书籍生成页
function goBookGenerator() {
  uni.switchTab({ url: '/pages/book-generator/index' });
}

// 关于我们
function showAbout() {
  uni.showModal({
    title: '关于声工坊',
    content: '声工坊是一款智能文本转语音工具，帮助您轻松制作高质量音频内容。\n\n版本: 1.0.0',
    showCancel: false,
  });
}

// 意见反馈
function showFeedback() {
  uni.showModal({
    title: '意见反馈',
    content: '如有问题或建议，请联系客服：\n邮箱：support@example.com',
    showCancel: false,
  });
}

// 退出登录
function handleLogout() {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        userStore.logout();
        uni.showToast({ title: '已退出登录', icon: 'success' });
        // 关闭所有页面，打开登录页
        uni.reLaunch({ url: '/pages/login/index' });
      }
    },
  });
}
</script>

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

/* 夜间模式适配 */
@media (prefers-color-scheme: dark) {
  .page {
    background: #1a1a2e;
  }
}

.user-card {
  margin: 32rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(79, 70, 229, 0.3);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
}

.avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.avatar-placeholder {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.avatar-text {
  font-size: 48rpx;
}

.user-text {
  margin-left: 24rpx;
}

.nickname {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 8rpx;
}

.member-badge {
  display: inline-block;
  padding: 4rpx 16rpx;
  border-radius: 16rpx;
  background: rgba(255, 255, 255, 0.2);
}

.member-badge.level-1 {
  background: linear-gradient(135deg, #f97316 0%, #fb923c 100%);
}

.member-badge.level-2 {
  background: linear-gradient(135deg, #fbbf24 0%, #fcd34d 100%);
}

.member-text {
  font-size: 22rpx;
  color: #ffffff;
}

.stats-row {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  padding: 24rpx;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 40rpx;
  font-weight: 700;
  color: #ffffff;
}

.stat-label {
  display: block;
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 4rpx;
}

.stat-divider {
  width: 2rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.2);
}

/* 今日创作概况卡片 */
.today-card {
  margin: 0 32rpx 24rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

@media (prefers-color-scheme: dark) {
  .today-card {
    background: #2d2d44;
  }
}

.today-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

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

@media (prefers-color-scheme: dark) {
  .today-title {
    color: #f9fafb;
  }
}

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

.today-stats {
  display: flex;
  align-items: center;
}

.today-stat-item {
  flex: 1;
  text-align: center;
}

.today-stat-value {
  display: block;
  font-size: 44rpx;
  font-weight: 700;
  color: #4f46e5;
}

@media (prefers-color-scheme: dark) {
  .today-stat-value {
    color: #818cf8;
  }
}

.today-stat-label {
  display: block;
  font-size: 22rpx;
  color: #6b7280;
  margin-top: 4rpx;
}

@media (prefers-color-scheme: dark) {
  .today-stat-label {
    color: #9ca3af;
  }
}

.today-stat-divider {
  width: 2rpx;
  height: 60rpx;
  background: #e5e7eb;
}

@media (prefers-color-scheme: dark) {
  .today-stat-divider {
    background: #374151;
  }
}

/* 最近的创作卡片 */
.recent-card {
  margin: 0 32rpx 24rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

@media (prefers-color-scheme: dark) {
  .recent-card {
    background: #2d2d44;
  }
}

.recent-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

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

@media (prefers-color-scheme: dark) {
  .recent-title {
    color: #f9fafb;
  }
}

.recent-more {
  font-size: 24rpx;
  color: #4f46e5;
}

@media (prefers-color-scheme: dark) {
  .recent-more {
    color: #818cf8;
  }
}

.recent-list {
  display: flex;
  flex-direction: column;
}

.recent-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f3f4f6;
}

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

.recent-item-hover {
  background-color: #f3f4f6;
  border-radius: 8rpx;
}

@media (prefers-color-scheme: dark) {
  .recent-item {
    border-bottom-color: #374151;
  }
  .recent-item-hover {
    background-color: #374151;
  }
  .recent-item:last-child {
    border-bottom: none;
  }
}

.recent-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  position: relative;
  overflow: hidden;
}

.cover-letter {
  position: absolute;
  top: -8rpx;
  left: 4rpx;
  font-size: 60rpx;
  font-weight: 900;
  color: rgba(255, 255, 255, 0.15);
  line-height: 1;
  pointer-events: none;
}

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

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

.recent-info {
  flex: 1;
  margin-left: 20rpx;
  overflow: hidden;
}

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

@media (prefers-color-scheme: dark) {
  .recent-title-text {
    color: #f9fafb;
  }
}

.recent-meta {
  display: block;
  font-size: 22rpx;
  color: #9ca3af;
  margin-top: 4rpx;
}

.recent-arrow {
  font-size: 32rpx;
  color: #d1d5db;
  margin-left: 16rpx;
}

@media (prefers-color-scheme: dark) {
  .recent-arrow {
    color: #4b5563;
  }
}

/* 升级会员卡片 */
.upgrade-card {
  margin: 0 32rpx 24rpx;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-radius: 20rpx;
  padding: 28rpx 32rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4rpx 16rpx rgba(251, 191, 36, 0.2);
}

@media (prefers-color-scheme: dark) {
  .upgrade-card {
    background: linear-gradient(135deg, #92400e 0%, #78350f 100%);
  }
}

.upgrade-left {
  display: flex;
  align-items: center;
}

.upgrade-icon {
  font-size: 40rpx;
  margin-right: 16rpx;
}

.upgrade-text {
  display: flex;
  flex-direction: column;
}

.upgrade-title {
  display: block;
  font-size: 30rpx;
  font-weight: 600;
  color: #92400e;
}

@media (prefers-color-scheme: dark) {
  .upgrade-title {
    color: #fef3c7;
  }
}

.upgrade-desc {
  display: block;
  font-size: 22rpx;
  color: #b45309;
  margin-top: 4rpx;
}

@media (prefers-color-scheme: dark) {
  .upgrade-desc {
    color: #fde68a;
  }
}

.upgrade-btn {
  font-size: 24rpx;
  color: #ffffff;
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  padding: 12rpx 24rpx;
  border-radius: 24rpx;
  font-weight: 500;
}

/* 功能菜单 */
.menu-section {
  margin: 32rpx;
  background: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
}

@media (prefers-color-scheme: dark) {
  .menu-section {
    background: #2d2d44;
  }
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f3f4f6;
}

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

@media (prefers-color-scheme: dark) {
  .menu-item {
    border-bottom-color: #374151;
  }
  .menu-item:last-child {
    border-bottom: none;
  }
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 24rpx;
}

.menu-text {
  flex: 1;
  font-size: 30rpx;
  color: #1f2937;
}

@media (prefers-color-scheme: dark) {
  .menu-text {
    color: #f9fafb;
  }
}

.menu-tag {
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  background: linear-gradient(135deg, #f97316 0%, #fb923c 100%);
  color: #ffffff;
  border-radius: 8rpx;
  margin-right: 16rpx;
}

.menu-arrow {
  font-size: 32rpx;
  color: #9ca3af;
}

@media (prefers-color-scheme: dark) {
  .menu-arrow {
    color: #6b7280;
  }
}

.logout-section {
  margin: 48rpx 32rpx;
}

.logout-btn {
  width: 100%;
  height: 88rpx;
  background: #ffffff;
  border-radius: 16rpx;
  border: 2rpx solid #ef4444;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.logout-btn text {
  font-size: 30rpx;
  color: #ef4444;
}

@media (prefers-color-scheme: dark) {
  .logout-btn {
    background: #2d2d44;
  }
}
</style>
