<template>
  <div class="dashboard-container">
    <HeaderBar
      :title="systemConfig.title"
      :title-background="systemConfig.titleBackground"
    />

    <!-- 主要内容区域 -->
    <div v-if="isLayoutReady" class="main-content">
      <!-- 左侧区域 - 分为左和左中两列 -->
      <div class="left-section">
        <!-- 左列 -->
        <div class="left-column">
          <div class="left-top">
            <RealTimeStats />
          </div>
          <div class="left-bottom">
            <YakTradingData />
          </div>
        </div>

        <!-- 左中列 -->
        <div class="left-center-column">
          <div class="left-center-top">
            <ComprehensiveSalesStats />
          </div>
          <div class="left-center-bottom">
            <YakPriceTrend />
          </div>
        </div>
      </div>

      <!-- 中央区域 -->
      <div class="center-section">
        <div class="map-container">
          <ChinaMap />
          <!-- <ScrollingAnnouncement /> -->
          <!-- <div class="floating-table">
            <TransactionDetails />
          </div> -->
        </div>
      </div>

      <!-- 右侧区域 - 分为右中和右两列 -->
      <div class="right-section">
        <!-- 当供应信息展开时，整个右侧区域显示供应信息 -->
        <div v-if="isSupplyExpanded" class="expanded-supply-container">
          <SupplyDemandData
            :force-expanded="true"
            :initial-detail-id="supplyDetailId"
            @expand-change="handleSupplyExpand"
            @initial-detail-applied="clearSupplyDetailId"
          />
        </div>

        <!-- 正常状态下的右侧布局 -->
        <template v-else>
          <!-- 右中列 -->
          <div class="right-center-column">
            <div class="right-center-top">
              <ExchangeMonitor />
            </div>
            <div class="right-center-middle">
              <YakSalesTypeStats />
            </div>
            <div class="right-center-bottom">
              <PurchaserAnalysis />
            </div>
          </div>

          <!-- 右列 -->
          <div class="right-column">
            <div class="right-bottom">
              <SupplyDemandData :force-expanded="false" @expand-change="handleSupplyExpand" />
            </div>
            <div class="right-middle">
              <MarketRealtimeMonitor />
            </div>
            <div class="right-top">
              <MarketEnvironmentMonitor />
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在初始化布局...</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { configManager } from './utils/config.js'
import { loadSystemConfig } from './utils/systemConfig.js'
import { dataManager } from './utils/dataManager.js'

// 导入组件
import RealTimeStats from './components/RealTimeStats.vue'
import YakTradingData from './components/YakTradingData.vue'
import ComprehensiveSalesStats from './components/ComprehensiveSalesStats.vue'
import YakPriceTrend from './components/YakPriceTrend.vue'
import ChinaMap from './components/ChinaMap.vue'
import ScrollingAnnouncement from './components/ScrollingAnnouncement.vue'
import TransactionDetails from './components/TransactionDetails.vue'
import ExchangeMonitor from './components/ExchangeMonitor.vue'
import YakSalesTypeStats from './components/YakSalesTypeStats.vue'
import PurchaserAnalysis from './components/PurchaserAnalysis.vue'
import MarketEnvironmentMonitor from './components/MarketEnvironmentMonitor.vue'
import MarketRealtimeMonitor from './components/MarketRealtimeMonitor.vue'
import SupplyDemandData from './components/SupplyDemandData.vue'
import HeaderBar from './components/HeaderBar.vue'

// 响应式数据
const config = ref(null)
const systemConfig = ref({
  title: '/标题.png',
  titleBackground: '/images/标题背景.png'
})
const isLayoutReady = ref(false) // 控制页面渲染时机
const isSupplyExpanded = ref(false) // 控制供应信息组件是否展开
const supplyDetailId = ref('')

// 处理供应信息组件展开/收缩
const handleSupplyExpand = (payload) => {
  if (typeof payload === 'boolean') {
    isSupplyExpanded.value = payload
    if (!payload) {
      supplyDetailId.value = ''
    }
    return
  }
  isSupplyExpanded.value = !!payload.expanded
  if (payload.detailId) {
    supplyDetailId.value = payload.detailId
  }
}

const clearSupplyDetailId = () => {
  supplyDetailId.value = ''
}

onMounted(async () => {
  try {
    systemConfig.value = await loadSystemConfig()

    // 加载配置
    console.log('App.vue: 开始加载配置')
    config.value = await configManager.loadConfig()
    console.log('App.vue: 配置加载完成', config.value)

    // 设置CSS变量
    console.log('App.vue: 设置CSS变量')
    configManager.setCSSVariables()

    // 等待CSS变量生效和DOM更新
    await nextTick()

    // 再等待一帧确保样式完全应用
    await new Promise(resolve => requestAnimationFrame(resolve))
    console.log('App.vue: CSS变量已生效')

    // 加载数据配置
    console.log('App.vue: 开始加载数据配置')
    const loadedData = await dataManager.loadData()
    console.log('App.vue: 数据配置加载完成', loadedData)

    // 标记布局准备完成，开始渲染组件
    console.log('App.vue: 布局准备完成，开始渲染组件')
    isLayoutReady.value = true

    console.log('Dashboard 完全初始化完成')
  } catch (error) {
    console.error('Failed to initialize dashboard:', error)
    systemConfig.value = await loadSystemConfig()
    // 使用默认配置
    config.value = configManager.getDefaultConfig()
    configManager.setCSSVariables()

    // 等待DOM更新后显示页面
    await nextTick()
    await new Promise(resolve => requestAnimationFrame(resolve))
    isLayoutReady.value = true
  }
})
</script>

<style scoped>
/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0;
  padding-bottom: 20px;
}

/* 左侧区域布局 */
.left-section {
  flex: 1;
  display: flex;
  gap: 12px;
  min-width: 0;
}

.left-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
}

.left-center-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
}

.left-top,
.left-bottom,
.left-center-top,
.left-center-bottom {
  flex: 1;
  min-height: 0;
}

/* 中央区域布局 */
.center-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.map-container {
  position: relative;
  flex: 1;
  min-height: 0;
}

.floating-table {
  position: absolute;
  bottom: 20px;
  left: 20px;
  right: 20px;
  height: 200px;
  background: rgba(26, 31, 46, 0.95);
  border: 1px solid rgba(64, 158, 255, 0.4);
  border-radius: 8px;
  backdrop-filter: blur(10px);
  z-index: 100;
}

/* 右侧区域布局 */
.right-section {
  flex: 1;
  display: flex;
  gap: 12px;
  min-width: 0;
}

.right-center-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
}

.right-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
}

.right-center-top,
.right-center-middle,
.right-center-bottom,
.right-top,
.right-middle,
.right-bottom {
  flex: 1;
  min-height: 0;
}

/* 展开的供应信息容器 */
.expanded-supply-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 状态指示器动画 */
@keyframes pulse {

  0%,
  100% {
    opacity: 1;
    transform: scale(1);
  }

  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
}

.status-indicator.online {
  animation: pulse 2s infinite;
}

.status-indicator.loading {
  background: #E6A23C;
  box-shadow: 0 0 8px rgba(230, 162, 60, 0.6);
  animation: pulse 1s infinite;
}

/* 加载状态样式 */
.loading-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.loading-content {
  text-align: center;
  color: #409EFF;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(64, 158, 255, 0.3);
  border-top: 3px solid #409EFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

.loading-text {
  font-size: 16px;
  font-weight: 500;
  color: #a0a8b8;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>