<template>
  <view class="page-rank">
    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper" :class="{ 'blur-content': !isLoggedIn }">
        <!-- 上证指数卡片 -->
        <view class="index-card">
          <view class="index-left">
            <view class="index-price-row">
              <text :class="['index-price', getIndexChangeClass(indexData.changePercent)]">
                {{ formatIndexPrice(indexData.currentPrice) }}
              </text>
              <text :class="['index-change', getIndexChangeClass(indexData.changePercent)]">
                {{ indexData.priceChange || '--' }}
              </text>
            </view>
            <view class="index-name-row">
              <text class="index-name">{{ indexData.stockName || '上证指数' }}</text>
              <text :class="['index-percent', getIndexChangeClass(indexData.changePercent)]">
                {{ indexData.changePercent || '--' }}
              </text>
            </view>
          </view>
        </view>

        <!-- 分段控制器 -->
        <view class="segment-control">
          <view class="segment-slider" :class="{ 'slider-right': viewMode === 'table' }"></view>
          <view 
            class="segment-item" 
            :class="{ 'segment-active': viewMode === 'list' }"
            @click="setViewMode('list')"
          >
            <text class="segment-text">热力图</text>
          </view>
          <view 
            class="segment-item" 
            :class="{ 'segment-active': viewMode === 'table' }"
            @click="setViewMode('table')"
          >
            <text class="segment-text">详情</text>
          </view>
        </view>

        <!-- 列表视图 -->
        <view v-show="viewMode === 'list'" class="stock-list" :class="{ 'hidden-list': myStocks.length === 0 }">
          <stock-list-item 
            v-for="(stock, index) in myStocks" 
            :key="stock.code"
            :stock="stock"
            :show-delete="true"
            @delete="removeStock(index)"
            @click="handleStockClick(stock, index)"
          />
        </view>

        <!-- 表格视图 -->
        <view v-show="viewMode === 'table'" class="stock-table" :class="{ 'hidden-list': myStocks.length === 0 }">
          <!-- 表头 -->
          <view class="table-header">
            <text class="th-name">股票</text>
            <text class="th-date">自选日</text>
            <text class="th-price">自选价</text>
            <text class="th-profit">自选收益</text>
          </view>
          <!-- 表格内容 -->
          <view 
            v-for="(stock, index) in myStocks" 
            :key="stock.code"
            class="table-row"
            @click="handleStockClick(stock, index)"
          >
            <view class="td-name">
              <text class="stock-name">{{ stock.name }}</text>
              <view class="stock-code-row">
                <text :class="['stock-tag', getMarketClass(stock.code)]">{{ getMarketTag(stock.code) }}</text>
                <text class="stock-code">{{ stock.code }}</text>
              </view>
            </view>
            <text class="td-date">{{ stock.addDate || '--' }}</text>
            <text class="td-price">{{ formatPrice(stock.addPrice) }}</text>
            <text :class="['td-profit', getProfitClass(stock.profitPercent)]">
              {{ stock.profitPercent || '--' }}
            </text>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="myStocks.length === 0" class="empty-content">
          <view class="empty-icon">📊</view>
          <text class="empty-text">暂无收藏股票</text>
          <text class="empty-desc">在强势池中点击"+"按钮添加股票</text>
        </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" @click="goToLogin">
          <text>登录</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShow, onHide, onUnload } from '@dcloudio/uni-app'
import { isLoggedIn as checkLoginStatus } from '../../utils/auth.js'
import { getStockQuotes, getIndexQuote, getUserStocks, deleteUserStock } from '../../utils/api.js'
import StockListItem from '../../components/StockListItem.vue'

const isLoggedIn = ref(false)
const myStocks = ref([])
const viewMode = ref('list') // 'list' 或 'table'

// 切换视图模式
const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'list' ? 'table' : 'list'
}

// 设置视图模式（只切换显示，不重新加载数据）
const setViewMode = (mode) => {
  viewMode.value = mode
}

const indexData = ref({
  stockCode: '000001',
  stockName: '上证指数',
  currentPrice: null,
  priceChange: null,
  changePercent: null
})
let refreshTimer = null

// 获取上证指数数据
const fetchIndexData = async () => {
  try {
    const res = await getIndexQuote('000001')
    if (res.code === 200 && res.data) {
      indexData.value = { ...indexData.value, ...res.data }
    }
  } catch (e) {
    console.error('[上证指数] 获取失败:', e.message)
  }
}

// 格式化指数价格
const formatIndexPrice = (price) => {
  if (!price) return '--'
  return parseFloat(price).toFixed(2)
}

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '--'
  return parseFloat(price).toFixed(2)
}

// 获取指数涨跌样式类
const getIndexChangeClass = (changePercent) => {
  if (!changePercent) return ''
  const str = String(changePercent).replace('%', '').replace('+', '')
  const value = parseFloat(str)
  if (value > 0) return 'index-up'
  if (value < 0) return 'index-down'
  return ''
}

// 获取收益样式类
const getProfitClass = (profitPercent) => {
  if (!profitPercent) return ''
  const str = String(profitPercent).replace('%', '').replace('+', '')
  const value = parseFloat(str)
  if (value > 0) return 'profit-up'
  if (value < 0) return 'profit-down'
  return ''
}

// 获取市场标签
const getMarketTag = (code) => {
  if (code.startsWith('6')) return '沪'
  if (code.startsWith('0')) return '深'
  if (code.startsWith('3')) return '创'
  return '沪'
}

const getMarketClass = (code) => {
  if (code.startsWith('6')) return 'market-sh'
  if (code.startsWith('0')) return 'market-sz'
  if (code.startsWith('3')) return 'market-cy'
  return 'market-sh'
}

// 加载我的股票列表（从服务器数据库查询）
const loadMyStocks = async () => {
  console.log('[我的股票] loadMyStocks 开始执行, isLoggedIn=', isLoggedIn.value)
  
  if (!isLoggedIn.value) {
    myStocks.value = []
    stopAutoRefresh()
    return
  }
  
  try {
    // 显示加载提示
    uni.showLoading({ title: '加载中...' })
    
    // 从服务器获取用户自选股票（每次都从数据库查询）
    console.log('[我的股票] 调用 getUserStocks 接口')
    const res = await getUserStocks()
    console.log('[我的股票] 服务器返回:', JSON.stringify(res))
    
    uni.hideLoading()
    
    if (res.code === 200 && res.data) {
      // 转换数据格式
      myStocks.value = res.data.map(item => ({
        code: item.stockCode,
        name: item.stockName,
        addPrice: item.addPrice,
        addDate: item.addDate,
        currentPrice: item.currentPrice,
        profitPercent: item.profitPercent,
        priceChange: item.priceChange,
        changePercent: item.changePercent,
        trendData: item.trendData
      }))
      console.log('[我的股票] 加载完成, 股票数量:', myStocks.value.length)
    } else {
      myStocks.value = []
      console.log('[我的股票] 返回数据为空')
    }
    
    // 获取上证指数
    await fetchIndexData()
    
    // 如果有股票数据，刷新行情
    if (myStocks.value.length > 0) {
      await refreshAllQuotes()
    }
    
    // 登录后启动定时刷新
    startAutoRefresh()
  } catch (e) {
    uni.hideLoading()
    console.error('[我的股票] 加载失败:', e)
    myStocks.value = []
    startAutoRefresh()
  }
}

// 批量刷新所有股票行情
const refreshAllQuotes = async () => {
  if (myStocks.value.length === 0) return
  
  try {
    const codes = myStocks.value.map(stock => stock.code).join(',')
    const quoteRes = await getStockQuotes(codes)
    
    if (quoteRes.code === 200 && quoteRes.data && quoteRes.data.length > 0) {
      quoteRes.data.forEach(quoteData => {
        const index = myStocks.value.findIndex(stock => stock.code === quoteData.stockCode)
        if (index !== -1) {
          const stock = myStocks.value[index]
          stock.priceChange = quoteData.priceChange
          stock.changePercent = quoteData.changePercent
          stock.currentPrice = quoteData.currentPrice
          stock.name = quoteData.stockName || stock.name
          stock.trendData = quoteData.trendData || null
          
          // 计算自选收益（当前价格相对于加入价格的涨跌幅）
          if (stock.addPrice && quoteData.currentPrice) {
            const addPrice = parseFloat(stock.addPrice)
            const currentPrice = parseFloat(quoteData.currentPrice)
            if (addPrice > 0) {
              const profit = ((currentPrice - addPrice) / addPrice * 100).toFixed(2)
              stock.profitPercent = profit >= 0 ? `+${profit}%` : `${profit}%`
            }
          }
        }
      })
    }
  } catch (e) {
    console.error('[我的股票] 刷新异常:', e.message)
  }
}

// 启动定时刷新
const startAutoRefresh = () => {
  if (!isLoggedIn.value) return
  stopAutoRefresh()
  
  const scheduleNextRefresh = () => {
    const delay = 3000 + Math.random() * 1000
    refreshTimer = setTimeout(async () => {
      await fetchIndexData()
      if (myStocks.value.length > 0) {
        await refreshAllQuotes()
      }
      scheduleNextRefresh()
    }, delay)
  }
  
  scheduleNextRefresh()
}

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

// 跳转到登录页
const goToLogin = () => {
  uni.navigateTo({ url: '/pages/login/login' })
}

// 点击股票项
const handleStockClick = async (stockItem, idx) => {
  console.log('点击股票:', stockItem.name, idx)
  // 刷新该股票的最新行情
  try {
    const quoteRes = await getStockQuotes(stockItem.code)
    if (quoteRes.code === 200 && quoteRes.data && quoteRes.data.length > 0) {
      const quoteData = quoteRes.data[0]
      const stock = myStocks.value[idx]
      if (stock) {
        stock.priceChange = quoteData.priceChange
        stock.changePercent = quoteData.changePercent
        stock.currentPrice = quoteData.currentPrice
        stock.name = quoteData.stockName || stock.name
        stock.trendData = quoteData.trendData || null
        
        // 计算自选收益
        if (stock.addPrice && quoteData.currentPrice) {
          const addPrice = parseFloat(stock.addPrice)
          const currentPrice = parseFloat(quoteData.currentPrice)
          if (addPrice > 0) {
            const profit = ((currentPrice - addPrice) / addPrice * 100).toFixed(2)
            stock.profitPercent = profit >= 0 ? `+${profit}%` : `${profit}%`
          }
        }
      }
    }
  } catch (e) {
    console.error('刷新股票行情失败:', e)
  }
  uni.showToast({ title: '股票详情功能开发中', icon: 'none' })
}

// 删除股票
const removeStock = async (idx) => {
  const stock = myStocks.value[idx]
  uni.showModal({
    title: '确认删除',
    content: `确定要删除 ${stock.name} 吗？`,
    confirmText: '删除',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用服务器删除接口
          await deleteUserStock(stock.code)
          // 从本地列表删除
          myStocks.value.splice(idx, 1)
          uni.showToast({ title: '删除成功', icon: 'success' })
          
          if (myStocks.value.length === 0) {
            stopAutoRefresh()
          }
        } catch (e) {
          console.error('删除失败:', e)
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

onLoad(() => {
  console.log('[我的股票] onLoad 触发')
  isLoggedIn.value = checkLoginStatus()
  loadMyStocks()
})

onShow(() => {
  console.log('[我的股票] onShow 触发')
  isLoggedIn.value = checkLoginStatus()
  // 每次页面显示时都从数据库重新加载
  loadMyStocks()
  uni.setNavigationBarTitle({ title: '量化交易大师' })
})

onHide(() => {
  stopAutoRefresh()
})

onUnload(() => {
  stopAutoRefresh()
})
</script>

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

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

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

/* 上证指数卡片 */
.index-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(37, 52, 94, 0.08);
}

.index-left {
  display: flex;
  flex-direction: column;
}

.index-price-row {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.index-price {
  font-size: 48rpx;
  font-weight: 700;
  margin-right: 16rpx;
}

.index-change {
  font-size: 28rpx;
  font-weight: 600;
}

.index-name-row {
  display: flex;
  align-items: center;
}

.index-name {
  font-size: 26rpx;
  color: #666666;
  margin-right: 12rpx;
}

.index-percent {
  font-size: 26rpx;
  font-weight: 600;
}

.index-up {
  color: #FF3B30;
}

.index-down {
  color: #34C759;
}

/* 分段控制器 */
.segment-control {
  display: flex;
  align-items: center;
  background: #F5F7FA;
  border-radius: 32rpx;
  padding: 6rpx;
  margin-bottom: 24rpx;
  position: relative;
  height: 64rpx;
  box-sizing: border-box;
}

.segment-slider {
  position: absolute;
  left: 6rpx;
  top: 6rpx;
  width: calc(50% - 6rpx);
  height: calc(100% - 12rpx);
  background: #ffffff;
  border-radius: 26rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
  z-index: 0;
}

.segment-slider.slider-right {
  transform: translateX(100%);
}

.segment-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  z-index: 1;
  transition: color 0.3s ease;
}

.segment-icon {
  font-size: 24rpx;
  margin-right: 8rpx;
  color: #999999;
  transition: color 0.3s ease;
}

.segment-text {
  font-size: 26rpx;
  color: #999999;
  font-weight: 500;
  transition: color 0.3s ease;
}

.segment-active .segment-icon,
.segment-active .segment-text {
  color: #E53935;
}

/* 隐藏空列表 */
.hidden-list {
  display: none !important;
}

/* 股票列表 */
.stock-list {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 0 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(37, 52, 94, 0.08);
}

/* 表格视图 */
.stock-table {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 0 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(37, 52, 94, 0.08);
}

.table-header {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f1f2f6;
}

.table-header text {
  font-size: 24rpx;
  color: #999999;
  font-weight: 500;
}

.th-name {
  flex: 1;
}

.th-date {
  width: 160rpx;
  text-align: center;
}

.th-price {
  width: 140rpx;
  text-align: center;
}

.th-profit {
  width: 140rpx;
  text-align: right;
}

.table-row {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f1f2f6;
}

.table-row:last-child {
  border-bottom: none;
}

.td-name {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.td-name .stock-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #222222;
  margin-bottom: 4rpx;
}

.stock-code-row {
  display: flex;
  align-items: center;
}

.stock-tag {
  font-size: 18rpx;
  padding: 2rpx 6rpx;
  border-radius: 4rpx;
  color: #ffffff;
  font-weight: 500;
  margin-right: 8rpx;
}

.market-sh {
  background: #FF3B30;
}

.market-sz {
  background: #34C759;
}

.market-cy {
  background: #FF9500;
}

.stock-code {
  font-size: 22rpx;
  color: #9ca2b5;
}

.td-date {
  width: 160rpx;
  text-align: center;
  font-size: 24rpx;
  color: #666666;
}

.td-price {
  width: 140rpx;
  text-align: center;
  font-size: 26rpx;
  color: #333333;
}

.td-profit {
  width: 140rpx;
  text-align: right;
  font-size: 26rpx;
  font-weight: 600;
}

.profit-up {
  color: #FF3B30;
}

.profit-down {
  color: #34C759;
}

/* 空状态 */
.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 60rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999999;
  text-align: center;
  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;
}
</style>
