<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @click="handleBack">
        <text class="back-icon">←</text>
      </view>
      <view class="navbar-title">
        <text class="title-text">超短池管理</text>
      </view>
      <view class="navbar-placeholder"></view>
    </view>

    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper">
        <!-- 搜索添加区域 -->
        <view class="search-card">
          <view class="search-header">
            <text class="search-title">添加股票</text>
          </view>
          <view class="search-box">
            <view class="search-input-wrap">
              <text class="search-icon">🔍</text>
              <input 
                class="search-input" 
                v-model="searchKeyword" 
                placeholder="搜索股票名称或代码"
                @input="handleSearchInput"
                @focus="showSuggestions = true"
              />
              <view v-if="searchKeyword" class="clear-btn" @click="clearSearch">
                <text>×</text>
              </view>
            </view>
          </view>
          
          <!-- 搜索建议下拉 -->
          <view v-if="showSuggestions && suggestions.length > 0" class="suggestions-dropdown">
            <view 
              v-for="(item, index) in suggestions" 
              :key="index"
              class="suggestion-item"
              @click="handleAddFromSuggestion(item)"
            >
              <view class="suggestion-info">
                <text class="suggestion-name">{{ item.name }}</text>
                <text class="suggestion-code">{{ item.code }}</text>
              </view>
              <view class="add-btn-small">
                <text>添加</text>
              </view>
            </view>
          </view>
          
          <view v-if="showSuggestions && searching" class="suggestions-dropdown">
            <view class="suggestion-loading">
              <text>搜索中...</text>
            </view>
          </view>
          
          <view v-if="showSuggestions && !searching && searchKeyword && suggestions.length === 0" class="suggestions-dropdown">
            <view class="suggestion-empty">
              <text>未找到相关股票</text>
            </view>
          </view>
        </view>

        <!-- 遮罩层 -->
        <view v-if="showSuggestions && suggestions.length > 0" class="mask" @click="closeSuggestions"></view>

        <!-- 股票列表卡片 -->
        <view class="stock-card">
          <view class="card-header">
            <view class="header-left">
              <view class="header-dot"></view>
              <text class="header-title">超短池股票</text>
            </view>
            <text class="header-count">共 {{ stockList.length }} 只</text>
          </view>

          <view v-if="loading && stockList.length === 0" class="loading-state">
            <text class="loading-text">加载中...</text>
          </view>

          <view v-else-if="stockList.length === 0" class="empty-state">
            <text class="empty-icon">📊</text>
            <text class="empty-text">暂无股票</text>
            <text class="empty-desc">通过上方搜索添加股票到超短池</text>
          </view>

          <view v-else class="stock-list">
            <view 
              v-for="(item, index) in stockList" 
              :key="item.code"
              class="stock-item"
            >
              <view class="stock-left">
                <text class="stock-name">{{ item.name }}</text>
                <text class="stock-code">{{ item.code }}</text>
              </view>
              <view class="stock-center">
                <text class="stock-price">{{ item.currentPrice || '-' }}</text>
                <text class="stock-change" :class="getChangeClass(item.changePercent)">{{ item.changePercent || '-' }}</text>
              </view>
              <view class="stock-right">
                <view class="action-btn" @click="handleDeleteStock(item)">
                  <text>撤出</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="bottom-safe-area"></view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import { refreshUserInfo } from '@/utils/auth.js'
import { getSuggestions, BASE_URL } from '@/utils/api.js'

const searchKeyword = ref('')
const suggestions = ref([])
const showSuggestions = ref(false)
const searching = ref(false)
const stockList = ref([])
const loading = ref(false)
const poolType = 1

let searchTimer = null
let refreshTimer = null

const getToken = () => uni.getStorageSync('user_token') || null

const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = getToken()
    const header = options.header || {}
    if (token) header['Authorization'] = `Bearer ${token}`
    
    uni.request({
      url: `${BASE_URL}${options.url}`,
      method: options.method || 'GET',
      data: options.data || {},
      header,
      success: (res) => res.statusCode === 200 ? resolve(res.data) : reject(new Error(res.data?.message || '请求失败')),
      fail: () => reject(new Error('网络异常'))
    })
  })
}

const handleBack = () => {
  const pages = getCurrentPages()
  pages.length > 1 ? uni.navigateBack() : uni.switchTab({ url: '/pages/mine/mine' })
}

onShow(() => {
  checkAdminPermission()
  loadStockList()
  startAutoRefresh()
})

onHide(() => stopAutoRefresh())
onUnmounted(() => stopAutoRefresh())

const startAutoRefresh = () => {
  stopAutoRefresh()
  refreshTimer = setInterval(() => loadStockList(true), 5000)
}

const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 检查管理员权限（从后端获取最新状态）
const checkAdminPermission = async () => {
  const userInfo = await refreshUserInfo()
  if (!userInfo || userInfo.status !== 2) {
    uni.showToast({ title: '无权限访问', icon: 'none' })
    setTimeout(() => {
      const pages = getCurrentPages()
      pages.length > 1 ? uni.navigateBack() : uni.switchTab({ url: '/pages/mine/mine' })
    }, 1500)
  }
}

const loadStockList = async (silent = false) => {
  if (!silent) loading.value = true
  try {
    const res = await request({ url: '/v1/stock/pool/admin/list', data: { poolType } })
    if (res.code === 200) stockList.value = res.data || []
  } catch (e) {
    console.error('加载失败', e)
  } finally {
    if (!silent) loading.value = false
  }
}

const getChangeClass = (changePercent) => {
  if (!changePercent || changePercent === '-') return ''
  return changePercent.startsWith('+') ? 'up' : changePercent.startsWith('-') ? 'down' : ''
}

const handleSearchInput = () => {
  if (searchTimer) clearTimeout(searchTimer)
  if (!searchKeyword.value.trim()) {
    suggestions.value = []
    showSuggestions.value = false
    return
  }
  searching.value = true
  showSuggestions.value = true
  searchTimer = setTimeout(async () => {
    try {
      const res = await getSuggestions(searchKeyword.value.trim())
      suggestions.value = res.code === 200 && res.data ? res.data : []
    } catch (e) {
      suggestions.value = []
    } finally {
      searching.value = false
    }
  }, 300)
}

const clearSearch = () => {
  searchKeyword.value = ''
  suggestions.value = []
  showSuggestions.value = false
}

const closeSuggestions = () => showSuggestions.value = false

const handleAddFromSuggestion = async (item) => {
  if (stockList.value.some(s => s.code === item.code)) {
    uni.showToast({ title: '该股票已在超短池中', icon: 'none' })
    return
  }
  try {
    const res = await request({
      url: '/v1/stock/pool/admin/add',
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: { stockCode: item.code, poolType }
    })
    if (res.code === 200) {
      uni.showToast({ title: '添加成功', icon: 'success' })
      clearSearch()
      loadStockList()
    } else {
      uni.showToast({ title: res.message || '添加失败', icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: '添加失败', icon: 'none' })
  }
}

const handleDeleteStock = (item) => {
  uni.showModal({
    title: '确认撤出',
    content: `确定要将 ${item.name} 从超短池撤出吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await request({
            url: '/v1/stock/pool/admin/delete',
            method: 'POST',
            header: { 'content-type': 'application/json' },
            data: { stockCode: item.code, poolType }
          })
          if (result.code === 200) {
            uni.showToast({ title: '撤出成功', icon: 'success' })
            loadStockList()
          } else {
            uni.showToast({ title: result.message || '撤出失败', icon: 'none' })
          }
        } catch (e) {
          uni.showToast({ title: '撤出失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

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

/* 导航栏 */
.custom-navbar {
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 80rpx 32rpx 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  position: relative;
}

.navbar-back {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 40rpx;
  color: #222222;
  font-weight: bold;
}

.navbar-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.title-text {
  font-size: 36rpx;
  font-weight: 600;
  color: #222222;
}

.navbar-placeholder {
  width: 80rpx;
}

/* 内容区 */
.scroll-view {
  flex: 1;
  height: 0;
}

.content-wrapper {
  padding: 32rpx;
}

/* 搜索卡片 */
.search-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(37, 52, 94, 0.08);
  position: relative;
  z-index: 100;
}

.search-header {
  margin-bottom: 20rpx;
}

.search-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #3abf81;
}

.search-box {
  position: relative;
}

.search-input-wrap {
  display: flex;
  align-items: center;
  background: #f5f6fb;
  border-radius: 16rpx;
  padding: 0 24rpx;
  height: 88rpx;
}

.search-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
}

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

.clear-btn {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #d0d0d0;
  border-radius: 50%;
}

.clear-btn text {
  font-size: 32rpx;
  color: #fff;
  line-height: 1;
}

/* 搜索建议 */
.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-info {
  display: flex;
  flex-direction: column;
}

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

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

.add-btn-small {
  padding: 12rpx 28rpx;
  background: #5B5AEA;
  border-radius: 32rpx;
}

.add-btn-small text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 500;
}

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

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

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

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #f1f2f6;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #5B5AEA;
  margin-right: 12rpx;
}

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

.header-count {
  font-size: 26rpx;
  color: #9ca2b5;
}

/* 股票列表 */
.stock-list {
  display: flex;
  flex-direction: column;
}

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

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

.stock-left {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.stock-name {
  font-size: 30rpx;
  font-weight: 700;
  color: #222222;
}

.stock-code {
  font-size: 24rpx;
  color: #9ca2b5;
  margin-top: 8rpx;
}

.stock-center {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-right: 32rpx;
}

.stock-price {
  font-size: 32rpx;
  font-weight: 700;
  color: #222222;
}

.stock-change {
  font-size: 26rpx;
  color: #9ca2b5;
  margin-top: 6rpx;
  font-weight: 500;
}

.stock-change.up {
  color: #f16565;
}

.stock-change.down {
  color: #3abf81;
}

.stock-right {
  flex-shrink: 0;
}

.action-btn {
  padding: 14rpx 32rpx;
  background: #5B5AEA;
  border-radius: 32rpx;
}

.action-btn text {
  font-size: 26rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 空状态 */
.loading-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 40rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #9ca2b5;
}

.empty-icon {
  font-size: 100rpx;
  margin-bottom: 24rpx;
}

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

.empty-desc {
  font-size: 26rpx;
  color: #999999;
}

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