  <template>
  <div class="subscription-page">
    <SidebarNav active="subscription" />
    
    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部导航栏 -->
      <TopHeader ref="topHeaderRef" @avatar-click="showUserMenu = !showUserMenu" />

      <template v-if="currentSection === 'works'">
        <MyWorks />
      </template>
      <template v-else>
        <!-- 顶部 两层合并为一个盒子 -->
        <section class="top-merged-card">
          <!-- 上层：用户信息 + 右侧按钮 -->
          <div class="row-top">
            <div class="user-left">
              <div class="avatar-wrap">
                <img src="/images/backgrounds/avatar-default.svg" :alt="$t('subscription.userAvatar')" class="avatar-image" />
              </div>
              <div class="user-meta">
                <div class="username">{{ userInfo.email || t('subscription.loading') }}</div>
              </div>
            </div>
            <div class="user-right">
              <div class="points-pill">
                <div class="star-icon">
                  <StarOutlined />
                </div>
                <span>{{ userStore.availablePoints }}</span>
              </div>
              <button class="mini-btn" @click="goToOrderDetails">{{ $t('subscription.pointsDetails') }}</button>
              <button class="mini-btn" @click="goToWorks">{{ $t('profile.myWorks') }}</button>
            </div>
          </div>
          <!-- 下层：三项总结 -->
          <div class="row-bottom">
            <div class="summary-item">
              <div class="summary-label">{{ $t('subscription.currentActivePlan') }}</div>
              <div class="summary-value">{{ subscriptionInfo.currentPlan || $t('members.freeMember') }}</div>
            </div>
            <div class="divider-v"></div>
            <div class="summary-item">
              <div class="summary-label">{{ $t('subscription.expiryTime') }}</div>
              <div class="summary-value">{{ subscriptionInfo.expiryTime || t('subscription.permanent') }}</div>
            </div>
            <div class="divider-v"></div>
            <div class="summary-item">
              <div class="summary-label">{{ $t('subscription.remainingPoints') }}</div>
              <div class="summary-value highlight">
                <div class="star-icon">
                  <StarOutlined />
                </div>
                <span class="points-number">{{ userStore.availablePoints }}</span>
              </div>
            </div>
          </div>
        </section>

        <!-- 套餐选择 -->
        <section class="subscription-packages">
          <h3 class="section-title">{{ $t('subscription.plans') }}</h3>

          <div class="packages-grid">
            <!-- 入门版 -->
            <div class="package-card starter-card" :class="{ selected: selectedPlan === 'starter' }" @click="selectPlan('starter')">
              <div class="package-header">
                <h4 class="package-title">{{ $t('subscription.starter') }}</h4>
              </div>
              <div class="package-price">¥{{ formatPrice(membershipPrices.starter) }}/{{ Math.floor((membershipPoints.starter || 0) / 30) }}{{ $t('subscription.items') }}</div>
              <div class="points-box points-box-placeholder">&nbsp;</div>
              <button
                v-if="shouldShowCurrentPlan('starter')"
                class="package-button current"
                @click.stop="handleSubscribe('starter')"
              >
                {{ $t('subscription.currentPackage') }}
              </button>
              <button
                v-else
                class="package-button subscribe"
                @click.stop="handleSubscribe('starter')"
              >
                {{ $t('subscription.subscribe') }}
              </button>
              <div class="package-features">
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.includedPoints', { points: membershipPoints.starter || 0 }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.freeNewUserBonus') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.textToVideo30Points') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.imageToVideo30Points') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.storyboardImage30Points') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.storyboardVideo30Points') }}</span>
                </div>
              </div>
            </div>

            <!-- 标准版 -->
            <div class="package-card standard-card" :class="{ selected: selectedPlan === 'standard' }" @click="selectPlan('standard')">
              <div class="package-header">
                <h4 class="package-title">{{ $t('subscription.standard') }}</h4>
              </div>
              <div class="package-price">¥{{ formatPrice(membershipPrices.standard) }}/{{ Math.floor((membershipPoints.standard || 0) / 30) }}{{ $t('subscription.items') }}</div>
              <div class="points-box points-box-placeholder">&nbsp;</div>
              <button
                v-if="isCurrentPlan('standard')"
                class="package-button current"
                @click.stop="handleSubscribe('standard')"
              >
                {{ $t('subscription.currentPackage') }}
              </button>
              <button
                v-else
                class="package-button subscribe"
                @click.stop="handleSubscribe('standard')"
              >
                {{ $t('subscription.subscribe') }}
              </button>
              <div class="package-features">
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.includedPoints', { points: membershipPoints.standard || 0 }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.fastGeneration') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.commercialUse') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.pointsValidOneYear') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.maxTextToVideo', { count: Math.floor((membershipPoints.standard || 0) / 30) }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.maxImageToVideo', { count: Math.floor((membershipPoints.standard || 0) / 30) }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.maxStoryboardImage', { count: Math.floor((membershipPoints.standard || 0) / 30) }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.maxStoryboardVideo', { count: Math.floor((membershipPoints.standard || 0) / 30) }) }}</span>
                </div>
              </div>
            </div>

            <!-- 专业版 -->
            <div class="package-card premium-card" :class="{ selected: selectedPlan === 'premium' }" @click="selectPlan('premium')">
              <div class="package-header">
                <h4 class="package-title">{{ $t('subscription.professional') }}</h4>
                <div class="value-tag">{{ $t('subscription.bestValue') }}</div>
              </div>
              <div class="package-price">¥{{ formatPrice(membershipPrices.premium) }}/{{ Math.floor((membershipPoints.premium || 0) / 30) }}{{ $t('subscription.items') }}</div>
              <div class="points-box points-box-placeholder">&nbsp;</div>
              <button
                v-if="isCurrentPlan('premium')"
                class="package-button current"
                @click.stop="handleSubscribe('premium')"
              >
                {{ $t('subscription.currentPackage') }}
              </button>
              <button
                v-else
                class="package-button premium"
                @click.stop="handleSubscribe('premium')"
              >
                {{ $t('subscription.subscribe') }}
              </button>
              <div class="package-features">
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.includedPoints', { points: membershipPoints.premium || 0 }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.superFastGeneration') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.commercialUse') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.earlyAccess') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.pointsValidOneYear') }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.textToVideoItems', { count: Math.floor((membershipPoints.premium || 0) / 30) }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.imageToVideoItems', { count: Math.floor((membershipPoints.premium || 0) / 30) }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.storyboardImageTimes', { count: Math.floor((membershipPoints.premium || 0) / 30) }) }}</span>
                </div>
                <div class="feature-item">
                  <CheckOutlined class="check-icon" />
                  <span>{{ $t('subscription.storyboardVideoItems', { count: Math.floor((membershipPoints.premium || 0) / 30) }) }}</span>
                </div>
              </div>
            </div>
          </div>
        </section>
      </template>
    </main>

    <!-- 用户菜单下拉（管理员功能） -->
    <Teleport to="body">
      <div v-if="showUserMenu" class="user-menu-teleport" :style="menuStyle">
        <template v-if="userStore.isAdmin">
          <div class="menu-item" @click="goToDashboard">
            <UserOutlined />
            <span>{{ t('profile.dashboard') }}</span>
          </div>
          <div class="menu-item" @click="goToOrders">
            <FileOutlined />
            <span>{{ t('profile.orderManagement') }}</span>
          </div>
          <div class="menu-item" @click="goToMembers">
            <UserOutlined />
            <span>{{ t('profile.memberManagement') }}</span>
          </div>
          <div class="menu-item" @click="goToSettings">
            <SettingOutlined />
            <span>{{ t('profile.systemSettings') }}</span>
          </div>
          <div class="menu-item" @click="goToErrorStats">
            <WarningOutlined />
            <span>{{ $t('nav.errorStats') }}</span>
          </div>
          <div class="menu-item" @click="goToApiManagement">
            <FileOutlined />
            <span>{{ t('nav.apiManagement') }}</span>
          </div>
          <div class="menu-item" @click="goToTaskRecord">
            <FileOutlined />
            <span>{{ t('nav.tasks') }}</span>
          </div>
        </template>
        <!-- 修改密码 -->
        <div class="menu-item" @click.stop="goToChangePassword" style="cursor: pointer;">
          <LockOutlined />
          <span>{{ t('profile.changePassword') }}</span>
        </div>
        <div class="menu-item" @click="logout">
          <UserOutlined />
          <span>{{ t('common.logout') }}</span>
        </div>
      </div>
    </Teleport>

    <!-- 积分详情模态框 -->
    <a-modal
      v-model:open="pointsHistoryDialogVisible"
      :title="$t('subscription.pointsUsageHistory')"
      width="80%"
      class="points-history-dialog"
      :mask-closable="true"
      :keyboard="true"
      @cancel="handlePointsHistoryDialogClose"
    >
      <div class="points-history-content">
        <div class="points-summary">
          <h3>{{ $t('subscription.pointsUsageOverview') }}</h3>
          <div class="summary-stats">
            <div class="stat-item">
              <span class="stat-label">{{ $t('subscription.totalRecharge') }}：</span>
              <span class="stat-value positive">+{{ totalRecharge || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">{{ $t('subscription.totalConsumption') }}：</span>
              <span class="stat-value negative">{{ totalConsume || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">{{ $t('subscription.currentPoints') }}：</span>
              <span class="stat-value current">{{ userStore.availablePoints }}</span>
            </div>
          </div>
        </div>

        <div class="points-history-list" :spinning="pointsHistoryLoading">
          <div v-if="pointsHistory.length === 0 && !pointsHistoryLoading" class="empty-history">
            <p>{{ $t('subscription.noPointsHistory') }}</p>
          </div>
          <div class="history-item" v-for="(item, index) in pointsHistory" :key="index">
            <div class="history-header">
              <span class="history-type" :class="isRechargeType(item.type) ? 'recharge' : 'consume'">
                {{ mapPointsTypeToI18nKey(item.type) }}
              </span>
              <span class="history-points" :class="item.points > 0 ? 'positive' : 'negative'">
                {{ item.points > 0 ? '+' : '' }}{{ item.points }}
              </span>
            </div>
            <div class="history-details">
              <div class="history-info">
                <p><strong>{{ $t('subscription.description') }}：</strong>{{ item.description }}</p>
                <p><strong>{{ $t('subscription.time') }}：</strong>{{ formatDateTime(item.time) }}</p>
                <p v-if="item.orderNumber"><strong>{{ $t('subscription.orderNumber') }}：</strong>{{ item.orderNumber }}</p>
                <p v-if="item.taskId"><strong>{{ $t('subscription.taskId') }}：</strong>{{ item.taskId }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 支付模态框 -->
    <PaymentModal
      v-model="paymentModalVisible"
      :title="currentPaymentData.title"
      :amount="currentPaymentData.amount"
      :order-id="currentPaymentData.orderId"
      @pay-success="handlePaymentSuccess"
      @pay-error="handlePaymentError"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import axios from 'axios'
import MyWorks from '@/views/MyWorks.vue'
import PaymentModal from '@/components/PaymentModal.vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { UserOutlined, FileOutlined, PlayCircleOutlined, PictureOutlined, VideoCameraOutlined, CompassOutlined, StarOutlined, CheckOutlined, PlusOutlined, SettingOutlined, LockOutlined, WarningOutlined } from '@ant-design/icons-vue'
import { createPayment, createAlipayPayment, getUserSubscriptionInfo } from '@/api/payments'
import { getPointsHistory } from '@/api/points'
import { getMembershipLevels } from '@/api/members'
import { useUserStore } from '@/stores/user'
import TopHeader from '@/components/TopHeader.vue'
import SidebarNav from '@/components/SidebarNav.vue'

const { t } = useI18n()

const router = useRouter()
const userStore = useUserStore()

// 当前选中的区域（订阅或作品）
const currentSection = ref('subscription')

// 切换区域
const setSection = (section) => {
  currentSection.value = section
}

// 用户菜单状态
const showUserMenu = ref(false)
const topHeaderRef = ref(null)

// 计算用户菜单 Teleport 的位置
const menuStyle = computed(() => {
  const avatarEl = topHeaderRef.value?.avatarRef
  if (!avatarEl || !showUserMenu.value) return {}

  const rect = avatarEl.getBoundingClientRect()
  return {
    position: 'fixed',
    top: `${rect.bottom + 8}px`,
    right: `${window.innerWidth - rect.right}px`,
    zIndex: 99999
  }
})

// 用户信息和订阅信息
const userInfo = ref({
  username: '',
  userId: null,
  points: 0,
  frozenPoints: 0,
  email: '',
  nickname: ''
})

const subscriptionInfo = ref({
  currentPlan: t('members.freeMember'),
  expiryTime: t('subscription.permanent'),
  paidAt: null
})

// 套餐名称映射函数：直接返回后端的原始文本，不进行映射
// 这样可以区分“免费会员”和“入门会员”
const mapPlanNameToI18nKey = (planName) => {
  if (!planName || planName.trim() === '') return t('members.freeMember')
  
  // 直接返回后端返回的原始文本
  return planName
}

// 积分类型映射函数：将后端返回的中文类型映射到国际化key
const mapPointsTypeToI18nKey = (type) => {
  if (!type) return type

  if (type === '充值' || type.toLowerCase() === 'recharge') {
    return t('subscription.recharge')
  } else if (type === '消耗' || type.toLowerCase() === 'consume' || type.toLowerCase() === 'consumption') {
    return t('subscription.consume')
  }

  // 如果无法识别，返回原始值
  return type
}

// 检查类型是否为充值类型（用于CSS类）
const isRechargeType = (type) => {
  return type === '充值' || type.toLowerCase() === 'recharge'
}

// 会员等级价格配置（从API动态加载，禁止硬编码）
const membershipPrices = ref({
  starter: 0,
  standard: null,
  premium: null
})

// 会员等级积分配置（从API动态加载，禁止硬编码）
const membershipPoints = ref({
  starter: 0,
  standard: null,
  premium: null
})

// 加载用户订阅信息
const loadUserSubscriptionInfo = async () => {
  try {
    // 确保用户store已初始化
    if (!userStore.initialized) {
      await userStore.init()
    }
    
    // 强制刷新用户信息，确保获取管理员修改后的最新数据
    await userStore.fetchCurrentUser()
    
    // 检查用户是否已认证
    if (!userStore.isAuthenticated) {
      console.warn('用户未认证，跳转到登录页')
      message.warning(t('subscription.pleaseLogin'))
      router.push('/login')
      return
    }

    // 检查token是否存在
    const token = userStore.token || localStorage.getItem('token')
    if (!token || token === 'null' || token.trim() === '') {
      console.warn('未找到有效的token，跳转到登录页')
      message.warning(t('subscription.pleaseLogin'))
      router.push('/login')
      return
    }
    
    console.log('开始加载用户订阅信息...')
    const response = await getUserSubscriptionInfo()
    console.log('用户订阅信息响应完整对象：', response)
    console.log('响应状态码：', response.status)
    console.log('响应数据：', response.data)
    console.log('响应数据类型：', typeof response.data)
    
    // 检查是否是HTML响应（302重定向的结果）
    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.error('收到HTML响应，可能是认证失败导致重定向到登录页')
      // 响应拦截器已经处理了跳转和清除token，这里直接返回
      return
    }
    
    // 检查响应结构
    if (response.data) {
      // 如果response.data.success存在且为true
      if (response.data.success === true && response.data.data) {
        const data = response.data.data
        userInfo.value = {
          username: data.username || '',
          userId: data.userId || null,
          points: data.points || 0,
          frozenPoints: data.frozenPoints || 0,
          email: data.email || '',
          nickname: data.nickname || ''
        }

        subscriptionInfo.value = {
          currentPlan: mapPlanNameToI18nKey(data.currentPlan),
          expiryTime: data.expiryTime || t('subscription.permanent'),
          paidAt: data.paidAt || null
        }
        
        console.log('用户信息加载成功:', userInfo.value)
        console.log('订阅信息加载成功:', subscriptionInfo.value)
        console.log('后端返回的 currentPlan:', data.currentPlan)
        console.log('设置后的 subscriptionInfo.currentPlan:', subscriptionInfo.value.currentPlan)
      } else {
        // 如果响应结构不同，尝试直接使用response.data
        console.warn('响应格式不符合预期，尝试直接使用response.data')
        const data = response.data.data || response.data
        if (data && typeof data === 'object' && (data.username || data.userId)) {
          userInfo.value = {
            username: data.username || '',
            userId: data.userId || null,
            points: data.points || 0,
            frozenPoints: data.frozenPoints || 0,
            email: data.email || '',
            nickname: data.nickname || ''
          }

          subscriptionInfo.value = {
            currentPlan: mapPlanNameToI18nKey(data.currentPlan),
            expiryTime: data.expiryTime || t('subscription.permanent'),
            paidAt: data.paidAt || null
          }
          console.log('用户信息加载成功（备用路径）:', userInfo.value)
          console.log('后端返回的 currentPlan（备用路径）:', data.currentPlan)
          console.log('设置后的 subscriptionInfo.currentPlan（备用路径）:', subscriptionInfo.value.currentPlan)
        } else {
          console.error('获取用户订阅信息失败: 响应数据为空或格式不正确')
          console.error('完整响应:', JSON.stringify(response.data, null, 2))
          message.warning(t('subscription.loadUserInfoFailed'))
        }
      }
    } else {
      console.error('获取用户订阅信息失败: response.data为空')
      console.error('完整响应对象:', response)
      message.warning(t('subscription.loadUserInfoFailed'))
    }
  } catch (error) {
    console.error('加载用户订阅信息失败:', error)
    console.error('错误详情:', error.response?.data || error.message)

    // 如果是认证失败（401、403、302或HTML响应），响应拦截器已经处理了跳转
    if (error.response?.status === 401 ||
        error.response?.status === 403 ||
        error.response?.status === 302 ||
        error.message?.includes('认证失败') ||
        error.message?.includes('redirect')) {
      // 响应拦截器已经处理了跳转，这里不再重复处理
      console.warn('认证失败，响应拦截器已处理跳转')
      return
    }

    // 其他错误才显示消息
    message.error(t('subscription.loadUserInfoError', { message: error.response?.data?.message || error.message || t('subscription.refreshPage') }))
  }
}

// 加载会员等级价格配置（从公开接口获取，无需登录）
const loadMembershipPrices = async () => {
  try {
    // 添加时间戳防止缓存
    const response = await axios.get('/api/public/config', {
      params: { _t: Date.now() },
      headers: { 'Cache-Control': 'no-cache' }
    })
    if (response.data) {
      // 从membershipLevels数组读取价格（必须从数据库获取，禁止硬编码）
      if (response.data.membershipLevels && response.data.membershipLevels.length > 0) {
        const levels = response.data.membershipLevels
        const starterLevel = levels.find(l => l.name === 'starter')
        const standardLevel = levels.find(l => l.name === 'standard')
        const proLevel = levels.find(l => l.name === 'professional')
        
        if (!starterLevel) console.warn('数据库中缺少starter会员等级配置')
        if (!standardLevel) console.warn('数据库中缺少standard会员等级配置')
        if (!proLevel) console.warn('数据库中缺少professional会员等级配置')
        
        // 将浮点数价格转换为整数存储（前端显示用），缺少的等级使用0
        membershipPrices.value = {
          starter: starterLevel ? Math.floor(starterLevel.price) : 0,
          standard: standardLevel ? Math.floor(standardLevel.price) : 0,
          premium: proLevel ? Math.floor(proLevel.price) : 0
        }
        // 同时加载积分配置
        membershipPoints.value = {
          starter: starterLevel ? starterLevel.pointsBonus : 0,
          standard: standardLevel ? standardLevel.pointsBonus : 0,
          premium: proLevel ? proLevel.pointsBonus : 0
        }
      } else {
        // 如果membershipLevels为空，尝试从独立字段读取（兼容旧API）
        membershipPrices.value = {
          starter: Math.floor(response.data.starterPriceCny || 0),
          standard: Math.floor(response.data.standardPriceCny || 0),
          premium: Math.floor(response.data.proPriceCny || 0)
        }
        membershipPoints.value = {
          starter: response.data.starterPoints || 0,
          standard: response.data.standardPoints || 0,
          premium: response.data.proPoints || 0
        }
      }
      console.log('从后端加载会员等级配置:', membershipPrices.value, membershipPoints.value)
    }
  } catch (error) {
    console.error('加载价格配置失败:', error.message)
    // API调用失败，设置为0并提示用户
    membershipPrices.value = {
      starter: 0,
      standard: 0,
      premium: 0
    }
    membershipPoints.value = {
      starter: 0,
      standard: 0,
      premium: 0
    }
    message.error(t('common.cannotLoadMembershipPriceConfig'))
  }
}

// 格式化价格，转换为整数显示
const formatPrice = (price) => {
  if (price === null || price === undefined) return '--'
  return Math.floor(Number(price)).toString()
}

// 组件挂载时加载数据
onMounted(async () => {
  // 先加载会员等级价格配置（不需要登录）
  await loadMembershipPrices()
  
  // 确保用户store已初始化
  if (!userStore.initialized) {
    await userStore.init()
  }
  
  // 如果用户已登录，加载订阅信息
  if (userStore.isAuthenticated) {
    // 先从store中获取基本信息（如果可用）
    if (userStore.user) {
      userInfo.value = {
        username: userStore.user.username || '',
        userId: userStore.user.id || null,
        points: userStore.user.points || 0,
        frozenPoints: userStore.user.frozenPoints || 0,
        email: userStore.user.email || '',
        nickname: userStore.user.nickname || ''
      }
    }
    
    // 然后从API获取完整的订阅信息
    await loadUserSubscriptionInfo()
    
    // 检查URL参数，处理支付回调
    const urlParams = new URLSearchParams(window.location.search)
    const paymentStatus = urlParams.get('paymentStatus')
    const orderId = urlParams.get('orderId')
    
    if (paymentStatus) {
      // 清除URL参数，避免刷新时重复显示
      window.history.replaceState({}, document.title, window.location.pathname)
      
      if (paymentStatus === 'success') {
        message.success(t('subscription.paymentSuccess'))
        // 刷新用户积分信息
        await userStore.fetchCurrentUser()
        await loadUserSubscriptionInfo()
      } else if (paymentStatus === 'pending') {
        message.info(t('subscription.paymentPending'))
      } else if (paymentStatus === 'cancelled') {
        message.warning(t('subscription.paymentCancelled'))
      } else if (paymentStatus === 'error') {
        message.error(t('subscription.paymentError'))
      }
    }
  } else {
    // 路由守卫应该已经处理了跳转，但这里作为双重保险
    console.warn('用户未登录，路由守卫应该已处理跳转')
  }
})

// 挂载/卸载时注册全局点击监听，用于关闭用户菜单
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 跳转到个人主页
const goToProfile = () => {
  router.push('/profile')
}

const goToMyWorks = () => {
  router.push('/works')
}

const goToTextToVideo = () => {
  router.push('/text-to-video/create')
}

const goToImageToVideo = () => {
  router.push('/image-to-video/create')
}

const goToStoryboardVideo = () => {
  router.push('/storyboard-video/create')
}

// 积分历史模态框相关
const pointsHistoryDialogVisible = ref(false)
const pointsHistoryLoading = ref(false)
const pointsHistory = ref([])
const paymentModalVisible = ref(false)
const currentPaymentData = ref({})

// 计算总充值和总消耗
const totalRecharge = computed(() => {
  return pointsHistory.value
    .filter(item => item.type === '充值')
    .reduce((sum, item) => sum + (item.points || 0), 0)
})

const totalConsume = computed(() => {
  // 后端返回的消耗记录points已经是负数，所以直接求和后取绝对值
  const consumeSum = pointsHistory.value
    .filter(item => item.type === '消耗')
    .reduce((sum, item) => sum + (item.points || 0), 0)
  return Math.abs(consumeSum)
})

// 显示积分详情模态框
const goToOrderDetails = async () => {
  pointsHistoryDialogVisible.value = true
  await loadPointsHistory()
}

// 加载积分使用历史
const loadPointsHistory = async () => {
  pointsHistoryLoading.value = true
  try {
    const response = await getPointsHistory({
      page: 0,
      size: 10000 // 使用足够大的值获取所有记录
    })
    
    if (response.data.success) {
      pointsHistory.value = response.data.data || []
    } else {
      console.error('获取积分使用历史失败:', response.data.message)
      message.error(t('subscription.loadPointsHistoryFailed'))
    }
  } catch (error) {
    console.error('加载积分使用历史失败:', error)
    message.error(t('subscription.loadPointsHistoryFailed'))
  } finally {
    pointsHistoryLoading.value = false
  }
}

// 关闭积分历史模态框
const handlePointsHistoryDialogClose = () => {
  pointsHistoryDialogVisible.value = false
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 跳转到我的作品页面
const goToWorks = () => {
  router.push('/works')
}

// 点击外部关闭用户菜单
const handleClickOutside = (event) => {
  const userAvatar = event.target.closest('.user-avatar')
  const userMenu = event.target.closest('.user-menu-teleport')
  if (!userAvatar && !userMenu) {
    showUserMenu.value = false
  }
}

// 管理员菜单导航
const goToDashboard = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/admin/dashboard')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToOrders = () => {
  showUserMenu.value = false
  router.push('/admin/orders')
}

const goToMembers = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/member-management')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToErrorStats = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/admin/error-statistics')
  }
}

const goToSettings = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/system-settings')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToApiManagement = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/api-management')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToTaskRecord = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/generate-task-record')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToChangePassword = () => {
  showUserMenu.value = false
  router.push('/change-password')
}

// 退出登录
const logout = async () => {
  try {
    showUserMenu.value = false
    await userStore.logoutUser()
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    message.success(t('profile.logoutSuccess'))
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    message.error(t('profile.logoutFailed'))
  }
}

// 选中套餐（紫色边框）
const selectedPlan = ref('starter')
const selectPlan = (plan) => {
  selectedPlan.value = plan
}

// 处理订阅
// 记录当前选择的套餐类型，用于判断是否需要生成新订单
let lastSelectedPlanType = ''

const handleSubscribe = async (planType) => {
  console.log('handleSubscribe 被调用，planType:', planType)
  try {
    console.log('开始处理订阅...')
    const planInfo = getPlanInfo(planType)
    console.log('获取到的套餐信息:', planInfo)

    if (!planInfo || planInfo.price === null || planInfo.price === undefined) {
      throw new Error(`会员等级配置缺失或价格未加载: ${planType}`)
    }
    
    // 只有套餐类型变化时才生成新的orderId
    if (planType !== lastSelectedPlanType || !currentPaymentData.value.orderId) {
      currentPaymentData.value = {
        title: `${planInfo.name}会员`,
        amount: planInfo.price,
        orderId: `SUB_${planType}_${Date.now()}`,
        planType: planType,
        planInfo: planInfo
      }
      lastSelectedPlanType = planType
      console.log('套餐变化，生成新的orderId:', currentPaymentData.value.orderId)
    } else {
      // 同一套餐，只更新必要信息，保留orderId
      currentPaymentData.value.title = `${planInfo.name}会员`
      currentPaymentData.value.amount = planInfo.price
      currentPaymentData.value.planInfo = planInfo
      console.log('同一套餐，复用orderId:', currentPaymentData.value.orderId)
    }
    
    console.log('支付数据设置完成:', currentPaymentData.value)
    
    // 显示支付模态框（PaymentModal组件会自动处理支付流程）
    paymentModalVisible.value = true
    console.log('支付模态框已显示，PaymentModal将自动处理支付')

  } catch (error) {
    console.error('订阅处理失败:', error)
    message.error(t('subscription.subscriptionFailed'))
  }
}

// 生成二维码
const generateQRCode = async (planType, planInfo) => {
  try {
    console.log('=== 开始生成二维码 ===')
    
    // 创建支付订单数据
    const paymentData = {
      orderId: `SUB_${planType}_${Date.now()}`,
      amount: planInfo.price.toString(),
      method: 'ALIPAY',
      description: `${planInfo.name}会员 - 支付宝支付`
    }

    console.log('1. 创建支付订单，数据：', paymentData)
    const createResponse = await createPayment(paymentData)
    console.log('创建支付订单响应：', createResponse)
    
    if (createResponse.data && createResponse.data.success) {
      const paymentId = createResponse.data.data.id
      console.log('2. 支付订单创建成功，ID：', paymentId)
      
      console.log('3. 创建支付宝支付...')
      const alipayResponse = await createAlipayPayment({ paymentId })
      console.log('支付宝支付响应：', alipayResponse)
      
      if (alipayResponse.data && alipayResponse.data.success) {
        const qrCode = alipayResponse.data.data.qrCode
        console.log('4. 支付宝二维码：', qrCode)
        
        if (qrCode) {
          // 使用在线API生成二维码图片（直接使用支付宝返回的URL生成二维码）
          try {
            console.log('开始生成二维码，内容:', qrCode)
            
            // 使用QuickChart API生成二维码，完全去除白边
            const qrCodeUrl = `https://quickchart.io/qr?text=${encodeURIComponent(qrCode)}&size=200&margin=0&dark=ffffff&light=1a1a1a`
            
            console.log('5. 二维码图片URL已生成')
            
            // 更新二维码显示
            const qrCodeElement = document.querySelector('#qr-code-img')
            if (qrCodeElement) {
              qrCodeElement.src = qrCodeUrl
              qrCodeElement.style.display = 'block'
              console.log('6. 二维码图片已设置')
            }
            
            // 隐藏模拟二维码
            const qrPlaceholder = document.querySelector('.qr-placeholder')
            if (qrPlaceholder) {
              qrPlaceholder.style.display = 'none'
              console.log('7. 模拟二维码已隐藏')
            }
            
            message.success(t('subscription.qrCodeGenerated'))
            console.log('=== 二维码生成完成 ===')
          } catch (error) {
            console.error('生成二维码失败：', error)
            message.error(t('subscription.qrCodeGenerationFailed'))
          }
        } else {
          message.error(t('subscription.qrCodeEmpty'))
        }
      } else {
        console.error('支付宝响应失败：', alipayResponse)
        // 不显示后端返回的详细错误消息，只显示通用提示
        message.error(t('subscription.qrCodeGenerationFailed'))
      }
    } else {
      console.error('创建支付订单失败：', createResponse)
      // 不显示后端返回的详细错误消息，只显示通用提示
      message.error(t('subscription.createPaymentFailed'))
    }

  } catch (error) {
    console.error('=== 二维码生成出错 ===')
    console.error('错误详情：', error)
    // 不显示详细错误消息，只显示通用提示
    message.error(t('subscription.qrCodeGenerationFailed'))
  }
}

// 当前套餐判断（直接使用后端返回的原始文本进行匹配）
const isCurrentPlan = (planType) => {
  const current = subscriptionInfo.value?.currentPlan
  if (!current) return false

  // 直接根据后端返回的中文文本匹配
  if (planType === 'starter') {
    // starter 套餐：匹配入门会员
    return current.includes('入门') || current.toLowerCase().includes('starter')
  } else if (planType === 'standard') {
    return current.includes('标准') || current.toLowerCase().includes('standard')
  } else if (planType === 'premium') {
    return current.includes('专业') || current.toLowerCase().includes('premium') || current.toLowerCase().includes('professional')
  }

  return false
}

// 🔥 判断是否应该显示“当前套餐”按钮
const shouldShowCurrentPlan = (planType) => {
  const current = subscriptionInfo.value?.currentPlan
  if (!current) return false

  // 如果是免费会员，三个套餐都显示“立即订阅”
  if (current.includes('免费') || current.toLowerCase().includes('free')) {
    return false  // 不显示“当前套餐”
  }

  // 如果是入门会员，只在入门套餐显示“当前套餐”
  if (current.includes('入门') || current.toLowerCase().includes('starter')) {
    return planType === 'starter'
  }

  // 标准会员：只在标准套餐显示
  if (current.includes('标准') || current.toLowerCase().includes('standard')) {
    return planType === 'standard'
  }

  // 专业会员：只在专业套餐显示
  if (current.includes('专业') || current.toLowerCase().includes('premium') || current.toLowerCase().includes('professional')) {
    return planType === 'premium'
  }

  return false
}

// 获取套餐信息（使用动态价格和积分，禁止硬编码）
const getPlanInfo = (planType) => {
  const plans = {
    starter: {
      name: t('subscription.starter'),
      price: membershipPrices.value.starter,
      points: membershipPoints.value.starter,
      description: t('subscription.starterDescription')
    },
    standard: {
      name: t('subscription.standard'),
      price: membershipPrices.value.standard,
      points: membershipPoints.value.standard,
      description: t('subscription.standardDescription')
    },
    premium: {
      name: t('subscription.professional'),
      price: membershipPrices.value.premium,
      points: membershipPoints.value.premium,
      description: t('subscription.premiumDescription')
    }
  }
  return plans[planType]
}

// 支付成功处理
const handlePaymentSuccess = async (paymentData) => {
  try {
    console.log('✅ 收到支付成功事件，支付数据:', paymentData)
    message.success(t('subscription.paymentSuccess'))

    // 关闭支付模态框
    paymentModalVisible.value = false
    
    // 重置支付数据，下次购买生成新订单
    lastSelectedPlanType = ''
    currentPaymentData.value = {}

    // 重新加载用户订阅信息
    await loadUserSubscriptionInfo()

    message.success(t('subscription.infoUpdated'))

  } catch (error) {
    console.error('❌ 支付成功处理失败:', error)
    message.error(t('subscription.paymentProcessingFailed'))
  }
}

// 支付失败处理
const handlePaymentError = (error) => {
  console.error('支付失败:', error)
  message.error(t('subscription.paymentFailed'))
}

// 创建订阅订单
const createSubscriptionOrder = async (planType, planInfo) => {
  try {
    message.info(t('subscription.creatingOrder'))

    // 生成订单号
    const orderId = `SUB_${planType}_${Date.now()}`

    // 创建支付订单数据
    const paymentData = {
      orderId: orderId,
      amount: planInfo.price.toString(),
      method: 'ALIPAY',
      description: planInfo.description,
      orderType: 'SUBSCRIPTION',
      planType: planType
    }

    // 先创建支付记录
    const createResponse = await createPayment(paymentData)

    if (createResponse.data.success) {
      const paymentId = createResponse.data.data.id

      // 然后创建支付宝支付
      const alipayResponse = await createAlipayPayment({ paymentId })

      if (alipayResponse.data.success) {
        // 跳转到支付宝支付页面
        const paymentForm = alipayResponse.data.data
        // 创建临时div来显示支付表单
        const tempDiv = document.createElement('div')
        tempDiv.innerHTML = paymentForm
        document.body.appendChild(tempDiv)

        // 自动提交表单
        const form = tempDiv.querySelector('form')
        if (form) {
          form.submit()
        } else {
          message.error(t('subscription.paymentPageLoadFailed'))
        }

        // 清理临时元素
        setTimeout(() => {
          if (document.body.contains(tempDiv)) {
            document.body.removeChild(tempDiv)
          }
        }, 1000)

      } else {
        message.error(alipayResponse.data.message || t('subscription.createAlipayPaymentFailed'))
      }

    } else {
      message.error(createResponse.data.message || t('subscription.createPaymentFailed'))
    }

  } catch (error) {
    console.error('创建支付订单失败:', error)
    message.error(t('subscription.createPaymentOrderFailed'))
  }
}
</script>

<style scoped>
.subscription-page {
  min-height: 100vh;
  background: var(--bg-base);
  color: var(--text-primary);
  display: flex !important;
  font-family: var(--font-sans);
  margin: 0 !important;
  padding: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  overflow: hidden;
  position: relative;
}

/* 侧边栏样式已由 <SidebarNav> 组件管理 */

/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 0;
  background: var(--bg-base);
  overflow-y: auto;
  min-width: 0;
}


/* 用户菜单样式（右上角头像下拉） */
.user-menu-teleport {
  background: var(--bg-surface);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-md);
  min-width: 160px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: var(--space-3) var(--space-4);
  cursor: pointer;
  transition: var(--transition-colors);
  color: var(--text-primary);
  font-size: var(--text-sm);
}

.menu-item:hover {
  background: var(--bg-hover);
}

.menu-item .anticon {
  margin-right: var(--space-2);
  font-size: var(--text-base);
}

.menu-item:not(:last-child) {
  border-bottom: 1px solid var(--border-default);
}

/* 套餐选择 */
.subscription-packages {
  padding: 0 var(--space-8) var(--space-8);
  margin: 0 auto;
  max-width: calc(100% - 80px);
  margin-left: 15px;
}

.subscription-packages .section-title {
  font-size: 1.75rem;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 var(--space-8) 0;
  text-align: left !important;
  position: relative;
}

.subscription-packages .section-title::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 0;
  transform: none;
  width: 80px;
  height: 4px;
  background: var(--gradient-brand);
  border-radius: 2px;
}

.subscription-packages .packages-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--space-6);
  max-width: 1440px;
  margin: 0 var(--space-8) 0 0;
  width: 100%;
  min-height: calc(100vh - 450px); /* 调整高度 */
}

.subscription-packages .package-card {
  background: var(--bg-surface);
  border-radius: 20px;
  padding: var(--space-8);
  border: 2px solid var(--border-subtle);
  position: relative;
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.subscription-packages .package-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 5px;
  background: var(--gradient-cool);
}

.subscription-packages .package-card.standard-card::before {
  background: var(--gradient-brand);
}

.subscription-packages .package-card.premium-card::before {
  background: var(--gradient-sunset);
}

.subscription-packages .package-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 16px 48px rgba(124, 58, 237, 0.15), 0 4px 12px rgba(0, 0, 0, 0.06);
  border-color: var(--primary-200);
}

.subscription-packages .package-card.selected {
  border: 2px solid var(--primary-400);
  box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.15), 0 12px 40px rgba(124, 58, 237, 0.2);
}

.subscription-packages .package-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--space-5);
}

.subscription-packages .package-title {
  font-size: 1.25rem;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0;
}

.subscription-packages .discount-tag, .subscription-packages .value-tag {
  font-size: 11px;
  padding: 4px 10px;
  border-radius: 20px;
  font-weight: 600;
}

.subscription-packages .discount-tag { background: var(--accent-glow); color: var(--accent-600); }
.subscription-packages .value-tag { background: var(--gradient-warm); color: #fff; box-shadow: 0 2px 8px rgba(236, 72, 153, 0.25); }

.subscription-packages .package-price {
  font-size: 2.25rem;
  font-weight: 800;
  background: var(--gradient-brand);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: var(--space-4);
}

.subscription-packages .points-box {
  background: var(--bg-overlay);
  color: var(--text-primary);
  padding: var(--space-3) var(--space-4);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  margin-bottom: var(--space-5);
  text-align: center;
}

.subscription-packages .points-box .points-validity {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
  margin-top: var(--space-1);
}

.subscription-packages .points-box-placeholder {
  background: transparent;
  color: transparent;
  visibility: hidden;
}

.subscription-packages .package-button {
  width: 100%;
  padding: 12px;
  border-radius: 14px;
  font-size: var(--text-base);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: var(--space-6);
  border: none;
}

.subscription-packages .package-button.current { background: var(--bg-active); color: var(--text-secondary); }
.subscription-packages .package-button.subscribe { background: var(--gradient-cool); color: #fff; box-shadow: 0 4px 16px rgba(6, 182, 212, 0.3); }
.subscription-packages .package-button.subscribe:hover { box-shadow: 0 6px 24px rgba(6, 182, 212, 0.4); transform: translateY(-2px); }
.subscription-packages .package-button.premium { background: var(--gradient-sunset); color: #fff; box-shadow: 0 4px 16px rgba(236, 72, 153, 0.3); }
.subscription-packages .package-button.premium:hover { box-shadow: 0 6px 24px rgba(236, 72, 153, 0.4); transform: translateY(-2px); }

.subscription-packages .package-features {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
  margin-top: auto; /* 将特性列表推至卡片下部，保持视觉均衡 */
}

.subscription-packages .feature-item {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  font-size: var(--text-sm);
  color: var(--text-secondary);
}

.subscription-packages .check-icon { color: var(--accent-500); font-size: var(--text-base); }
.subscription-packages .premium-card .check-icon { color: var(--secondary-500); }

/* 响应式设计 */
@media (max-width: 1024px) {
  .subscription-packages .packages-grid {
    grid-template-columns: 1fr;
    gap: var(--space-5);
    max-width: 720px;
  }
  
  .membership-overview {
    flex-direction: column;
    gap: var(--space-5);
  }
}

@media (max-width: 768px) {
  .sidebar {
    width: 240px;
  }
  
  .user-profile-section {
    flex-direction: column;
    text-align: center;
  }
  
  .profile-actions {
    justify-content: center;
  }
}

/* 顶部合并的两层盒子 — Bold Gradient */
.top-merged-card {
  max-width: calc(100% - 80px);
  width: 100%;
  margin: var(--space-5) auto;
  background: var(--gradient-brand);
  border: none;
  border-radius: 24px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 8px 32px rgba(124, 58, 237, 0.25), 0 2px 8px rgba(236, 72, 153, 0.15);
}

.top-merged-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background:
    radial-gradient(circle at 85% 15%, rgba(255, 255, 255, 0.15) 0%, transparent 50%),
    radial-gradient(circle at 15% 85%, rgba(6, 182, 212, 0.2) 0%, transparent 50%);
  pointer-events: none;
}

.top-merged-card .row-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-5);
  padding: var(--space-8);
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
  position: relative;
  z-index: 1;
}

.top-merged-card .row-bottom {
  display: grid;
  grid-template-columns: 1fr auto 1fr auto 1fr;
  gap: var(--space-8);
  padding: var(--space-8);
  align-items: center;
  position: relative;
  z-index: 1;
}

.top-merged-card .divider-v { width:1px; height:var(--space-12); background:rgba(255, 255, 255, 0.2); }
.top-merged-card .summary-item { display:flex; flex-direction:column; gap:var(--space-2); }
.top-merged-card .summary-label { font-size:var(--text-sm); color:rgba(255, 255, 255, 0.7); }
.top-merged-card .summary-value { font-size:var(--text-lg); color:#fff; font-weight:var(--font-semibold); }
.top-merged-card .summary-value.highlight { color:#fff; display:flex; align-items:center; gap:var(--space-2); }
.top-merged-card .plus-icon { font-size:var(--text-xl); color:rgba(255, 255, 255, 0.8); }

/* 顶部行内的用户信息与按钮样式（沿用原样式类） */
.user-left { display:flex; align-items:center; gap:var(--space-5); }
.avatar-wrap {
  width: 60px;
  height: 60px;
  border-radius: var(--radius-full);
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px solid rgba(255, 255, 255, 0.5);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.avatar-wrap .avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-meta { display:flex; flex-direction:column; }
.username { font-size:var(--text-lg); font-weight:700; color:#fff; text-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.user-id { font-size:var(--text-sm); color:rgba(255, 255, 255, 0.7); }
.user-right { display:flex; align-items:center; gap:var(--space-3); }
.points-pill { display:flex; align-items:center; gap:var(--space-2); padding:var(--space-2) var(--space-3); border-radius:var(--radius-full); background:rgba(255, 255, 255, 0.18); border:1px solid rgba(255, 255, 255, 0.3); color:#fff; font-weight:var(--font-semibold); font-size:var(--text-base); backdrop-filter:blur(8px); }
.star-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  background: rgba(255, 255, 255, 0.25);
  border-radius: var(--radius-full);
  color: #fff;
  font-size: var(--text-xs);
}
.mini-btn { background:rgba(255, 255, 255, 0.18); color:#fff; border:1px solid rgba(255, 255, 255, 0.3); padding:var(--space-2) var(--space-3); border-radius:10px; font-size:var(--text-sm); cursor:pointer; transition:all 0.2s ease; backdrop-filter:blur(8px); }
.mini-btn:hover { background:rgba(255, 255, 255, 0.3); border-color:rgba(255, 255, 255, 0.5); }
 
@media (max-width: 1024px) {
  .top-merged-card { margin: 0 var(--space-4) var(--space-4); }
  .top-merged-card .row-top { flex-direction: column; align-items: flex-start; gap: var(--space-3); }
  .top-merged-card .row-bottom { grid-template-columns: 1fr; gap: var(--space-3); }
}

/* 积分详情模态框样式 */
.points-history-dialog {
  background: var(--bg-surface);
  color: var(--text-primary);
}

/* 修改对话框边框为淡蓝色 */
.points-history-dialog :deep(.ant-modal) {
  border: 1px solid var(--primary-400) !important;
}

.points-history-dialog :deep(.ant-modal-header) {
  border-bottom: 1px solid var(--primary-400) !important;
}

.points-history-content {
  background: var(--bg-surface);
  color: var(--text-primary);
  border: 1px solid var(--primary-400);
  border-radius: var(--radius-sm);
  padding: var(--space-5);
}

.points-summary {
  margin-bottom: var(--space-8);
  padding: var(--space-5);
  background: var(--bg-hover);
  border-radius: var(--radius-md);
}

.points-summary h3 {
  color: var(--text-primary);
  margin: 0 0 var(--space-4) 0;
  font-size: var(--text-lg);
}

.summary-stats {
  display: flex;
  gap: var(--space-8);
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.stat-label {
  color: var(--text-tertiary);
  font-size: var(--text-sm);
}

.stat-value {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
}

.stat-value.positive {
  color: var(--accent-500);
}

.stat-value.negative {
  color: var(--error-500);
}

.stat-value.current {
  color: var(--primary-400);
}

.points-history-list {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
  max-height: 600px;
  overflow-y: auto;
}

.empty-history {
  text-align: center;
  padding: var(--space-10);
  color: var(--text-tertiary);
}

.history-item {
  background: var(--bg-hover);
  border-radius: var(--radius-md);
  padding: var(--space-5);
  border: 1px solid var(--border-default);
  transition: var(--transition-all);
}

.history-item:hover {
  border-color: var(--border-strong);
  transform: translateY(-2px);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-4);
}

.history-type {
  padding: var(--space-1) var(--space-3);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
}

.history-type.recharge {
  background: var(--accent-500);
  color: var(--text-primary);
}

.history-type.consume {
  background: var(--error-500);
  color: var(--text-primary);
}

.history-points {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
}

.history-points.positive {
  color: var(--accent-500);
}

.history-points.negative {
  color: var(--error-500);
}

.history-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-info p {
  margin: var(--space-1) 0;
  color: var(--text-secondary);
  font-size: var(--text-sm);
}

.history-info strong {
  color: var(--text-primary);
}

/* Sora2.0 SVG 风格标签 */
.badge-pro, .badge-max {
  font-size: 9px;
  padding: 0 3px;
  border-radius: 2px;
  font-weight: var(--font-medium);
  margin-left: var(--space-2);
  background: var(--primary-glow-medium);
  color: var(--primary-400);
  flex: 0 0 auto !important;
  width: auto !important;
}

.badge-max {
  background: var(--error-glow);
  color: var(--error-400);
}
</style>

