<template>
  <view class="page-container">
    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper">
        <!-- 超短精选池标题 -->
        <view class="pool-header-section">
          <view class="pool-header">
            <text class="pool-icon">⚡</text>
            <text class="pool-title">超短精选池</text>
          </view>
          <text class="pool-desc">今日更新,高频捕捉短期爆发机会</text>
        </view>

        <!-- 性能指标卡片（动态计算） -->
        <PerformanceCard 
          :successRate="performanceStats.successRate" 
          :profitRate="performanceStats.avgTrend" 
          :totalTrades="performanceStats.totalCount" 
        />

        <!-- 超短精选池区域 -->
        <view class="card pool-card">
          <!-- 未购买时显示锁定状态 -->
          <view v-if="!isPurchased" class="locked-content">
            <view class="lock-icon-wrapper">
              <text class="lock-icon">🔒</text>
            </view>
            <text class="lock-text">权限锁定: 查看 超短精选池 </text>
            <text class="lock-desc">超短池为每日实时更新,捕捉短期爆发机会。</text>
            <view class="unlock-button" @click="showPurchaseModal">
              <text class="unlock-button-text">立即打赏</text>
            </view>
          </view>

          <!-- 已购买时显示内容 -->
          <view v-else class="unlocked-content">
            <view class="unlocked-header">
              <view class="unlocked-dot"></view>
              <text class="unlocked-tip">已解锁内容</text>
            </view>
            <view class="stock-list">
              <view class="stock-item" v-for="(stock, index) in stockList" :key="index">
                <view class="stock-main">
                  <view class="stock-info">
                    <text class="stock-name">{{ stock.name }}</text>
                    <text class="stock-code">{{ stock.code }}</text>
                  </view>
                  <view class="stock-quote">
                    <text class="stock-price">{{ stock.currentPrice || '-' }}</text>
                    <text :class="['stock-change', getChangeClass(stock.changePercent)]">{{ stock.changePercent || '-' }}</text>
                  </view>
                </view>
                <view class="stock-action">
                  <view class="add-btn" @click="addToMyStocks(stock)">
                    <text class="add-btn-text">+ 自选</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 历史股票池回顾（仅订阅用户可见） -->
        <HistorySearchCard 
          :poolType="1"
          :canSearch="isPurchased"
          @dateChange="onDateChange"
        />

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

    <!-- 购买弹窗 -->
    <PurchaseModal
      :visible="showModal"
      icon="💰"
      title="打赏解锁"
      description="支持作者，解锁今日超短池内容"
      amountLabel="打赏金额："
      :amount="shortPrice"
      @close="closePurchaseModal"
      @confirm="handlePurchase"
    />
  </view>
</template>

<script setup>
import { ref, onUnmounted, reactive } from 'vue'
import { onLoad, onShow, onHide } from '@dcloudio/uni-app'
import { isLoggedIn as checkLoginStatus } from '../../utils/auth.js'
import { getStockQuotes, addUserStock, getStockPoolList, createOrder, wxPay, checkSubscription, getPaymentConfig, queryOrder, getStockHistoryStats } from '../../utils/api.js'
import PurchaseModal from '../../components/PurchaseModal.vue'
import PerformanceCard from '../../components/PerformanceCard.vue'
import HistorySearchCard from '../../components/HistorySearchCard.vue'

const isPurchased = ref(false)
const showModal = ref(false)
const isLoggedIn = ref(false)
const isPageVisible = ref(false) // 页面是否可见
const shortPrice = ref(1) // 超短池价格，默认1

const stockList = ref([])
let refreshTimer = null

// 性能统计数据
const performanceStats = reactive({
  successRate: '0%',
  avgTrend: '+0%',
  totalCount: 0
})

// 日期变化时加载统计数据
const onDateChange = async ({ startDate, endDate, poolType }) => {
  try {
    const res = await getStockHistoryStats({
      startDate,
      endDate,
      poolType
    })
    if (res.code === 200 && res.data) {
      performanceStats.successRate = res.data.successRate || '0%'
      performanceStats.avgTrend = res.data.avgTrend || '+0%'
      performanceStats.totalCount = res.data.totalCount || 0
    }
  } catch (e) {
    console.error('加载统计数据失败:', e)
  }
}

// 获取涨跌样式
const getChangeClass = (changePercent) => {
  if (!changePercent || changePercent === '-') return ''
  return changePercent.startsWith('+') ? 'text-red' : 'text-green'
}

// 获取随机刷新间隔 (2000-3000ms)
const getRandomInterval = () => 2000 + Math.random() * 1000

// 启动自动刷新
const startAutoRefresh = () => {
  if (!isPageVisible.value) return
  stopAutoRefresh()
  
  const scheduleNextRefresh = () => {
    if (!isPageVisible.value) {
      stopAutoRefresh()
      return
    }
    
    refreshTimer = setTimeout(async () => {
      if (!isPageVisible.value) {
        stopAutoRefresh()
        return
      }
      await loadStockPool()
      scheduleNextRefresh()
    }, getRandomInterval())
  }
  
  scheduleNextRefresh()
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearTimeout(refreshTimer)
    refreshTimer = null
  }
}

// 检查登录状态
const checkLogin = () => {
  isLoggedIn.value = checkLoginStatus()
  return isLoggedIn.value
}

// 检查购买状态（从后端查询）
const checkPurchaseStatus = async () => {
  if (!checkLogin()) {
    isPurchased.value = false
    stopAutoRefresh()
    return
  }
  
  try {
    const res = await checkSubscription(1)  // 1=超短池
    if (res.code === 200 && res.data.hasSubscription) {
      isPurchased.value = true
      loadAndStartRefresh()
    } else {
      isPurchased.value = false
      stopAutoRefresh()
    }
  } catch (e) {
    console.error('检查订阅状态失败:', e)
    isPurchased.value = false
    stopAutoRefresh()
  }
}

// 加载股票池数据
const loadStockPool = async () => {
  try {
    const res = await getStockPoolList(1)  // 1=超短池
    if (res.code === 200 && res.data) {
      stockList.value = res.data
    }
  } catch (e) {
    console.error('加载股票池失败:', e)
  }
}

// 加载数据并启动自动刷新
const loadAndStartRefresh = async () => {
  await loadStockPool()
  startAutoRefresh()
}

// 显示购买弹窗（需要登录）
const showPurchaseModal = async () => {
  if (!checkLogin()) {
    uni.showModal({
      title: '登录提示',
      content: '此功能需要登录后使用，是否前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/login' })
        }
      }
    })
    return
  }
  
  // 获取最新价格配置
  try {
    const res = await getPaymentConfig(1)  // 1=超短池
    if (res.code === 200 && res.data) {
      shortPrice.value = res.data.price || 1
    }
  } catch (e) {
    console.error('获取价格配置失败:', e)
  }
  
  showModal.value = true
}

const closePurchaseModal = () => {
  showModal.value = false
}

// 轮询订单状态，确认服务端已处理支付回调
const pollOrderStatus = async (orderNo, maxRetries = 5, interval = 1000) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const res = await queryOrder(orderNo)
      if (res.code === 200 && res.data && res.data.orderStatus === 1) {
        return true
      }
    } catch (e) {
      console.log('查询订单状态失败:', e)
    }
    if (i < maxRetries - 1) {
      await new Promise(r => setTimeout(r, interval))
    }
  }
  return false
}

// 处理购买（调用后端支付接口）
const handlePurchase = async () => {
  try {
    uni.showLoading({ title: '正在支付...' })
    
    // 1. 创建订单
    const res = await createOrder({ poolType: 1 })  // 1=超短池
    if (res.code !== 200) {
      throw new Error(res.message || '创建订单失败')
    }
    
    const orderNo = res.data.orderNo
    uni.hideLoading()
    
    // 2. 调起微信支付
    await wxPay(res.data)
    
    // 3. 轮询确认订单状态
    uni.showLoading({ title: '确认支付结果...' })
    const confirmed = await pollOrderStatus(orderNo)
    uni.hideLoading()
    
    if (confirmed) {
      isPurchased.value = true
      closePurchaseModal()
      uni.showToast({ title: '支付成功', icon: 'success' })
      loadAndStartRefresh()
    } else {
      closePurchaseModal()
      uni.showToast({ title: '支付处理中，请稍后刷新', icon: 'none' })
    }
  } catch (e) {
    uni.hideLoading()
    uni.showToast({ title: e.message || '支付失败', icon: 'none' })
  }
}

// 添加到我的股票
const addToMyStocks = async (stock) => {
  if (!checkLogin()) {
    uni.showModal({
      title: '登录提示',
      content: '添加自选股票需要登录，是否前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/login' })
        }
      }
    })
    return
  }

  try {
    uni.showLoading({ title: '添加中...' })
    
    let currentPrice = null
    try {
      const quoteRes = await getStockQuotes(stock.code)
      if (quoteRes.code === 200 && quoteRes.data && quoteRes.data.length > 0) {
        currentPrice = quoteRes.data[0].currentPrice
      }
    } catch (e) {
      console.error('获取行情数据失败:', e)
    }
    
    const addRes = await addUserStock({
      stockCode: stock.code,
      stockName: stock.name,
      currentPrice: currentPrice,
      poolType: 1  // 超短池
    })
    
    uni.hideLoading()
    
    if (addRes.code === 200 && addRes.data === true) {
      uni.showToast({ title: '添加成功', icon: 'success' })
    } else if (addRes.code === 200 && addRes.data === false) {
      uni.showToast({ title: '股票已存在', icon: 'none' })
    } else {
      uni.showToast({ title: addRes.message || '添加失败', icon: 'none' })
    }
  } catch (e) {
    uni.hideLoading()
    console.error('添加股票失败:', e)
    uni.showToast({ title: '添加失败', icon: 'none' })
  }
}

onLoad(() => {
  console.log('[超短池] onLoad')
  isPageVisible.value = true
  checkPurchaseStatus()
})

onShow(() => {
  console.log('[超短池] onShow')
  isPageVisible.value = true
  checkPurchaseStatus()
  uni.setNavigationBarTitle({ title: '量化交易大师' })
})

onHide(() => {
  console.log('[超短池] onHide')
  isPageVisible.value = false
  stopAutoRefresh()
})

onUnmounted(() => {
  isPageVisible.value = false
  stopAutoRefresh()
})
</script>

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

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

.content-wrapper {
  padding: 32rpx;
  background: #f5f6fb;
  min-height: 100%;
}

.card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 16rpx 40rpx rgba(37, 52, 94, 0.08);
  margin-bottom: 32rpx;
}

.pool-header-section {
  margin-bottom: 24rpx;
}

.pool-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.pool-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
}

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

.pool-desc {
  font-size: 26rpx;
  color: #666a7f;
}

.pool-card {
  padding: 32rpx;
}

.locked-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0 40rpx;
}

.lock-icon-wrapper {
  margin-bottom: 32rpx;
}

.lock-icon {
  font-size: 80rpx;
}

.lock-text {
  font-size: 28rpx;
  color: #222222;
  margin-bottom: 16rpx;
  text-align: center;
}

.lock-desc {
  font-size: 24rpx;
  color: #9ca2b5;
  margin-bottom: 48rpx;
  text-align: center;
  line-height: 1.6;
}

.unlock-button {
  width: 100%;
  background: linear-gradient(135deg, #5d55e8, #7568ff);
  border-radius: 16rpx;
  padding: 28rpx 0;
  text-align: center;
  box-shadow: 0 12rpx 24rpx rgba(93, 85, 232, 0.4);
}

.unlock-button-text {
  font-size: 30rpx;
  font-weight: 600;
  color: #ffffff;
}

.unlocked-content {
  padding: 8rpx 0;
}

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

.unlocked-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #3abf81;
  margin-right: 12rpx;
}

.unlocked-tip {
  font-size: 26rpx;
  font-weight: 500;
  color: #3abf81;
  letter-spacing: 1rpx;
}

.stock-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.stock-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 24rpx;
  background: #fafbfc;
  border-radius: 20rpx;
}

.stock-main {
  display: flex;
  align-items: center;
  flex: 1;
}

.stock-info {
  display: flex;
  flex-direction: column;
  width: 140rpx;
}

.stock-name {
  font-size: 30rpx;
  font-weight: 700;
  color: #1a1a2e;
  margin-bottom: 6rpx;
  letter-spacing: 1rpx;
}

.stock-code {
  font-size: 22rpx;
  color: #9ca3af;
  font-weight: 400;
}

.stock-quote {
  display: flex;
  align-items: center;
  flex: 1;
  justify-content: flex-end;
}

.stock-price {
  font-size: 32rpx;
  font-weight: 800;
  color: #1a1a2e;
  margin-right: 16rpx;
  min-width: 120rpx;
  text-align: right;
  font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', sans-serif;
}

.stock-change {
  font-size: 24rpx;
  font-weight: 600;
  padding: 6rpx 12rpx;
  border-radius: 8rpx;
  min-width: 100rpx;
  text-align: center;
}

.text-red {
  color: #ef4444;
  background: rgba(239, 68, 68, 0.1);
}

.text-green {
  color: #22c55e;
  background: rgba(34, 197, 94, 0.1);
}

.stock-action {
  margin-left: 20rpx;
}

.add-btn {
  background: #5B5AEA;
  border-radius: 40rpx;
  padding: 16rpx 28rpx;
  box-shadow: 0 8rpx 20rpx rgba(91, 90, 234, 0.3);
}

.add-btn-text {
  font-size: 24rpx;
  font-weight: 600;
  color: #ffffff;
  letter-spacing: 1rpx;
}

.bottom-safe-area {
  height: 80rpx;
}
</style>
