<template>
  <div class="profile-container">
    <!-- 未登录状态 -->
    <div v-if="!userStore.isLoggedIn" class="login-prompt">
      <div class="login-card">
        <div class="login-icon">
          <div class="icon-circle">
            <div class="lock-icon">🔒</div>
          </div>
        </div>
        <div class="login-content">
          <h3>登录账号</h3>
          <p>登录后查看个人信息和使用记录</p>
          <div class="login-actions">
            <router-link to="/login" class="btn btn-primary">立即登录</router-link>
            <router-link to="/register" class="btn btn-secondary">快速注册</router-link>
          </div>
        </div>
      </div>
    </div>

    <!-- 已登录状态 -->
    <div v-else>
      <!-- 用户信息卡片 -->
      <div class="user-card">
        <!-- 用户信息加载状态 -->
        <div v-if="userInfoLoading" class="user-info-loading">
          <div class="loading-spinner">正在更新用户信息...</div>
        </div>
        <div v-else class="user-content">
        <div class="user-avatar">
          <div class="avatar-circle">
            <img v-if="userStore.user.avatar" :src="userStore.user.avatar" alt="头像" class="avatar-img" />
            <div v-else class="avatar-icon">{{ userInitial }}</div>
          </div>
        </div>
        <div class="user-info">
          <div class="user-name">{{ displayUsername }}</div>
          <div class="user-level">
              <span class="level-badge" :class="{ 'vip-member': !isVipExpired, 'trial-user': isVipExpired }">
                {{ !isVipExpired ? '会员' : '非会员' }}
            </span>
            <span class="expire-date">有效期至：{{ formattedExpireDate }}</span>
            </div>
          </div>
        </div>
        <div class="user-actions">
          <div class="exchange-btn" @click="showMemberExchange">
            <div class="exchange-icon">💎</div>
            <span class="exchange-text">会员兑换</span>
          </div>
          <div class="logout-wrapper" @click="handleLogout">
            <img src="@/assets/icon/tuichu.png" alt="退出" class="logout-icon-img" />
          </div>
        </div>
        
        <!-- 悬浮在线客服 -->
        <div class="floating-customer-service" @click="showCustomerService">
          <div class="floating-service-content">
            <div class="service-avatar">
              <img src="@/assets/weixin.png" alt="客服" class="avatar-img" />
              <div class="online-indicator"></div>
            </div>
            <div class="service-bubble">
              <div class="bubble-text">在线客服</div>
              <div class="bubble-arrow"></div>
            </div>
          </div>
        </div>

        <!-- Coze AI 聊天助手 -->
        <div id="coze-chat-container"></div>
      </div>

      <!-- 会员续费提醒 -->
      <div v-if="isVipExpired" class="vip-renewal-notice">
        <div class="renewal-content">
          <div class="renewal-icon">⏰</div>
          <div class="renewal-text">
            <h4>会员已到期</h4>
            <p>您的会员权限已过期，续费后可继续享受专业推测服务。<span class="renewal-link" @click="showCustomerService">去续费</span></p>
          </div>
        </div>
      </div>

      <!-- 会员权益 -->
      <div class="benefits-section">
        <h3>会员权益</h3>
        <div class="benefits-grid">
          <div class="benefit-item">
            <div class="benefit-icon" style="background-color: #4285F4;">
              <el-icon><Search /></el-icon>
            </div>
            <div class="benefit-label">开奖信息查询</div>
          </div>
          <div class="benefit-item">
            <div class="benefit-icon" style="background-color: #34A853;">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="benefit-label">三性数据分析</div>
          </div>
          <div class="benefit-item">
            <div class="benefit-icon" style="background-color: #FBBC04;">
              <el-icon><Aim /></el-icon>
            </div>
            <div class="benefit-label">开奖推测辅助</div>
          </div>
          <div class="benefit-item">
            <div class="benefit-icon" style="background-color: #EA4335;">
              <el-icon><FolderChecked /></el-icon>
            </div>
            <div class="benefit-label">推测数据备份</div>
          </div>
          <div class="benefit-item">
            <div class="benefit-icon" style="background-color: #9C27B0;">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="benefit-label">AI深度互动</div>
          </div>
          <div class="benefit-item">
            <div class="benefit-icon" style="background-color: #FF9800;">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="benefit-label">彩票规则查阅</div>
          </div>
        </div>

        <div class="upgrade-button" v-if="isVipExpired">
          <button class="btn-upgrade" @click="showUpgradeInfo">升级正式会员</button>
        </div>
      </div>

      <!-- 功能菜单 -->
      <div class="menu-section">
        <div class="menu-item" @click="showAIAssistant">
          <div class="menu-icon">
            <img src="@/assets/icon/ai.svg" alt="AI助手" class="menu-icon-img">
          </div>
          <div class="menu-label ai-label">AI助手</div>
          <div class="menu-arrow">›</div>
        </div>
        <div class="menu-item" @click="$router.push('/exchange-records')">
          <div class="menu-icon">
            <img src="@/assets/icon/dhjl.svg" alt="兑换记录" class="menu-icon-img">
          </div>
          <div class="menu-label">兑换记录</div>
          <div class="menu-arrow">›</div>
        </div>
        <div class="menu-item" @click="$router.push('/predict-records')">
          <div class="menu-icon">
            <img src="@/assets/icon/tcjl.svg" alt="推测记录" class="menu-icon-img">
          </div>
          <div class="menu-label">推测记录</div>
          <div class="menu-arrow">›</div>
        </div>
        <div class="menu-item" @click="$router.push('/data-analysis')">
          <div class="menu-icon">
            <img src="@/assets/icon/sjfx.svg" alt="数据分析" class="menu-icon-img">
          </div>
          <div class="menu-label">数据分析</div>
          <div class="menu-arrow">›</div>
        </div>
        <div class="menu-item" @click="$router.push('/help-center')">
          <div class="menu-icon">
            <img src="@/assets/icon/bzzx.svg" alt="帮助中心" class="menu-icon-img">
          </div>
          <div class="menu-label">帮助中心</div>
          <div class="menu-arrow">›</div>
        </div>
        <div class="menu-item" @click="$router.push('/about-us')">
          <div class="menu-icon">
            <img src="@/assets/icon/gywm.svg" alt="关于我们" class="menu-icon-img">
          </div>
          <div class="menu-label">关于我们</div>
          <div class="menu-arrow">›</div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <h3>使用统计</h3>
        <div v-if="statsLoading" class="stats-loading">
          <div class="loading-spinner">加载中...</div>
        </div>
        <div v-else class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ userStats.predictCount || 0 }}</div>
            <div class="stat-label">推测次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ userStats.pendingCount || 0 }}</div>
            <div class="stat-label">待开奖次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ userStats.hitCount || 0 }}</div>
            <div class="stat-label">命中次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ formatHitRate(userStats.hitRate) }}%</div>
            <div class="stat-label">命中率</div>
          </div>
        </div>
      </div>

      <!-- 详细命中率分析 -->
      <div class="stats-section">
        <h3>命中率分析</h3>
        <div v-if="detailedStatsLoading" class="stats-loading">
          <div class="loading-spinner">加载中...</div>
        </div>
        <div v-else class="detailed-stats-grid">
          <!-- 首球命中数和命中率 -->
          <div class="stat-item">
            <div class="stat-number">{{ detailedStats.firstBall.hitCount || 0 }}</div>
            <div class="stat-label">首球命中次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ formatHitRate(detailedStats.firstBall.hitRate) }}%</div>
            <div class="stat-label">首球命中率</div>
          </div>
          
          <!-- 红球命中数和命中率 -->
          <div class="stat-item">
            <div class="stat-number">{{ detailedStats.redBall.totalHitCount || 0 }}</div>
            <div class="stat-label">红球命中总数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ formatHitRate(detailedStats.redBall.hitRate) }}%</div>
            <div class="stat-label">红球命中率</div>
          </div>
          
          <!-- 蓝球命中数和命中率 -->
          <div class="stat-item">
            <div class="stat-number">{{ detailedStats.blueBall.hitCount || 0 }}</div>
            <div class="stat-label">蓝球命中次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ formatHitRate(detailedStats.blueBall.hitRate) }}%</div>
            <div class="stat-label">蓝球命中率</div>
          </div>
        </div>
      </div>

      <!-- 奖金统计 -->
      <div class="stats-section">
        <h3>奖金统计</h3>
        <div v-if="detailedStatsLoading" class="stats-loading">
          <div class="loading-spinner">加载中...</div>
        </div>
        <div v-else>
          <div class="total-prize-summary">
            <span class="total-prize-label">总奖金:</span> <span class="prize-amount">¥{{ detailedStats.prize.totalPrize || 0 }}</span>
          </div>
          <el-table :data="filteredPrizeDetails" stripe style="width: 100%">
            <el-table-column prop="prizeLevel" label="奖项" />
            <el-table-column prop="winningCount" label="中奖次数" />
            <el-table-column prop="subtotal" label="累计奖金 (元)">
              <template #default="scope">
                <span>
                  {{ (scope.row.prizeLevel === '一等奖' || scope.row.prizeLevel === '二等奖') ? '约 ' : '' }}
                  {{ scope.row.subtotal }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 提示弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="hideModal">
      <div class="modal-content" @click.stop>
        <h3>{{ modalTitle }}</h3>
        <p>{{ modalMessage }}</p>
        <button class="btn btn-primary" @click="hideModal">确定</button>
      </div>
    </div>

    <!-- 退出登录确认弹窗 -->
    <div v-if="showLogoutConfirm" class="modal-overlay" @click="cancelLogout">
      <div class="modal-content logout-modal" @click.stop>
        <h3>退出登录</h3>
        <p>确定要退出当前账号吗？</p>
        <div class="modal-actions">
          <button class="btn btn-secondary" @click="cancelLogout">取消</button>
          <button class="btn btn-danger" @click="confirmLogout">确定退出</button>
        </div>
      </div>
    </div>

    <!-- 会员兑换弹窗 -->
    <div v-if="showMemberExchangeModal" class="modal-overlay" @click="hideMemberExchange">
      <div class="modal-content member-exchange-modal" @click.stop>
        <h3>会员兑换</h3>
        <p>请输入您的会员兑换码</p>
        <div class="exchange-input-container">
          <input 
            v-model="exchangeCode" 
            type="text" 
            placeholder="请输入兑换码" 
            class="exchange-input"
            maxlength="20"
          />
        </div>
        <div class="modal-actions">
          <button class="btn btn-secondary" @click="hideMemberExchange">取消</button>
          <button class="btn btn-primary" @click="confirmExchange">确认兑换</button>
        </div>
      </div>
    </div>

    <!-- 客服二维码弹窗 -->
    <div v-if="showCustomerServiceModal" class="modal-overlay" @click="hideCustomerService">
      <div class="modal-content customer-service-modal" @click.stop>
        <h3>在线客服</h3>
        <p>扫描二维码联系客服</p>
        <div class="qrcode-container">
          <canvas ref="qrcodeCanvas" class="qrcode-canvas"></canvas>
        </div>
        <div class="service-info">
          <p class="service-tip">请保存二维码图片，使用微信扫码添加客服</p>
          <p class="service-time">服务时间：9:00-21:00</p>
        </div>
        <div class="modal-actions">
          <button class="btn btn-secondary" @click="downloadQRCode">下载二维码</button>
          <button class="btn btn-primary" @click="hideCustomerService">关闭</button>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
import { userStore } from '../store/user'
import { lotteryApi } from '../api/index.js'
import QRCode from 'qrcode'
import { ElIcon, ElTable, ElTableColumn } from 'element-plus'
import {
  Search,
  DataAnalysis,
  Aim,
  FolderChecked,
  ChatDotRound,
  Collection,
  Tickets,
  ShoppingBag,
  Document
} from '@element-plus/icons-vue'

export default {
  name: 'Profile',
  components: {
    ElIcon,
    Search,
    DataAnalysis,
    Aim,
    FolderChecked,
    ChatDotRound,
    Collection,
    ElTable,
    ElTableColumn,
    Tickets,
    ShoppingBag,
    Document
  },
  data() {
    return {
      userStore,
      showModal: false,
      modalTitle: '',
      modalMessage: '',
      showLogoutConfirm: false,
      showMemberExchangeModal: false,
      showCustomerServiceModal: false,
      exchangeCode: '',
      statsLoading: false,
      userInfoLoading: false,
      detailedStatsLoading: false,
      userStats: {
        predictCount: 0,
        pendingCount: 0,
        hitCount: 0,
        hitRate: '0.00'
      },
      detailedStats: {
        firstBall: { hitCount: 0, totalCount: 0, hitRate: 0 },
        blueBall: { hitCount: 0, totalCount: 0, hitRate: 0 },
        redBall: { totalHitCount: 0, totalPredictedCount: 0, hitRate: 0 },
        prize: { totalPrize: 0, prizeDetails: [] }
      },
      cozeWebSDK: null
    }
  },
  async mounted() {
    // 进入页面时重新获取用户信息，确保数据是最新的
    if (this.userStore.isLoggedIn) {
      await this.refreshUserInfo()
    } else {
      // 如果未登录，跳转到登录页面
      console.log('用户未登录，跳转到登录页面')
      this.$router.push('/login')
    }
    
    // 初始检测设备类型
    this.checkDeviceType();
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.checkDeviceType);
    
    // 加载Coze Chat SDK
    this.loadCozeChatSDK()
  },
  async activated() {
    if (this.userStore.isLoggedIn) {
      await this.refreshUserInfo()
    }
  },
  beforeUnmount() {
    // 移除事件监听
    window.removeEventListener('resize', this.checkDeviceType);
    // 清理资源，避免内存泄漏
    this.cozeWebSDK = null
  },
  computed: {
    userStore() {
      return userStore
    },
    isVip() {
      return this.userStore.user?.vipLevel > 0
    },
    vipExpireDate() {
      if (!this.userStore.user?.vipExpireTime) return ''
      return new Date(this.userStore.user.vipExpireTime).toLocaleDateString()
    },
    filteredPrizeDetails() {
      // 过滤掉未中奖的记录
      return this.detailedStats.prize.prizeDetails?.filter(item => item.prizeLevel !== '未中奖') || []
    },
    // 计算用户头像首字母
    userInitial() {
      console.log('用户数据:', this.userStore.user) // 调试信息
      if (this.userStore.user && this.userStore.user.username) {
        return this.userStore.user.username.charAt(0).toUpperCase()
      }
      return '👤'
    },
    // 计算显示的账号
    displayUsername() {
      if (this.userStore.user && this.userStore.user.username) {
        return this.userStore.user.username
      }
      return '未知用户'
    },
    // 格式化有效期显示
    formattedExpireDate() {
      if (this.userStore.user && this.userStore.user.expireDate) {
        const date = new Date(this.userStore.user.expireDate)
        return date.toISOString().split('T')[0] // 只取日期部分 YYYY-MM-DD
      }
      return '2025-06-30'
    },
    
    // 检查会员是否已过期
    isVipExpired() {
      if (!this.userStore.user || !this.userStore.user.expireDate) {
        return false
      }
      
      const expireDate = new Date(this.userStore.user.expireDate)
      const currentDate = new Date()
      // 设置时间为当天23:59:59，确保在到期当天还能使用
      currentDate.setHours(23, 59, 59, 999)
      
      return expireDate < currentDate
    }
  },
  methods: {
    // 加载Coze Chat SDK
    loadCozeChatSDK() {
      // 创建script标签
      const script = document.createElement('script');
      script.src = 'https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.10/libs/cn/index.js';
      script.async = true;
      script.onload = () => {
        // SDK加载完成后初始化聊天客户端
        console.log('Coze SDK 加载完成');
        this.initCozeChatClient()
          .then(() => {
            console.log('Coze客户端初始化成功');
          })
          .catch(error => {
            console.error('Failed to initialize Coze chat client:', error);
          });
      };
      script.onerror = (error) => {
        console.error('加载Coze SDK失败:', error);
      };
      // 添加到文档中
      document.body.appendChild(script);
    },
    
    // 初始化Coze聊天客户端
    async initCozeChatClient() {
      if (!window.CozeWebSDK) {
        console.error('Coze SDK not loaded');
        throw new Error('Coze SDK未加载');
      }
      
      try {
        console.log('Initializing Coze chat client...');
        
        // 获取token
        const tokenData = await this.fetchCozeToken();
        console.log('Token data received:', tokenData);
        
        if (!tokenData || !tokenData.access_token) {
          console.error('Failed to get valid Coze token');
          throw new Error('无法获取有效的Coze token');
        }
        
        console.log('Creating Coze chat client with token...');
        
        // 检测设备类型
        const isMobile = this.checkDeviceType();
        console.log('设备类型:', isMobile ? '移动设备' : 'PC设备');
        
        // 保存Coze SDK配置
        const config = {
          config: {
            bot_id: '7524958762676305971',
          },
          componentProps: {
            title: '彩票猪手',
          },
          auth: {
            type: 'token',
            token: tokenData.access_token,
            onRefreshToken: async () => {
              try {
                console.log('Refreshing token...');
                const refreshedData = await this.fetchCozeToken();
                if (refreshedData && refreshedData.access_token) {
                  console.log('Token refreshed successfully');
                  return refreshedData.access_token;
                } else {
                  throw new Error('Failed to refresh token');
                }
              } catch (error) {
                console.error('Error refreshing token:', error);
                return '';
              }
            }
          },
          ui: {
            base: {
              icon: 'https://lf26-appstore-sign.oceancloudapi.com/ocean-cloud-tos/FileBizType.BIZ_BOT_ICON/2534800929065520_1751962457338211464.jpeg?lk3s=ca44e09c&x-expires=1752109178&x-signature=b4hRlUI61B9g8wHnao1%2FiRdqGtg%3D',
              layout: isMobile ? 'mobile' : 'pc', // 根据设备类型设置布局
              zIndex: 1000,
            },
            asstBtn: {
              isNeed: false, // 不展示默认悬浮球
            }
          }
        };
        
        // 仅输出部分配置信息，避免暴露token
        console.log('Coze client config (partial):', {
          botId: config.config.bot_id,
          title: config.componentProps.title,
          layout: config.ui.base.layout,
          authType: config.auth.type
        });
        
        // 创建聊天客户端实例
        this.cozeWebSDK = new window.CozeWebSDK.WebChatClient(config);
        console.log('Coze chat client initialized successfully');
        return this.cozeWebSDK;
        
      } catch (error) {
        console.error('Error initializing Coze chat:', error);
        throw error; // 重新抛出错误，让调用者知道初始化失败
      }
    },
    
    // 从API获取Coze token
    async fetchCozeToken() {
      try {
        const userId = this.userStore.user ? this.userStore.user.id : 'guest';
        const jwtExpireSeconds = 3600; // 1小时
        const tokenDurationSeconds = 86400; // 24小时
        
        // 根据环境确定API基础URL
        let baseUrl = '';
        if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
          baseUrl = 'http://localhost:8123';
        } else {
          // 生产环境或其他环境使用相对路径
          // baseUrl = 'http://47.117.22.239';
          baseUrl = 'https://www.jingcaishuju.com';
        }
        
        const url = `${baseUrl}/api/jwt/one-step-token?jwtExpireSeconds=${jwtExpireSeconds}&sessionName=${userId}&tokenDurationSeconds=${tokenDurationSeconds}`;
        
        console.log('Fetching Coze token, URL:', url);
        
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          credentials: 'include' // 包含cookies
        });
        
        if (!response.ok) {
          console.error(`API error: ${response.status}`, await response.text());
          throw new Error(`API error: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('Token API response:', data);
        
        // 根据API实际返回结构判断
        if (!data.success || !data.data) {
          throw new Error('API返回错误: ' + (data.message || '未知错误'));
        }
        
        // 确保返回的是正确格式的token
        if (data.data.access_token) {
          console.log('Token received successfully:', data.data.access_token.substring(0, 10) + '...');
          return data.data;
        } else if (typeof data.data === 'string') {
          // 如果直接返回了token字符串
          console.log('Token string received:', data.data.substring(0, 10) + '...');
          return { access_token: data.data };
        } else {
          console.error('Invalid token format:', data.data);
          throw new Error('Invalid token format');
        }
      } catch (error) {
        console.error('Error fetching Coze token:', error);
        return null;
      }
    },

    // 刷新用户信息（统一方法）
    async refreshUserInfo() {
      this.userInfoLoading = true
      try {
        console.log('重新获取用户信息')
        await this.userStore.fetchLoginUser()
        
        // 检查用户状态是否被禁用 (status为1表示禁用)
        if (this.userStore.user && this.userStore.user.status === 1) {
          this.modalTitle = '账号异常'
          this.modalMessage = '您的账号已被禁用，请联系管理员。'
          this.showModal = true
          
          // 延迟跳转到登录页
          setTimeout(() => {
            this.$router.push('/login')
          }, 2000) // 2秒后跳转
          return // 禁用状态下不再加载统计数据
        }

        // 获取用户信息成功后，获取用户统计数据
        if (this.userStore.user && this.userStore.user.id) {
          await this.fetchUserStats()
          await this.fetchDetailedStats()
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // fetchLoginUser内部已经处理了logout，如果失败会跳转到登录页
      } finally {
        this.userInfoLoading = false
      }
    },

    // 获取用户统计数据
    async fetchUserStats() {
      if (!this.userStore.user || !this.userStore.user.id) {
        console.log('用户ID不存在，无法获取统计数据')
        return
      }

      this.statsLoading = true
      try {
        console.log('正在获取用户统计数据，用户ID:', this.userStore.user.id)
        const response = await lotteryApi.getUserPredictStat(this.userStore.user.id)
        
        if (response && response.success && response.data) {
          this.userStats = {
            predictCount: response.data.predictCount || 0,
            pendingCount: response.data.pendingCount || 0,
            hitCount: response.data.hitCount || 0,
            hitRate: response.data.hitRate || '0.00'
          }
          console.log('获取用户统计数据成功:', this.userStats)
        } else {
          console.error('获取用户统计数据失败:', response)
          this.showModal = true
          this.modalTitle = '获取数据失败'
          this.modalMessage = response?.message || '无法获取统计数据，请稍后重试'
        }
      } catch (error) {
        console.error('获取用户统计数据出错:', error)
        this.showModal = true
        this.modalTitle = '网络错误'
        this.modalMessage = '获取统计数据时发生网络错误，请检查网络连接'
      } finally {
        this.statsLoading = false
      }
    },

    // 获取详细统计数据
    async fetchDetailedStats() {
      if (!this.userStore.user || !this.userStore.user.id) {
        console.log('用户ID不存在，无法获取详细统计数据');
        return;
      }

      this.detailedStatsLoading = true;
      try {
        console.log('正在获取详细统计数据，用户ID:', this.userStore.user.id);
        
        const [firstBallRes, blueBallRes, redBallRes, prizeRes] = await Promise.all([
          lotteryApi.getFirstBallHitRate(),
          lotteryApi.getBlueBallHitRate(),
          lotteryApi.getRedBallHitRate(),
          lotteryApi.getPrizeStatistics()
        ]);

        if (firstBallRes.success) this.detailedStats.firstBall = firstBallRes.data;
        if (blueBallRes.success) this.detailedStats.blueBall = blueBallRes.data;
        if (redBallRes.success) this.detailedStats.redBall = redBallRes.data;
        if (prizeRes.success) this.detailedStats.prize = prizeRes.data;

        console.log('获取详细统计数据成功:', this.detailedStats);

      } catch (error) {
        console.error('获取详细统计数据出错:', error);
        this.$message.error('获取详细统计数据时发生网络错误');
      } finally {
        this.detailedStatsLoading = false;
      }
    },

    showComingSoon() {
      this.modalTitle = '功能开发中'
      this.modalMessage = '该功能正在开发中，敬请期待！'
      this.showModal = true
    },


    
    showUpgradeInfo() {
      // 直接弹出客服咨询窗口
      this.showCustomerService()
    },

    showMemberExchange() {
      this.showMemberExchangeModal = true
      this.exchangeCode = ''
    },

    hideMemberExchange() {
      this.showMemberExchangeModal = false
      this.exchangeCode = ''
    },

    async confirmExchange() {
      if (!this.exchangeCode.trim()) {
        this.modalTitle = '提示'
        this.modalMessage = '请输入兑换码'
        this.showModal = true
        return
      }

      // 检查用户是否已登录
      if (!this.userStore.user || !this.userStore.user.id) {
        this.modalTitle = '提示'
        this.modalMessage = '请先登录后再进行会员兑换'
        this.showModal = true
        return
      }

      try {
        console.log('正在激活会员码，用户ID:', this.userStore.user.id, '兑换码:', this.exchangeCode)
        
        // 调用后端激活会员码接口
        const response = await lotteryApi.activateVipCode(this.userStore.user.id, this.exchangeCode)
        
        if (response && response.success) {
          this.hideMemberExchange()
          this.modalTitle = '兑换成功'
          this.modalMessage = '会员码激活成功！您的会员权限已生效，感谢您的使用。'
          this.showModal = true
          
          // 重新获取用户信息以更新会员状态
          try {
            await this.userStore.fetchLoginUser()
          } catch (error) {
            console.error('更新用户信息失败:', error)
          }
        } else {
          this.hideMemberExchange()
          this.modalTitle = '兑换失败'
          this.modalMessage = response?.message || '会员码激活失败，请检查兑换码是否正确。'
          this.showModal = true
        }
      } catch (error) {
        console.error('激活会员码失败:', error)
        this.hideMemberExchange()
        this.modalTitle = '兑换失败'
        this.modalMessage = error?.response?.data?.message || '会员码无效或已过期，请检查后重试。'
        this.showModal = true
      }
    },
    
    hideModal() {
      this.showModal = false
    },
    
    async handleLogout() {
      this.showLogoutConfirm = true
    },

    async confirmLogout() {
      this.showLogoutConfirm = false
      try {
        // 调用后端退出登录接口，清除session
        await lotteryApi.userLogout()
        console.log('服务端退出登录成功')
      } catch (error) {
        console.error('服务端退出登录失败:', error)
        // 即使服务端退出失败，也要清除本地状态
      }
      
      // 清除本地用户状态和统计数据
      userStore.logout()
      this.userStats = {
        predictCount: 0,
        pendingCount: 0,
        hitCount: 0,
        hitRate: '0.00'
      }
      
      // 跳转到登录页面
      this.$router.push('/login')
    },

    cancelLogout() {
      this.showLogoutConfirm = false
    },

    async showCustomerService() {
      this.showCustomerServiceModal = true
      // 等待弹窗打开后再生成二维码
      await this.$nextTick()
      this.generateQRCode()
    },

    hideCustomerService() {
      this.showCustomerServiceModal = false
    },

    async generateQRCode() {
      try {
        const canvas = this.$refs.qrcodeCanvas
        if (canvas) {
          await QRCode.toCanvas(canvas, 'https://work.weixin.qq.com/kfid/kfc69665176351bc02f', {
            width: 200,
            margin: 2,
            color: {
              dark: '#000000',
              light: '#ffffff'
            }
          })
        }
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.modalTitle = '错误'
        this.modalMessage = '生成二维码失败，请稍后重试'
        this.showModal = true
      }
    },

    downloadQRCode() {
      try {
        const canvas = this.$refs.qrcodeCanvas
        if (canvas) {
          // 创建一个链接用于下载
          const link = document.createElement('a')
          link.download = '客服二维码.png'
          link.href = canvas.toDataURL('image/png')
          link.click()
        }
      } catch (error) {
        console.error('下载二维码失败:', error)
        this.modalTitle = '错误'
        this.modalMessage = '下载二维码失败，请稍后重试'
        this.showModal = true
      }
    },

    // 格式化命中率，保留两位小数
    formatHitRate(rate) {
      if (!rate || rate === '0.00') {
        return '0.00'
      }
      
      // 如果是字符串，先转换为数字
      const numRate = typeof rate === 'string' ? parseFloat(rate) : rate
      
      // 保留两位小数
      return numRate.toFixed(2)
    },

    showAIAssistant() {
      if (this.cozeWebSDK) {
        console.log('显示聊天窗口');
        try {
          this.cozeWebSDK.showChatBot();
        } catch (error) {
          console.error('显示聊天窗口失败:', error);
          // 重新初始化并显示
          this.reinitializeCozeChat();
        }
      } else {
        console.log('Coze SDK未初始化，正在重新加载');
        this.reinitializeCozeChat();
      }
    },
    
    // 重新初始化Coze聊天
    async reinitializeCozeChat() {
      try {
        console.log('重新加载Coze SDK');
        
        // 先移除已有的script标签
        const existingScripts = document.querySelectorAll('script[src*="coze"]');
        existingScripts.forEach(script => {
          try {
            document.body.removeChild(script);
          } catch (e) {
            console.warn('移除script标签失败:', e);
          }
        });
        
        // 清空实例
        this.cozeWebSDK = null;
        
        // 重新加载SDK
        const script = document.createElement('script');
        script.src = 'https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.10/libs/cn/index.js';
        script.async = true;
        
        // 使用Promise等待脚本加载完成
        await new Promise((resolve, reject) => {
          script.onload = () => {
            console.log('Coze SDK 重新加载完成');
            resolve();
          };
          script.onerror = (err) => {
            console.error('加载Coze SDK失败:', err);
            reject(new Error('加载SDK失败'));
          };
          document.body.appendChild(script);
        });
        
        console.log('Coze SDK 加载完成，初始化客户端');
        await this.initCozeChatClient();
        
        // 检查是否成功初始化
        if (!this.cozeWebSDK) {
          throw new Error('初始化失败，无法获取有效的聊天实例');
        }
        
        // 等待一段时间确保初始化完成
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        console.log('成功重新初始化，显示聊天窗口');
        this.cozeWebSDK.showChatBot();
      } catch (error) {
        console.error('重新初始化失败:', error);
      }
    },

    // 检查是否为移动设备（基于屏幕宽度）
    checkDeviceType() {
      const isMobile = window.innerWidth <= 768;
      console.log('设备类型检测:', isMobile ? '移动设备' : 'PC设备', '屏幕宽度:', window.innerWidth);
      return isMobile;
    }
  }
}
</script>

<style scoped>
/* 用户中心容器 */
.profile-container {
  min-height: calc(100vh - 85px);
  background: #f0f2f5;
  padding: 0;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

/* 登录提示卡片 */
.login-prompt {
  padding: 30px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 160px);
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.login-card {
  background: white;
  border-radius: 20px;
  padding: 50px 30px;
  text-align: center;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  max-width: 380px;
  width: 100%;
  position: relative;
  overflow: hidden;
}

.login-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
}

.login-icon {
  margin-bottom: 20px;
}

.icon-circle {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}

.lock-icon {
  font-size: 32px;
  color: white;
}

.login-content h3 {
  color: #333;
  margin-bottom: 10px;
  font-size: 20px;
}

.login-content p {
  color: #666;
  margin-bottom: 25px;
  font-size: 14px;
}

.login-actions {
  display: flex;
  gap: 15px;
}

.btn {
  padding: 12px 24px;
  border-radius: 8px;
  text-decoration: none;
  font-weight: bold;
  text-align: center;
  transition: all 0.3s;
  border: none;
  cursor: pointer;
  flex: 1;
}

.btn-primary {
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(229, 62, 62, 0.3);
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.btn-secondary:hover {
  background: #e9ecef;
  border-color: #ccc;
}

/* 会员兑换弹窗 */
.member-exchange-modal {
  max-width: 400px;
  width: 90%;
}

.member-exchange-modal h3 {
  color: #333;
  margin-bottom: 15px;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
}

.member-exchange-modal h3::before {
  content: '💎';
  margin-right: 8px;
  font-size: 20px;
}

.member-exchange-modal p {
  margin-bottom: 20px;
  color: #666;
  line-height: 1.5;
  text-align: center;
}

.exchange-input-container {
  margin-bottom: 25px;
}

.exchange-input {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition: all 0.3s;
  text-align: center;
  letter-spacing: 1px;
}

.exchange-input:focus {
  border-color: #e53e3e;
  box-shadow: 0 0 0 3px rgba(229, 62, 62, 0.1);
}

.exchange-input::placeholder {
  color: #999;
  text-align: center;
}

/* 用户信息卡片 */
.user-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  border-radius: 16px;
  margin: 20px 30px;
  position: relative;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
  min-height: 150px;
}

.user-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.user-avatar {
  margin-right: 20px;
}

.avatar-circle {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-icon {
  font-size: 24px;
  font-weight: bold;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 15px;
}

.user-level {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.level-badge {
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  align-self: flex-start;
  backdrop-filter: blur(10px);
}

.level-badge.premium {
  background: rgba(255, 215, 0, 0.3);
  color: #ffd700;
}

/* 会员样式 */
.level-badge.vip-member {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b45309;
  font-weight: 700;
  font-size: 13px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 215, 0, 0.3);
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
}

/* 体验版用户样式 */
.level-badge.trial-user {
  background: rgba(255, 255, 255, 0.3);
  color: rgba(255, 255, 255, 0.9);
  font-weight: 400;
  font-size: 12px;
}

.expire-date {
  font-size: 14px;
  opacity: 0.8;
  margin-top: 12px;
}

.user-actions {
  position: absolute;
  top: 15px;
  right: 15px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.exchange-btn {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  backdrop-filter: blur(10px);
  padding: 8px 12px;
  gap: 6px;
}

.exchange-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.exchange-icon {
  font-size: 16px;
}

.logout-wrapper {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  backdrop-filter: blur(10px);
  padding: 8px;
  height: 35px;
}

.logout-wrapper:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.logout-icon-img {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

.exchange-icon {
  animation: sparkle 2s infinite ease-in-out;
}

.exchange-text {
  color: white;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

@keyframes sparkle {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

/* 会员权益 */
.benefits-section {
  background: white;
  margin: 15px 30px;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.benefits-section h3 {
  margin-bottom: 8px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
  padding: 10px 20px;
}

.benefits-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 12px;
}

.benefit-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 6px;
  border-radius: 6px;
  transition: transform 0.3s;
}

.benefit-item:hover {
  transform: translateY(-1px);
}

.benefit-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  margin-bottom: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
}

.benefit-label {
  font-size: 15px;
  color: #666;
  font-weight: 500;
  line-height: 1.1;
}

.upgrade-button {
  text-align: center;
  margin-top: 8px;
}

.btn-upgrade {
  background: linear-gradient(135deg, #ffd700, #ffb347);
  color: #333;
  border: none;
  padding: 8px 20px;
  border-radius: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.btn-upgrade:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 215, 0, 0.3);
}

/* 功能菜单 */
.menu-section {
  background: white;
  margin: 20px 30px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

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

.menu-item:hover {
  background-color: #f8f9fa;
}

.menu-icon {
  margin-right: 18px;
  width: 26px;
  height: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-icon-img {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.menu-label {
  font-size: 16px;
  color: #333;
  flex: 1;
}

.ai-label {
  color: #1296db;
  font-weight: bold;
}

.menu-arrow {
  color: #ccc;
  font-size: 18px;
}

/* 统计信息 */
.stats-section {
  background: white;
  margin: 20px 30px;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.stats-section h3 {
  margin-bottom: 25px;
  color: #333;
  font-size: 20px;
  font-weight: 700;
  position: relative;
  padding-left: 10px;
}

/* 加载状态 */
.stats-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: #666;
}

.loading-spinner {
  font-size: 16px;
}

/* 统计卡片网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-top: 15px;
}

.detailed-stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-top: 15px;
}

/* 统计卡片样式 */
.stat-item {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px 15px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.stat-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  background: #fff;
  border-color: rgba(229, 62, 62, 0.2);
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display: inline-block;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  line-height: 1.4;
}

/* 奖金统计样式 */
.total-prize-summary {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 25px;
  padding: 20px;
  background: linear-gradient(135deg, #fffaf0, #fff5f5);
  border-radius: 10px;
  border: 1px solid rgba(229, 62, 62, 0.1);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.03);
}

.total-prize-label {
  color: #333;
  margin-right: 10px;
}

.prize-amount {
  color: #e53e3e;
  font-size: 24px;
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__row:hover td) {
  background-color: #fff9f9 !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .detailed-stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .stat-label {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .detailed-stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .stat-item {
    padding: 15px 10px;
  }
  
  .stat-number {
    font-size: 20px;
    margin-bottom: 5px;
  }
  
  .stat-label {
    font-size: 12px;
  }
}

/* 会员续费提醒 */
.vip-renewal-notice {
  background: linear-gradient(135deg, #fff3cd, #ffeaa7);
  margin: 15px 30px;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #ffc107;
  box-shadow: 0 4px 15px rgba(255, 193, 7, 0.2);
  animation: renewalPulse 2s ease-in-out infinite;
}

.renewal-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.renewal-icon {
  font-size: 32px;
  flex-shrink: 0;
}

.renewal-text h4 {
  color: #856404;
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 5px;
}

.renewal-text p {
  color: #664d03;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

.renewal-link {
  color: #e53e3e;
  font-weight: 700;
  cursor: pointer;
  text-decoration: underline;
  transition: all 0.3s ease;
}

.renewal-link:hover {
  color: #d32f2f;
  text-shadow: 0 1px 2px rgba(229, 62, 62, 0.3);
}

@keyframes renewalPulse {
  0%, 100% {
    transform: scale(1);
    box-shadow: 0 4px 15px rgba(255, 193, 7, 0.2);
  }
  50% {
    transform: scale(1.02);
    box-shadow: 0 6px 20px rgba(255, 193, 7, 0.3);
  }
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  max-width: 300px;
  width: 90%;
  text-align: center;
}

.modal-content h3 {
  margin-bottom: 15px;
  color: #333;
}

.modal-content p {
  margin-bottom: 20px;
  color: #666;
  line-height: 1.5;
}

.modal-content .btn {
  width: 100px;
  margin: 0 auto;
}

/* 退出登录确认弹窗 */
.logout-modal {
  max-width: 350px;
}

.logout-modal h3 {
  color: #f44336;
  margin-bottom: 15px;
  font-size: 20px;
  font-weight: 600;
}

.logout-modal p {
  margin-bottom: 25px;
  color: #666;
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.modal-actions .btn {
  width: 100px;
  margin: 0;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-danger {
  background: linear-gradient(135deg, #f44336, #e57373);
  color: white;
  border: none;
}

.btn-danger:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(244, 67, 54, 0.3);
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.btn-secondary:hover {
  background: #e9ecef;
  border-color: #ccc;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .profile-container {
    max-width: 100%;
    margin: 0;
    min-height: calc(100vh - 80px);
  }
  
  .user-card,
  .benefits-section,
  .menu-section,
  .stats-section,
  .vip-renewal-notice {
    margin: 12px 18px;
    padding: 18px;
  }
  
  .user-card {
    min-height: 150px;
  }
  
  .user-actions {
    gap: 15px;
  }
  
  .exchange-btn {
    padding: 6px 10px;
    gap: 4px;
  }
  
  .exchange-icon {
    font-size: 14px;
  }
  
  .logout-wrapper {
    padding: 6px;
    height: 32px;
  }
  
  .logout-icon-img {
    width: 18px;
    height: 18px;
  }
  
  .exchange-text {
    font-size: 11px;
  }
  
  .benefits-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 18px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .actions-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  /* 中等屏幕功能菜单优化 */
  .menu-item {
    padding: 18px 22px;
  }
  
  .menu-icon {
    font-size: 21px;
    margin-right: 16px;
  }
  
  .menu-label {
    font-size: 14px;
  }
  
  /* 中等屏幕统计区块优化 */
  .stats-section h3,
  .vip-renewal-notice h4 {
    margin-bottom: 18px;
    font-size: 17px;
  }
  
  .stat-item {
    padding: 14px 10px;
  }
  
  .stat-number {
    font-size: 26px;
  }
  
  .action-item {
    padding: 20px 15px;
  }
  
  .action-icon {
    font-size: 26px;
    margin-bottom: 8px;
  }
  
  .action-label {
    font-size: 13px;
  }
  
  .login-actions {
    flex-direction: column;
  }
  
  .login-card {
    padding: 30px 20px;
    margin: 0 20px;
  }
}

@media (max-width: 480px) {
  .benefits-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .actions-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .action-item {
    padding: 12px 8px;
  }
  
  .action-icon {
    font-size: 22px;
    margin-bottom: 6px;
  }
  
  .action-label {
    font-size: 11px;
    line-height: 1.2;
  }
  
  .user-card,
  .benefits-section,
  .menu-section,
  .stats-section,
  .vip-renewal-notice {
    margin: 8px 12px;
    padding: 12px;
  }
  
  /* 功能菜单紧凑化 */
  .menu-item {
    padding: 15px 18px;
  }
  
  .menu-icon {
    font-size: 20px;
    margin-right: 15px;
    width: 24px;
  }
  
  .menu-label {
    font-size: 14px;
  }
  
  .menu-arrow {
    font-size: 16px;
  }
  
  /* 统计区块紧凑化 */
  .stats-section {
    padding: 15px;
  }
  
  .stats-section h3 {
    margin-bottom: 15px;
    font-size: 16px;
  }
  
  .stats-grid {
    gap: 12px;
  }
  
  .stat-item {
    padding: 12px 8px;
  }
  
  .stat-number {
    font-size: 24px;
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 12px;
  }
  
  /* 快捷入口紧凑化 */
  .vip-renewal-notice {
    padding: 15px;
    margin-bottom: 15px;
  }
  
  .vip-renewal-notice h4 {
    margin-bottom: 10px;
    font-size: 15px;
  }
  
  .benefits-section {
    padding: 12px;
  }
  
  .benefits-section h3 {
    margin-bottom: 10px;
    font-size: 15px;
  }
  
  .benefits-grid {
    gap: 10px;
    margin-bottom: 12px;
  }
  
  .benefit-item {
    padding: 6px;
  }
  
  .benefit-icon {
    width: 30px;
    height: 30px;
    font-size: 14px;
    margin-bottom: 4px;
  }
  
  .benefit-label {
    font-size: 15px;
    line-height: 1.2;
  }
  
  .btn-upgrade {
    padding: 8px 16px;
    font-size: 13px;
    border-radius: 16px;
  }
  
  .upgrade-button {
    margin-top: 10px;
  }
  
  .renewal-content {
    gap: 10px;
  }
  
  .renewal-icon {
    font-size: 28px;
  }
  
  .renewal-text h4 {
    font-size: 15px;
  }
  
  .renewal-text p {
    font-size: 13px;
  }
  
  /* 悬浮客服移动端适配 */
  .floating-customer-service {
    bottom: 110px;
    right: 15px;
  }
  
  .service-avatar {
    width: 50px;
    height: 50px;
  }
  
  .service-avatar .avatar-img {
    width: 36px;
    height: 36px;
  }
  
  .online-indicator {
    width: 10px;
    height: 10px;
  }
  
  .service-bubble {
    padding: 8px 12px;
  }
  
  .bubble-text {
    font-size: 12px;
  }
}



/* 悬浮在线客服 */
.floating-customer-service {
  position: absolute;
  bottom: 15px;
  right: 15px;
  z-index: 999;
  cursor: pointer;
  animation: floatBounce 3s ease-in-out infinite;
}

.floating-service-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-direction: column-reverse;
}

.service-avatar {
  position: relative;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.service-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.2);
}

.service-avatar .avatar-img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: contain;
  padding: 2px;
}

.online-indicator {
  position: absolute;
  bottom: 4px;
  right: 4px;
  width: 12px;
  height: 12px;
  background: #00d976;
  border-radius: 50%;
  border: 2px solid white;
  animation: pulse 2s infinite;
}

.service-bubble {
  position: relative;
  background: rgba(255, 255, 255, 0.95);
  padding: 8px 12px;
  border-radius: 16px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  opacity: 0;
  transform: translateY(10px);
  transition: all 0.3s ease;
  white-space: nowrap;
  backdrop-filter: blur(10px);
}

.floating-customer-service:hover .service-bubble {
  opacity: 1;
  transform: translateY(0);
}

.bubble-text {
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.bubble-arrow {
  position: absolute;
  bottom: -6px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-top: 6px solid rgba(255, 255, 255, 0.95);
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
}

@keyframes floatBounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-8px);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 客服二维码弹窗 */
.customer-service-modal {
  max-width: 420px;
  width: 90%;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.customer-service-modal h3 {
  color: #333;
  margin-bottom: 15px;
  font-size: 20px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  color: #333;
  margin: -30px -30px 20px -30px;
  border-bottom: 2px solid #e0e0e0;
}

.customer-service-modal h3::before {
  content: '💬';
  margin-right: 8px;
  font-size: 22px;
}

.customer-service-modal p {
  margin-bottom: 20px;
  color: #666;
  line-height: 1.5;
  text-align: center;
  font-size: 15px;
}

.qrcode-container {
  margin-bottom: 25px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 2px dashed #e0e0e0;
}

.qrcode-canvas {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
}

.service-info {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
  margin-bottom: 20px;
  border-left: 4px solid #666;
}

.service-tip {
  color: #666;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

.service-time {
  color: #666;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.service-time::before {
  content: '🕐';
  font-size: 14px;
}

.modal-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.btn-secondary:hover {
  background: #e9ecef;
  border-color: #ccc;
}

/* 用户信息加载状态 */
.user-info-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.user-info-loading .loading-spinner {
  color: #666;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info-loading .loading-spinner::before {
  content: '';
  width: 20px;
  height: 20px;
  border: 2px solid #e0e0e0;
  border-top: 2px solid #666;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Coze AI 聊天助手样式 */
#coze-chat-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}
</style> 