<template>
  <div class="dashboard">
    <!-- <h1>系统概览</h1> -->
    
    <div class="dashboard-stats">
      <a-card title="栏舍数量" :bordered="false">
        <template #extra><a-tag color="blue">总计</a-tag></template>
        <p class="stat-number">{{ penCount }}</p>
      </a-card>
      
      <a-card title="牛只数量" :bordered="false">
        <template #extra><a-tag color="green">总计</a-tag></template>
        <p class="stat-number">{{ animalCount }}</p>
      </a-card>
      
      <a-card title="智能设备" :bordered="false">
        <template #extra><a-tag color="orange">在线率</a-tag></template>
        <p class="stat-number">{{ deviceCount }}</p>
      </a-card>
      
      <a-card title="智能预警" :bordered="false">
        <template #extra><a-tag color="red">本月</a-tag></template>
        <p class="stat-number clickable" @click="handleAlertClick">{{ alertCount }}</p>
      </a-card>
    </div>
    
    <div class="dashboard-charts">
      <a-card title="养殖场分布" :bordered="false" class="chart-card">
        <baidu-map 
          :markers="farmMarkers" 
          height="350px" 
          @marker-click="handleFarmClick"
        />
      </a-card>
    </div>
    
    <!-- 养殖场详情抽屉 -->
    <a-drawer
      :title="`养殖场详情 - ${selectedFarmId ? dataStore.farms.find(f => f.id == selectedFarmId)?.name : ''}`"
      :width="600"
      :visible="drawerVisible"
      @close="closeDrawer"
      :bodyStyle="{ paddingBottom: '80px' }"
    >
      <farm-detail v-if="selectedFarmId" :farm-id="selectedFarmId" />
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { RiseOutlined, FallOutlined } from '@ant-design/icons-vue'
import { useDataStore } from '../stores'
import { convertFarmsToMarkers } from '../utils/mapService'
import BaiduMap from './BaiduMap.vue'
import FarmDetail from './FarmDetail.vue'
import { message } from 'ant-design-vue'

// 使用数据存储
const dataStore = useDataStore()

// 使用路由
const router = useRouter()

// 图表容器引用
const trendChart = ref(null)

// 从store获取统计数据
const statsData = computed(() => dataStore.stats)

// 从store获取计算属性
const farmCount = computed(() => dataStore.farmCount)
const animalCount = computed(() => dataStore.animalCount)
const deviceCount = computed(() => dataStore.deviceCount)
const alertCount = computed(() => dataStore.alertCount)
const penCount = computed(() => dataStore.penCount)
const deviceOnlineRate = computed(() => dataStore.deviceOnlineRate)

// 养殖场地图标记
const farmMarkers = computed(() => {
  console.log('Dashboard: 计算farmMarkers')
  console.log('dataStore.farms:', dataStore.farms)
  const markers = convertFarmsToMarkers(dataStore.farms)
  console.log('转换后的markers:', markers)
  return markers
})

// 抽屉控制
const drawerVisible = ref(false)
const selectedFarmId = ref(null)

// 处理养殖场标记点击事件
function handleFarmClick(markerData) {
  // 设置选中的养殖场ID
  selectedFarmId.value = markerData.originalData.id
  // 打开抽屉
  drawerVisible.value = true
}

// 关闭抽屉
function closeDrawer() {
  drawerVisible.value = false
}

// 处理智能预警点击事件
function handleAlertClick() {
  console.log('点击智能预警，跳转到智能耳标预警页面')
  router.push('/smart-alerts/eartag')
}

// 图表实例
let trendChartInstance = null

// 定时刷新器
let refreshTimer = null

// 组件挂载后初始化数据和图表
onMounted(async () => {
  console.log('Dashboard: 组件挂载，开始加载数据')
  
  // 加载数据
  await dataStore.fetchAllData()
  
  console.log('Dashboard: 数据加载完成')
  console.log('farms数据:', dataStore.farms)
  
  // 初始化趋势图表
  initTrendChart()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
  
  // 启动定时刷新智能预警数据（每30秒刷新一次）
  startSmartAlertRefresh()
})

// 组件卸载时清理资源
onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
  
  // 清理定时器
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
  
  // 销毁图表实例
  if (trendChartInstance) {
    trendChartInstance.dispose()
    trendChartInstance = null
  }
})

// 初始化趋势图表
function initTrendChart() {
  if (!trendChart.value) return
  
  // 导入图表服务
  import('../utils/chartService').then(({ createTrendChart }) => {
    // 使用空数据初始化图表，等待后端数据
    const trendData = {
      xAxis: [],
      series: []
    }
    
    // 创建趋势图表
    trendChartInstance = createTrendChart(trendChart.value, trendData, {
      title: {
        text: '月度数据趋势',
        left: 'center'
      }
    })
  })
}

// 处理窗口大小变化
function handleResize() {
  if (trendChartInstance) {
    trendChartInstance.resize()
  }
}

// 启动智能预警数据定时刷新
function startSmartAlertRefresh() {
  // 每30秒刷新一次智能预警数据
  refreshTimer = setInterval(async () => {
    try {
      console.log('定时刷新智能预警数据...')
      await dataStore.fetchSmartAlerts()
      console.log('智能预警数据刷新完成，当前预警数量:', dataStore.alertCount)
    } catch (error) {
      console.error('刷新智能预警数据失败:', error)
    }
  }, 30000) // 30秒
}

// 停止智能预警数据定时刷新
function stopSmartAlertRefresh() {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.dashboard-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.clickable {
  cursor: pointer;
  transition: color 0.3s ease;
}

.stat-number.clickable:hover {
  color: #1890ff;
}

.stat-change {
  color: #8c8c8c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.dashboard-charts {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.chart-card {
  height: 400px;
}

.map-container,
.chart-container {
  height: 350px;
}

@media (max-width: 1200px) {
  .dashboard-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .dashboard-charts {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard-stats {
    grid-template-columns: 1fr;
  }
}
</style>