<template>
  <view class="page-rank">
    <!-- 顶部标题卡片 -->
    <view class="page-title-card">
      <text class="page-title-text">量化选股大师</text>
    </view>
    
    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper" :class="{ 'blur-content': !isLoggedIn }">
        <!-- 我的模拟资产卡片 -->
        <view class="portfolio-card">
          <view class="portfolio-header">
            <view class="portfolio-icon">💼</view>
            <text class="portfolio-title">我的模拟资产</text>
          </view>
          
          <view class="portfolio-content">
            <view class="portfolio-main">
              <view class="portfolio-label">当前账户余额 (¥)</view>
              <view class="portfolio-amount">{{ formatAmount(portfolio.balance) }}</view>
            </view>
            <view class="portfolio-profit">
              <view class="profit-label">总盈亏 / 收益率</view>
              <view :class="['profit-value', portfolio.profitRate >= 0 ? 'profit-positive' : 'profit-negative']">
                ¥ {{ formatProfit(portfolio.profit) }} ({{ formatRate(portfolio.profitRate) }}%)
              </view>
            </view>
          </view>
        </view>

        <!-- 模拟交易排行榜 -->
        <view class="leaderboard-section">
          <view class="section-header">
            <view class="trophy-icon">🏆</view>
            <text class="section-title">模拟交易排行榜</text>
          </view>

          <!-- 当前用户排名 -->
          <view class="my-rank-card">
            <view class="rank-number">#{{ myRank.rank }}</view>
            <view class="rank-info">
              <text class="rank-name">您 (本期收益)</text>
            </view>
            <view :class="['rank-rate', myRank.rate >= 0 ? 'rate-positive' : 'rate-negative']">
              {{ myRank.rate >= 0 ? '+' : '' }}{{ myRank.rate }}%
            </view>
          </view>

          <!-- 排行榜列表 -->
          <view class="leaderboard-list">
            <view 
              v-for="(item, index) in leaderboard" 
              :key="index"
              class="leaderboard-item"
            >
              <view :class="['rank-badge', getRankClass(item.rank)]">
                #{{ item.rank }}
              </view>
              <view class="user-info">
                <text class="user-name">{{ item.name }}</text>
              </view>
              <view :class="['user-rate', item.rate >= 0 ? 'rate-positive' : 'rate-negative']">
                {{ item.rate >= 0 ? '+' : '' }}{{ item.rate }}%
              </view>
            </view>
          </view>

          <view class="leaderboard-note">
            <text class="note-text">排名每日更新，收益基于系统信号的模拟交易。</text>
          </view>
        </view>

        <!-- 预留底部空间 -->
        <view class="bottom-safe-area"></view>
      </view>
    </scroll-view>

    <!-- 未登录遮罩层 -->
    <view v-if="!isLoggedIn" class="login-mask">
      <view class="login-prompt">
        <view class="lock-icon">🔒</view>
        <text class="prompt-title">登录后查看完整数据</text>
        <text class="prompt-desc">使用微信授权快速登录</text>
        
        <!-- 微信授权登录按钮 -->
        <button 
          class="login-button-native" 
          open-type="getPhoneNumber" 
          @getphonenumber="onGetPhoneNumber"
        >
          <text class="button-icon">📱</text>
          <text>微信授权登录</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserPortfolio, getLeaderboard } from '../../utils/api.js'
import { isLoggedIn as checkIsLoggedIn, wxAuthLogin } from '../../utils/auth.js'

// 登录状态
const isLoggedIn = ref(false)

const portfolio = ref({
  balance: 100000,
  profit: 0,
  profitRate: 0
})

const myRank = ref({
  rank: 5,
  rate: 0
})

// 模糊数据 - 未登录时显示
const mockLeaderboard = [
  { rank: 1, name: '量化王者 ***', rate: 35.2 },
  { rank: 2, name: '短线猎手 ***', rate: 28.9 },
  { rank: 3, name: '趋势追踪者 ***', rate: 22.1 },
  { rank: 4, name: '稳健投资 ***', rate: 18.5 },
  { rank: 5, name: '价值发现 ***', rate: 15.3 }
]

const leaderboard = ref(mockLeaderboard)

const formatAmount = (amount) => {
  return amount.toLocaleString('zh-CN')
}

const formatProfit = (profit) => {
  return Math.abs(profit).toLocaleString('zh-CN')
}

const formatRate = (rate) => {
  return rate.toFixed(2)
}

const getRankClass = (rank) => {
  if (rank === 1) return 'rank-first'
  if (rank === 2) return 'rank-second'
  if (rank === 3) return 'rank-third'
  return ''
}

// 处理手机号授权 - 静默登录
const onGetPhoneNumber = async (e) => {
  console.log('[模拟排名] 获取手机号回调:', e.detail)
  
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    const phoneCode = e.detail.code
    console.log('[模拟排名] phoneCode:', phoneCode)
    
    uni.showLoading({
      title: '登录中...',
      mask: true
    })
    
    try {
      // 获取微信登录code
      const loginRes = await uni.login()
      console.log('[模拟排名] uni.login完整响应:', loginRes)
      console.log('[模拟排名] 微信登录code:', loginRes.code)
      
      if (!loginRes.code) {
        throw new Error('获取微信登录code失败')
      }
      
      // 调用后端登录接口（只传code和phoneCode）
      const result = await wxAuthLogin(loginRes.code, phoneCode)      
      uni.hideLoading()
      
      if (result) {
        // 登录成功，重新加载数据
        checkLoginAndLoadData()
      }
    } catch (error) {
      uni.hideLoading()
      console.error('[模拟排名] 登录失败:', error)
    }
  } else {
    // 用户拒绝授权手机号
    uni.showToast({
      title: '需要授权手机号才能登录',
      icon: 'none',
      duration: 2000
    })
  }
}

// 检查登录状态并加载数据
const checkLoginAndLoadData = () => {
  isLoggedIn.value = checkIsLoggedIn()
  console.log('[模拟排名] 登录状态:', isLoggedIn.value)
  
  if (isLoggedIn.value) {
    loadRealData()
  } else {
    // 未登录，显示模糊数据
    leaderboard.value = mockLeaderboard
  }
}

// 加载真实数据
const loadRealData = async () => {
  try {
    const portfolioRes = await getUserPortfolio()
    if (portfolioRes.code === 0 && portfolioRes.data) {
      portfolio.value = portfolioRes.data
    }
  } catch (err) {
    console.error('获取资产数据失败:', err)
  }

  try {
    const leaderboardRes = await getLeaderboard()
    if (leaderboardRes.code === 0 && leaderboardRes.data) {
      leaderboard.value = leaderboardRes.data.list || []
      myRank.value = leaderboardRes.data.myRank || { rank: 5, rate: 0 }
    }
  } catch (err) {
    console.error('获取排行榜数据失败:', err)
  }
}

onMounted(() => {
  checkLoginAndLoadData()
})
</script>

<style>
.page-rank {
  display: flex;
  flex-direction: column;
  background: #f5f6fb;
  height: 100vh;
}

.page-title-card {
  background: #ffffff;
  padding: 30rpx 0;
  text-align: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  border-radius: 0;
}

.page-title-text {
  font-size: 36rpx;
  font-weight: 800;
  color: #3F51F7;
  letter-spacing: 2rpx;
}

.scroll-view {
  flex: 1;
  height: 0;
}

.content-wrapper {
  padding: 32rpx;
}

/* 模拟资产卡片 */
.portfolio-card {
  background: linear-gradient(135deg, #5d55e8, #7568ff);
  border-radius: 24rpx;
  padding: 40rpx 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 16rpx 40rpx rgba(93, 85, 232, 0.3);
}

.portfolio-header {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
}

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

.portfolio-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}

.portfolio-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.portfolio-main {
  flex: 1;
}

.portfolio-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 12rpx;
}

.portfolio-amount {
  font-size: 56rpx;
  font-weight: 700;
  color: #ffffff;
  line-height: 1.2;
}

.portfolio-profit {
  text-align: right;
}

.profit-label {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 8rpx;
}

.profit-value {
  font-size: 28rpx;
  font-weight: 600;
}

.profit-positive {
  color: #4fffb0;
}

.profit-negative {
  color: #ff6b9d;
}

/* 排行榜区域 */
.leaderboard-section {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 16rpx 40rpx rgba(37, 52, 94, 0.08);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.trophy-icon {
  font-size: 36rpx;
  margin-right: 12rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222222;
}

/* 当前用户排名卡片 */
.my-rank-card {
  background: linear-gradient(135deg, #fff9e6, #fffbf0);
  border: 2rpx solid #ffd966;
  border-radius: 16rpx;
  padding: 24rpx 28rpx;
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.rank-number {
  font-size: 40rpx;
  font-weight: 700;
  color: #ff9800;
  margin-right: 24rpx;
  min-width: 80rpx;
}

.rank-info {
  flex: 1;
}

.rank-name {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.rank-rate {
  font-size: 32rpx;
  font-weight: 700;
}

.rate-positive {
  color: #00c853;
}

.rate-negative {
  color: #ff5252;
}

/* 排行榜列表 */
.leaderboard-list {
  margin-bottom: 24rpx;
}

.leaderboard-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f5f6fb;
}

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

.rank-badge {
  font-size: 32rpx;
  font-weight: 700;
  color: #666666;
  margin-right: 24rpx;
  min-width: 80rpx;
}

.rank-first {
  color: #ff5252;
}

.rank-second {
  color: #ff9800;
}

.rank-third {
  color: #ffc107;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 28rpx;
  color: #333333;
}

.user-rate {
  font-size: 32rpx;
  font-weight: 700;
}

.leaderboard-note {
  padding-top: 16rpx;
  border-top: 1rpx solid #f5f6fb;
}

.note-text {
  font-size: 22rpx;
  color: #999999;
  line-height: 1.6;
}

.bottom-safe-area {
  height: 80rpx;
}

/* 模糊效果 */
.blur-content {
  filter: blur(8rpx);
  pointer-events: none;
}

/* 登录遮罩层 */
.login-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.login-prompt {
  width: 560rpx;
  max-width: 560rpx;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 50rpx 40rpx;
  margin: 0 auto;
  text-align: center;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}

.lock-icon {
  font-size: 72rpx;
  margin-bottom: 20rpx;
}

.prompt-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #222222;
  margin-bottom: 12rpx;
}

.prompt-desc {
  display: block;
  font-size: 24rpx;
  color: #999999;
  line-height: 1.5;
  margin-bottom: 32rpx;
}

.login-button-native {
  width: 100%;
  height: 80rpx;
  background: linear-gradient(135deg, #4CAF50, #66BB6A);
  color: #ffffff;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: 600;
  box-shadow: 0 8rpx 24rpx rgba(76, 175, 80, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  padding: 0;
  line-height: 80rpx;
}

.login-button-native::after {
  border: none;
}

.button-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
}
</style>
