<template>
  <view class="page-container">
    <!-- 遮罩层 -->
    <view v-if="showDropdown && suggestions.length > 0" class="mask" @click="closeDropdown"></view>

    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper">

        <!-- 顶部查询卡片 -->
        <view class="card search-card">
          <text class="card-title">量化分数实时查询 & 历史数据</text>

          <view class="search-box">
            <view class="search-input-wrap">
              <input
                class="search-input"
                type="text"
                placeholder="请输入股票代码/名称 (如: 600030)"
                v-model="keyword"
                @input="onKeywordChange"
                @confirm="handleSearchClick"
                @focus="onInputFocus"
              />
              <view class="search-button" @click="handleSearchClick">
                <image class="search-icon" src="/static/images/tab_search.png" mode="aspectFit"></image>
              </view>
            </view>
          </view>
          
          <!-- 搜索建议下拉 -->
          <view v-if="showDropdown && suggestions.length > 0" class="suggestions-dropdown">
            <view 
              v-for="(item, index) in suggestions" 
              :key="index"
              class="suggestion-item"
              @click="onSelectSuggestion(item)"
            >
              <text class="suggestion-name">{{ item.name }}</text>
              <text class="suggestion-code">{{ item.code }}</text>
            </view>
          </view>
          
          <view v-if="showDropdown && searching" class="suggestions-dropdown">
            <view class="suggestion-loading">
              <text>搜索中...</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 class="stock-info-left">
                <view class="detail-name">{{result.stockName}}</view>
                <view class="detail-code">{{result.stockCode}}</view>
              </view>
              <view class="stock-price-right">
                <view class="current-price" :class="getPriceClass(result.changePercent)">
                  {{result.currentPrice || '--'}}
                </view>
                <view class="price-change" :class="getPriceClass(result.changePercent)">
                  {{result.priceChange || '--'}} ({{result.changePercent || '--'}})
                </view>
              </view>
            </view>

            <view class="quote-section" v-if="result.currentPrice">
              <view class="quote-grid">
                <view class="quote-item">
                  <text class="quote-label">开盘</text>
                  <text class="quote-value">{{result.openPrice || '--'}}</text>
                </view>
                <view class="quote-item">
                  <text class="quote-label">最高</text>
                  <text class="quote-value price-up">{{result.highPrice || '--'}}</text>
                </view>
                <view class="quote-item">
                  <text class="quote-label">最低</text>
                  <text class="quote-value price-down">{{result.lowPrice || '--'}}</text>
                </view>
                <view class="quote-item">
                  <text class="quote-label">成交量</text>
                  <text class="quote-value">{{result.volume || '--'}}</text>
                </view>
                <view class="quote-item">
                  <text class="quote-label">成交额</text>
                  <text class="quote-value">{{result.amount || '--'}}</text>
                </view>
                <view class="quote-item">
                  <text class="quote-label">换手率</text>
                  <text class="quote-value">{{result.turnoverRate || '--'}}</text>
                </view>
              </view>
            </view>

            <view class="section" v-if="result.score">
              <view class="section-title">量化系统评分</view>
              <view class="score-display">
                <view class="score-badge">{{result.score}}</view>
              </view>
            </view>

            <view class="section" v-if="result.history && result.history.length > 0">
              <view class="section-title">历史评分趋势</view>
              <view class="history-row" v-for="(item, idx) in result.history" :key="idx">
                <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" v-if="result.factors && result.factors.length > 0">
              <view class="section-title">评分因子构成</view>
              <view class="factor-row" v-for="(item, idx) in result.factors" :key="idx">
                <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>

        <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'
import { onShow, onHide } 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 searching = ref(false)
const isLoggedIn = ref(false)
let searchTimer = null

onMounted(() => {
  isLoggedIn.value = checkLoginStatus()
})

onShow(() => {
  isLoggedIn.value = checkLoginStatus()
  uni.setNavigationBarTitle({ title: '量化交易大师' })
})

onHide(() => {
  showDropdown.value = false
})

const onInputFocus = () => {
  if (suggestions.value.length > 0) {
    showDropdown.value = true
  }
}

const onKeywordChange = (e) => {
  const value = e.detail.value
  keyword.value = value
  
  if (searchTimer) clearTimeout(searchTimer)
  
  if (!value || !value.trim()) {
    suggestions.value = []
    showDropdown.value = false
    return
  }
  
  searching.value = true
  showDropdown.value = true
  
  searchTimer = setTimeout(async () => {
    try {
      const response = await getSuggestions(value.trim())
      if (response.code === 200 && response.data) {
        suggestions.value = Array.isArray(response.data) ? response.data : []
      } else {
        suggestions.value = []
      }
    } catch (err) {
      console.error('搜索建议错误:', err)
      suggestions.value = []
    } finally {
      searching.value = false
    }
  }, 300)
}

const closeDropdown = () => {
  showDropdown.value = false
}

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

const handleSearchClick = () => {
  if (!isLoggedIn.value) {
    uni.showModal({
      title: '登录提示',
      content: '此功能需要登录后使用，是否前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/login' })
        }
      }
    })
    return
  }
  onSearch()
}

const onSearch = () => {
  const kw = (keyword.value || '').trim()
  if (!kw) {
    uni.showToast({ title: '请输入股票代码或名称', icon: 'none' })
    return
  }
  
  showDropdown.value = false
  suggestions.value = []
  
  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
  showDropdown.value = false
  suggestions.value = []

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

const getPriceClass = (changePercent) => {
  if (!changePercent) return ''
  if (changePercent.startsWith('+')) return 'price-up'
  if (changePercent.startsWith('-')) return 'price-down'
  return ''
}
</script>

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

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

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

/* 遮罩层 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 99;
}

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

/* 搜索卡片 - 关键：设置 z-index 和 position */
.search-card {
  margin-top: 16rpx;
  position: relative;
  z-index: 100;
}

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

.search-box {
  position: relative;
}

.search-input-wrap {
  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-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;
}

/* 搜索建议下拉 - 关键样式 */
.suggestions-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #ffffff;
  border-radius: 16rpx;
  margin-top: 12rpx;
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.15);
  max-height: 480rpx;
  overflow-y: auto;
  z-index: 101;
}

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

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

.suggestion-item:active {
  background: #f9f9fb;
}

.suggestion-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #222222;
}

.suggestion-code {
  font-size: 24rpx;
  color: #9ca2b5;
}

.suggestion-loading {
  padding: 48rpx;
  text-align: center;
  color: #9ca2b5;
  font-size: 28rpx;
}

.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: flex-start;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #f1f2f6;
}

.stock-info-left {
  flex: 1;
}

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

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

.stock-price-right {
  text-align: right;
}

.current-price {
  font-size: 44rpx;
  font-weight: 700;
  color: #333;
}

.price-change {
  margin-top: 6rpx;
  font-size: 26rpx;
}

.price-up { color: #e74c3c; }
.price-down { color: #27ae60; }

.quote-section {
  margin-bottom: 24rpx;
}

.quote-grid {
  display: flex;
  flex-wrap: wrap;
  background: #f8f9fc;
  border-radius: 16rpx;
  padding: 20rpx 16rpx;
}

.quote-item {
  width: 33.33%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12rpx 0;
}

.quote-label {
  font-size: 24rpx;
  color: #9da3b5;
  margin-bottom: 8rpx;
}

.quote-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.score-display {
  display: flex;
  justify-content: center;
  margin-top: 16rpx;
}

.score-badge {
  min-width: 140rpx;
  padding: 12rpx 22rpx;
  border-radius: 20rpx;
  background: #f16565;
  color: #ffffff;
  font-size: 40rpx;
  font-weight: 700;
  text-align: center;
  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>
