<template>
  <div class="dashboard">
    <!-- 临时添加API测试组件 -->
    <div style="position: fixed; top: 80px; right: 20px; z-index: 9999; width: 350px;">
      <ApiTest />
    </div>
    
    <header class="dashboard-header">
      <div class="header-decoration"></div>
      <div class="header-title">
        <h1>锡林郭勒盟智慧养殖产业数据大屏</h1>
      </div>
      <div class="header-info">
        <p>{{ currentTime }}</p>
      </div>
      <div class="header-decoration"></div>
    </header>
    
    <main class="dashboard-main">
      <!-- 左侧区域 -->
      <div class="left-section">
        <!-- 关键指标 -->
        <div class="metric-cards">
          <div class="metric-card" v-for="(metric, index) in keyMetrics" :key="index">
            <div class="metric-border card">
              <div class="metric-content">
                <div class="metric-title">{{ metric.title }}</div>
                <div class="metric-value">{{ metric.value }}</div>
                <div class="metric-change" :class="{ positive: metric.change > 0, negative: metric.change < 0 }">
                  {{ metric.change > 0 ? '↑' : '↓' }} {{ Math.abs(metric.change) }}%
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 风险预警 -->
        <div class="risk-card">
          <div class="chart-border card">
            <h3 class="chart-title">风险预警</h3>
            <div class="risk-content">
              <div class="risk-list">
                <div 
                  class="risk-item" 
                  v-for="(risk, index) in riskData" 
                  :key="index"
                >
                  <div class="risk-time">{{ risk.time }}</div>
                  <div class="risk-type">{{ risk.type }}</div>
                  <div class="risk-desc">{{ risk.desc }}</div>
                  <div class="risk-status" :class="risk.status">{{ risk.status }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 中间区域 -->
      <div class="center-section">
        <!-- 产业概览地图 -->
        <div class="center-top">
          <div class="center-border card">
            <h2>锡林郭勒盟产业分布</h2>
            <div class="map-container">
              <ThreeDMap 
                :height="300" 
                :map-data="mapData"
                ref="threeDMap"
              />
            </div>
          </div>
        </div>
        
        <!-- 月度产值趋势 -->
        <div class="center-middle">
          <div class="center-chart-border card">
            <h3 class="chart-title">月度产值趋势</h3>
            <div ref="breedingChart" class="chart-wrapper"></div>
          </div>
        </div>
        
        <!-- 区域分布 -->
        <div class="center-bottom">
          <div class="center-chart-border card">
            <h3 class="chart-title">区域分布</h3>
            <div ref="regionChart" class="chart-wrapper"></div>
          </div>
        </div>
      </div>
      
      <!-- 右侧区域 -->
      <div class="right-section">
        <!-- 交易数据 -->
        <div class="transaction-card">
          <div class="chart-border card">
            <h3 class="chart-title">交易数据</h3>
            <div ref="transactionChart" class="chart-wrapper"></div>
          </div>
        </div>
        
        <!-- 风险雷达 -->
        <div class="radar-card">
          <div class="chart-border card">
            <h3 class="chart-title">风险雷达</h3>
            <div ref="riskRadarChart" class="chart-wrapper"></div>
          </div>
        </div>
      </div>
    </main>
    
    <footer class="dashboard-footer">
      <div class="footer-decoration"></div>
      <div class="footer-content">
        <p>锡林郭勒盟智慧养殖产业数字化管理平台</p>
      </div>
      <div class="footer-decoration"></div>
    </footer>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import ThreeDMap from '@/components/map/ThreeDMap.vue'
import ApiTest from '@/components/ApiTest.vue'
import { fetchMapData } from '@/services/dashboard.js'

export default {
  name: 'Dashboard',
  components: {
    ThreeDMap,
    ApiTest
  },
  setup() {
    const currentTime = ref(new Date().toLocaleString())
    const breedingChart = ref(null)
    const transactionChart = ref(null)
    const regionChart = ref(null)
    const riskRadarChart = ref(null)
    const threeDMap = ref(null)
    
    let breedingChartInstance = null
    let transactionChartInstance = null
    let regionChartInstance = null
    let riskRadarChartInstance = null
    let timer = null

    // 关键指标数据
    const keyMetrics = ref([
      { title: '本月交易额', value: '¥860万', change: 5.7 },
      { title: '平均体重', value: '420kg', change: 0.8 },
      { title: '疫苗接种率', value: '98.6%', change: 2.1 },
      { title: '风险事件', value: '12起', change: -15.2 }
    ])

    // 风险数据
    const riskData = ref([
      { time: '08-19 10:23', type: '健康问题', desc: '某牧场发现疑似疫情', status: '处理中' },
      { time: '08-19 09:45', type: '环境异常', desc: '气温过高，注意防暑', status: '已处理' },
      { time: '08-19 08:30', type: '交易风险', desc: '一笔交易存在争议', status: '处理中' },
      { time: '08-18 16:15', type: '运输风险', desc: '运输路线受阻', status: '已处理' }
    ])

    // 地图数据
    const mapData = ref([])

    // 初始化图表
    const initCharts = () => {
      // 确保 DOM 元素已正确绑定
      if (!breedingChart.value || !regionChart.value) {
        console.error('ECharts 初始化失败: DOM 元素未正确绑定')
        return
      }

      // 养殖规模趋势图
      breedingChartInstance = echarts.init(breedingChart.value)
      breedingChartInstance.setOption({
        title: { text: '' },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: { type: 'value' },
        series: [{
          data: [8200, 9100, 10500, 11200, 12100, 12860],
          type: 'line',
          smooth: true,
          itemStyle: { color: '#4CAF50' },
          areaStyle: { color: 'rgba(76, 175, 80, 0.3)' }
        }]
      })

      // 交易数据分析图
      if (transactionChart.value) {
        transactionChartInstance = echarts.init(transactionChart.value)
        transactionChartInstance.setOption({
          tooltip: { trigger: 'item' },
          legend: { bottom: '0' },
          series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            data: [
              { value: 335, name: '线上交易' },
              { value: 310, name: '线下交易' },
              { value: 234, name: '跨区域交易' },
              { value: 135, name: '本地交易' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        })
      }

      // 区域分布图
      regionChartInstance = echarts.init(regionChart.value)
      regionChartInstance.setOption({
        tooltip: { trigger: 'item' },
        xAxis: {
          type: 'category',
          data: ['东乌旗', '西乌旗', '锡市', '镶黄旗', '正蓝旗', '太仆寺旗']
        },
        yAxis: { type: 'value' },
        series: [{
          data: [1200, 1800, 2400, 1600, 2100, 1900],
          type: 'bar',
          itemStyle: { color: '#388E3C' }
        }]
      })

      // 风险雷达图
      if (riskRadarChart.value) {
        riskRadarChartInstance = echarts.init(riskRadarChart.value)
        riskRadarChartInstance.setOption({
          title: { text: '' },
          tooltip: { trigger: 'item' },
          radar: {
            indicator: [
              { name: '健康问题', max: 100 },
              { name: '交易风险', max: 100 },
              { name: '环境异常', max: 100 },
              { name: '运输风险', max: 100 },
              { name: '市场波动', max: 100 }
            ]
          },
          series: [{
            type: 'radar',
            data: [{
              value: [60, 30, 50, 20, 40],
              name: '风险指数',
              itemStyle: { color: '#FF9800' },
              areaStyle: { color: 'rgba(255, 152, 0, 0.3)' }
            }]
          }]
        })
      }
    }

    // 获取地图数据
    const loadMapData = async () => {
      try {
        const data = await fetchMapData()
        if (data.regions && data.regions.length > 0) {
          mapData.value = data.regions
        } else {
          // 使用默认数据
          mapData.value = [
            { id: 'xlg', name: '锡林浩特市', cattle_count: 25600, farm_count: 120, coordinates: [116.093, 43.946] },
            { id: 'dwq', name: '东乌旗', cattle_count: 18500, farm_count: 95, coordinates: [116.980, 45.514] },
            { id: 'xwq', name: '西乌旗', cattle_count: 21200, farm_count: 108, coordinates: [117.615, 44.587] },
            { id: 'abg', name: '阿巴嘎旗', cattle_count: 16800, farm_count: 86, coordinates: [114.971, 44.022] },
            { id: 'snz', name: '苏尼特左旗', cattle_count: 12400, farm_count: 65, coordinates: [113.653, 43.859] }
          ]
        }
      } catch (error) {
        console.error('获取地图数据失败:', error)
        // 使用默认数据
        mapData.value = [
          { id: 'xlg', name: '锡林浩特市', cattle_count: 25600, farm_count: 120, coordinates: [116.093, 43.946] },
          { id: 'dwq', name: '东乌旗', cattle_count: 18500, farm_count: 95, coordinates: [116.980, 45.514] },
          { id: 'xwq', name: '西乌旗', cattle_count: 21200, farm_count: 108, coordinates: [117.615, 44.587] },
          { id: 'abg', name: '阿巴嘎旗', cattle_count: 16800, farm_count: 86, coordinates: [114.971, 44.022] },
          { id: 'snz', name: '苏尼特左旗', cattle_count: 12400, farm_count: 65, coordinates: [113.653, 43.859] }
        ]
      }
    }

    // 更新时间
    const updateTime = () => {
      currentTime.value = new Date().toLocaleString()
    }

    // 窗口大小改变时重绘图表
    const resizeCharts = () => {
      if (breedingChartInstance) breedingChartInstance.resize()
      if (transactionChartInstance) transactionChartInstance.resize()
      if (regionChartInstance) regionChartInstance.resize()
      if (riskRadarChartInstance) riskRadarChartInstance.resize()
    }

    onMounted(() => {
      initCharts()
      loadMapData()
      timer = setInterval(updateTime, 1000)
      window.addEventListener('resize', resizeCharts)
    })

    onBeforeUnmount(() => {
      clearInterval(timer)
      window.removeEventListener('resize', resizeCharts)
      if (breedingChartInstance) breedingChartInstance.dispose()
      if (transactionChartInstance) transactionChartInstance.dispose()
      if (regionChartInstance) regionChartInstance.dispose()
      if (riskRadarChartInstance) riskRadarChartInstance.dispose()
    })

    return {
      currentTime,
      keyMetrics,
      riskData,
      mapData,
      breedingChart,
      transactionChart,
      regionChart,
      riskRadarChart,
      threeDMap
    }
  }
}
</script>

<style scoped>
.dashboard {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #0f2027, #20555d, #2c5364);
  color: #fff;
  overflow: hidden;
  padding: 20px;
  box-sizing: border-box;
}

.dashboard-header {
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: var(--border-radius-lg);
  margin-bottom: 20px;
  box-shadow: var(--box-shadow);
}

.header-decoration {
  width: 200px;
  height: 40px;
  position: relative;
}

.header-decoration::before {
  content: '';
  position: absolute;
  top: 50%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #4CAF50, transparent);
}

.header-title {
  flex: 1;
  text-align: center;
}

.header-title h1 {
  font-size: 32px;
  font-weight: bold;
  margin: 0;
  background: linear-gradient(to right, #4CAF50, #8BC34A);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-align: center;
}

.header-info {
  font-size: 16px;
  color: #ccc;
}

.dashboard-main {
  display: flex;
  height: calc(100% - 180px);
  gap: 20px;
}

.left-section, .right-section {
  width: 25%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.center-section {
  width: 50%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.metric-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  height: 30%;
}

.metric-card {
  height: 100%;
}

.metric-border {
  width: 100%;
  height: 100%;
  padding: 15px;
}

.metric-content {
  text-align: center;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.metric-title {
  font-size: 16px;
  color: var(--text-secondary);
  margin-bottom: 10px;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: var(--primary-color);
}

.metric-change {
  font-size: 14px;
}

.metric-change.positive {
  color: var(--success-color);
}

.metric-change.negative {
  color: var(--danger-color);
}

.center-top {
  height: 40%;
}

.center-middle {
  height: 35%;
}

.center-bottom {
  height: 25%;
}

.center-border, .center-chart-border {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.map-container {
  height: calc(100% - 40px);
}

.center-content {
  height: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.total-count {
  text-align: center;
}

.count-title {
  font-size: 18px;
  color: var(--text-secondary);
  margin-bottom: 10px;
}

.count-value {
  font-size: 40px;
  font-weight: bold;
  color: var(--primary-color);
}

.count-unit {
  font-size: 16px;
  color: var(--text-secondary);
}

.growth-rate {
  text-align: center;
}

.rate-title {
  font-size: 18px;
  color: var(--text-secondary);
  margin-bottom: 10px;
}

.rate-value {
  font-size: 24px;
  font-weight: bold;
}

.rate-value.positive {
  color: var(--success-color);
}

.risk-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.risk-title {
  font-size: 18px;
  margin-bottom: 15px;
  text-align: center;
}

.risk-list {
  flex: 1;
  overflow-y: auto;
}

.risk-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.risk-time {
  width: 15%;
  font-size: 14px;
  color: var(--text-secondary);
}

.risk-type {
  width: 20%;
  font-size: 14px;
}

.risk-desc {
  flex: 1;
  font-size: 14px;
  padding: 0 10px;
}

.risk-status {
  width: 15%;
  font-size: 14px;
  text-align: center;
  padding: 4px 8px;
  border-radius: var(--border-radius-sm);
}

.risk-status.处理中 {
  background: rgba(255, 152, 0, 0.2);
  color: var(--warning-color);
}

.risk-status.已处理 {
  background: rgba(76, 175, 80, 0.2);
  color: var(--success-color);
}

.chart-title {
  font-size: 18px;
  text-align: center;
  margin-bottom: 15px;
}

.chart-wrapper {
  height: calc(100% - 40px);
}

.dashboard-footer {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  margin-top: 20px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--box-shadow);
}

.footer-decoration {
  width: 300px;
  height: 5px;
  position: relative;
}

.footer-decoration::before {
  content: '';
  position: absolute;
  top: 50%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #4CAF50, transparent);
}

.footer-content {
  text-align: center;
  font-size: 18px;
  color: var(--primary-color);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .dashboard-main {
    flex-direction: column;
    height: auto;
  }
  
  .left-section, .center-section, .right-section {
    width: 100%;
  }
  
  .metric-cards {
    height: auto;
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }
  
  .dashboard-header,
  .dashboard-footer {
    height: 80px;
    padding: 0 10px;
  }
  
  .header-title h1 {
    font-size: 24px;
  }
  
  .metric-cards {
    grid-template-columns: 1fr;
  }
  
  .risk-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .risk-time,
  .risk-type,
  .risk-desc,
  .risk-status {
    width: 100%;
  }
}
</style>