<template>
  <view class="page-container">
    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper">

        <!-- 顶部查询卡片 -->
        <view class="card search-card" style="position: relative; z-index: 100;">
          <text class="card-title">量化分数实时查询 & 历史数据</text>

          <view class="search-row">
            <input
              class="search-input"
              type="text"
              placeholder="请输入股票代码/名称 (如: 600030)"
              placeholder-class="search-placeholder"
              confirm-type="search"
              v-model="keyword"
              @input="onKeywordChange"
              @confirm="handleSearchClick"
              @blur="onInputBlur"
            />
            <!-- 搜索按钮（统一处理登录检查） -->
            <view class="search-button" @click="handleSearchClick">
              <image class="search-icon" src="/static/images/tab_search.png" mode="aspectFit"></image>
            </view>
          </view>
          
          <!-- 模糊搜索下拉列表 -->
          <view class="search-dropdown" v-if="showDropdown && suggestions && suggestions.length > 0">
            <view 
              v-for="(item, index) in suggestions" 
              :key="index"
              class="dropdown-item" 
              hover-class="dropdown-item-hover" 
              @tap.stop="onSelectSuggestion(item)"
            >
              <text class="item-name">{{item.name}}</text>
              <text class="item-code">{{item.code}}</text>
            </view>
          </view>

          <text class="search-tip">支持A股代码或名称模糊查询{{ isLoggedIn ? '' : '（需登录）' }}</text>
        </view>

        <!-- 查询结果 -->
        <view v-if="hasSearched" class="card result-card">
          <view v-if="loading">
            <text class="result-loading">正在查询，请稍候...</text>
          </view>
          <view v-else-if="errorMsg">
            <text class="result-error">{{errorMsg}}</text>
          </view>
          <view v-else-if="result">
            <!-- 头部：名称 / 代码 / 分数徽章 -->
            <view class="detail-header">
              <view>
                <view class="detail-name">{{result.stockName}}（{{result.stockCode}}）</view>
                <view class="detail-sub">最新量化系统评分</view>
              </view>
              <view class="score-badge">{{result.score}}</view>
            </view>

            <!-- 历史评分趋势 -->
            <view class="section">
              <view class="section-title">历史评分趋势</view>
              <view class="history-row" v-for="(item, index) in result.history" :key="index">
                <text class="history-date">{{item.date}} 的量化评分：</text>
                <text :class="['history-score', item.score >= 90 ? 'tag-danger' : (item.score >= 80 ? 'tag-success' : 'tag-info')]">
                  {{item.score}}
                </text>
              </view>
              <text class="history-note">（注意：此为模拟历史数据，仅供展示。）</text>
            </view>

            <!-- 评分因子构成 -->
            <view class="section">
              <view class="section-title">评分因子构成</view>
              <view class="factor-row" v-for="(item, index) in result.factors" :key="index">
                <text class="factor-name">{{item.name}}</text>
                <text class="factor-score">{{item.value}}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 量化投资的优势 -->
        <view class="card advantage-card">
          <view class="card-header">
            <view class="icon-circle">
              <text class="icon-check">✓</text>
            </view>
            <text class="card-header-title">量化投资的优势</text>
          </view>

          <view class="advantage-item">
            <text class="advantage-label">客观纪律性：</text>
            <text class="advantage-desc">排除情绪干扰，严格执行预设的交易信号。</text>
          </view>
          <view class="advantage-item">
            <text class="advantage-label">高效覆盖广度：</text>
            <text class="advantage-desc">能同时分析数千只股票，人工无法企及。</text>
          </view>
        </view>

        <!-- 风险提示（免责声明） -->
        <view class="card risk-card">
          <view class="card-header">
            <view class="icon-warning">
              <text class="icon-warning-text">!</text>
            </view>
            <text class="card-header-title">风险提示（免责声明）</text>
          </view>

          <text class="risk-text">
            本系统的量化分数和股票池信息均基于历史数据和特定模型计算，并非对未来市场的保证或预测。市场环境瞬息万变，
            量化模型可能存在失效或回撤风险。请勿将本系统数据作为投资决策的唯一依据，请您充分理解股票投资风险，并独立做出投资判断。
          </text>
        </view>

        <!-- 预留底部空间，避免被 tabBar 遮挡 -->
        <view class="bottom-safe-area"></view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getSuggestions, searchStocks } from '../../utils/api.js'
import { isLoggedIn as checkLoginStatus } from '../../utils/auth.js'

// 引入 onShow 生命周期
import { onShow } from '@dcloudio/uni-app'

const keyword = ref('')
const loading = ref(false)
const hasSearched = ref(false)
const errorMsg = ref('')
const result = ref(null)
const suggestions = ref([])
const showDropdown = ref(false)
const isLoggedIn = ref(false)
let timer = null

/**
 * 页面加载时检查登录状态
 */
onMounted(() => {
  isLoggedIn.value = checkLoginStatus()
  console.log('[首页] 登录状态:', isLoggedIn.value)
})

/**
 * 页面显示时检查登录状态（从登录页返回时会触发）
 */
onShow(() => {
  isLoggedIn.value = checkLoginStatus()
  // 设置导航栏标题
  uni.setNavigationBarTitle({ title: '量化交易大师' })
})

/**
 * 处理搜索按钮点击（统一登录校验UI）
 */
const handleSearchClick = async () => {
  console.log('=== 点击搜索按钮 ===')
  console.log('当前登录状态:', isLoggedIn.value)
  
  // 检查登录状态
  if (!isLoggedIn.value) {
    console.log('未登录，跳转到登录页')
    uni.showModal({
      title: '登录提示',
      content: '此功能需要登录后使用，是否前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }
      }
    })
    return
  }
  
  console.log('已登录，执行搜索')
  // 已登录，执行搜索
  onSearch()
}

const onKeywordChange = (e) => {
  const value = e.detail.value
  keyword.value = value
  console.log('输入关键词:', value)
  
  if (timer) {
    clearTimeout(timer)
  }
  
  timer = setTimeout(() => {
    doSearchSuggestions(value)
  }, 500)
}

const doSearchSuggestions = async (kw) => {
  if (!kw || !kw.trim()) {
    suggestions.value = []
    showDropdown.value = false
    return
  }

  try {
    // getSuggestions 返回完整响应对象 {code, message, data}
    const response = await getSuggestions(kw.trim())
    console.log('模糊查询返回数据:', response)
    
    // 从响应中提取 data 数组
    const list = response.data || []
    suggestions.value = Array.isArray(list) ? list : []
    showDropdown.value = suggestions.value.length > 0
    console.log('下拉框状态:', { showDropdown: showDropdown.value, suggestionsLength: suggestions.value.length })
  } catch (err) {
    console.error('模糊查询错误:', err)
    suggestions.value = []
    showDropdown.value = false
  }
}

const onSelectSuggestion = (item) => {
  const searchText = `${item.name} (${item.code})`
  keyword.value = searchText
  suggestions.value = []
  showDropdown.value = false
  
  doSearch(item.code)
}

const onSearch = () => {
  const kw = (keyword.value || '').trim()
  if (!kw) {
    uni.showToast({
      title: '请输入股票代码或名称',
      icon: 'none'
    })
    return
  }

  let searchCode = kw
  const codeMatch = kw.match(/\((\d{6})\)/)
  if (codeMatch) {
    searchCode = codeMatch[1]
  }

  doSearch(searchCode)
}

const doSearch = async (queryCode) => {
  loading.value = true
  hasSearched.value = true
  errorMsg.value = ''
  result.value = null
  suggestions.value = []
  showDropdown.value = false

  try {
    const res = await searchStocks(queryCode)
    if (res.code === 0 && res.data) {
      result.value = res.data
    } else {
      errorMsg.value = res.message || '未查询到相关股票数据'
    }
  } catch (err) {
    errorMsg.value = '网络请求失败，请检查网络连接'
  } finally {
    loading.value = false
  }
}

const onInputBlur = () => {
  // 延迟关闭，给点击下拉项留出时间
  setTimeout(() => {
    showDropdown.value = false
  }, 300)
}
</script>

<style>
/** 首页量化查询界面样式 **/

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

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

.content-wrapper {
  padding: 32rpx 32rpx 48rpx;
}

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

.search-card {
  margin-top: 16rpx;
  z-index: 10;
}

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

.search-row {
  display: flex;
  align-items: center;
  background: #f7f8fc;
  border-radius: 999rpx;
  padding: 0 8rpx 0 32rpx;
  height: 96rpx;
  box-sizing: border-box;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #222222;
}

.search-placeholder {
  color: #b4b8c6;
}

.search-button {
  width: 96rpx;
  height: 80rpx;
  margin-left: 12rpx;
  border-radius: 999rpx;
  background: #f5f6fb;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-icon {
  width: 48rpx;
  height: 48rpx;
}

.search-tip {
  display: block;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #9ca2b5;
}

/* 下拉列表样式 */
.search-dropdown {
  position: absolute;
  top: 100%; /* 相对于父元素定位，在搜索框下方 */
  left: 0;
  right: 0;
  margin-top: 8rpx;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);
  max-height: 400rpx;
  overflow-y: auto;
  z-index: 1000; /* 提高层级，确保在最上层 */
  border: 1rpx solid #f0f0f0;
}

.dropdown-item {
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f5f6fb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

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

.dropdown-item-hover {
  background-color: #f7f8fc;
}

.item-name {
  font-size: 28rpx;
  color: #333;
}

.item-code {
  font-size: 24rpx;
  color: #999;
}

.result-card {
  margin-top: 8rpx;
}

.result-loading {
  font-size: 26rpx;
  color: #666a7f;
}

.result-error {
  font-size: 26rpx;
  color: #ff5b5b;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.detail-name {
  font-size: 30rpx;
  font-weight: 700;
  color: #1f1f2e;
}

.detail-sub {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #9da3b5;
}

.score-badge {
  min-width: 140rpx;
  padding: 12rpx 22rpx;
  border-radius: 20rpx;
  background: #f16565;
  color: #ffffff;
  font-size: 40rpx;
  font-weight: 700;
  text-align: right;
  box-shadow: 0 10rpx 24rpx rgba(241, 101, 101, 0.35);
}

.section {
  margin-top: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 700;
  color: #1f1f2e;
  margin-bottom: 16rpx;
}

.history-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18rpx 0;
  border-bottom: 1rpx solid #f1f2f6;
}

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

.history-date {
  font-size: 26rpx;
  color: #3c4050;
}

.history-score {
  min-width: 96rpx;
  text-align: center;
  padding: 6rpx 18rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  font-weight: 700;
  color: #ffffff;
}

.tag-danger {
  background: #f16565;
}

.tag-success {
  background: #3abf81;
}

.tag-info {
  background: #4c86ff;
}

.history-note {
  display: block;
  margin-top: 12rpx;
  font-size: 22rpx;
  color: #9da3b5;
}

.factor-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14rpx 0;
}

.factor-name {
  font-size: 26rpx;
  color: #3c4050;
}

.factor-score {
  font-size: 28rpx;
  font-weight: 600;
  color: #4c86ff;
}

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

.card-header-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #222222;
}

.icon-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: #e7f7ef;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.icon-check {
  font-size: 24rpx;
  color: #28a745;
}

.advantage-item {
  margin-bottom: 12rpx;
  font-size: 26rpx;
  line-height: 1.6;
  color: #4a4f63;
}

.advantage-label {
  font-weight: 600;
}

.advantage-desc {
  font-weight: 400;
}

.risk-card {
  margin-bottom: 24rpx;
}

.icon-warning {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: #ffecef;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.icon-warning-text {
  font-size: 26rpx;
  color: #ff5b5b;
}

.risk-text {
  display: block;
  font-size: 24rpx;
  line-height: 1.8;
  color: #666a7f;
}

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