<template>
  <div class="dashboard-container">
    <!-- 顶部欢迎区域 -->
    <div class="welcome-header">
      <a-row align="center">
        <a-col :span="12">
          <a-space size="medium" align="center">
            <a-avatar :size="64" style="background-color: #165DFF">Admin</a-avatar>
            <div class="welcome-text">
              <div class="title">早安，管理员，祝你开心每一天！</div>
              <div class="subtitle">今日天气晴朗，适合工作。</div>
            </div>
          </a-space>
        </a-col>
        <a-col :span="12" style="text-align: right;">
          <a-space size="large">
            <div class="stat-item">
              <div class="label">设备总数</div>
              <div class="value">{{ stats.total_devices }}</div>
            </div>
            <div class="stat-item">
              <div class="label">告警数量</div>
              <div class="value">{{ stats.active_alarms }}</div>
            </div>
            <div class="stat-item">
              <div class="label">系统消息</div>
              <div class="value">3</div>
            </div>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 内容区域 -->
    <a-row :gutter="20" style="margin-top: 20px;">
      <!-- 左侧主要内容 -->
      <a-col :span="16">
        <!-- 数据概览卡片 -->
        <a-grid :cols="24" :colGap="12" :rowGap="12" style="margin-bottom: 20px;">
          <a-grid-item :span="8">
            <a-card :bordered="false" class="data-card">
              <a-statistic title="今日电力能耗" :value="stats.total_energy" :precision="2" show-group-separator>
                <template #suffix>kWh</template>
              </a-statistic>
            </a-card>
          </a-grid-item>
          <a-grid-item :span="8">
            <a-card :bordered="false" class="data-card">
              <a-statistic title="实时电力功率" :value="stats.total_power" :precision="2" show-group-separator>
                <template #suffix>kW</template>
              </a-statistic>
            </a-card>
          </a-grid-item>
          <a-grid-item :span="8">
            <a-card :bordered="false" class="data-card">
              <a-statistic title="设备在线率" :value="stats.online_rate" :precision="1" :value-style="{ color: '#00b42a' }">
                <template #suffix>%</template>
                <template #prefix>
                  <icon-check-circle-fill style="color: #00b42a" />
                </template>
              </a-statistic>
            </a-card>
          </a-grid-item>
        </a-grid>

        <!-- 图表区域 -->
        <a-card class="general-card" title="能耗趋势 (最近7天)" :bordered="false" style="margin-bottom: 20px;">
          <div ref="chartRef" style="height: 350px;"></div>
        </a-card>

        <!-- 电力功率曲线 -->
        <a-card class="general-card" title="电力功率曲线 (最近24小时)" :bordered="false">
          <div ref="powerChartRef" style="height: 350px;"></div>
        </a-card>
      </a-col>

      <!-- 右侧侧边栏 -->
      <a-col :span="8">
        <!-- 公告/动态 -->
        <a-card class="general-card" title="最近动态" :bordered="false" style="height: 100%">
          <a-list :split="false">
            <a-list-item v-for="(item, index) in stats.recent_activities" :key="index">
              <a-list-item-meta :title="item.title" :description="item.description">
                <template #avatar>
                  <a-tag :color="item.level === 'danger' ? 'red' : (item.level === 'success' ? 'green' : (item.level === 'warning' ? 'orange' : 'blue'))">
                    {{ item.type === 'alarm' ? '告警' : '消息' }}
                  </a-tag>
                </template>
                <template #description>
                  {{ item.description }}
                  <div style="font-size: 12px; color: var(--color-text-3); margin-top: 4px">
                    {{ new Date(item.time).toLocaleString() }}
                  </div>
                </template>
              </a-list-item-meta>
            </a-list-item>
            <a-empty v-if="!stats.recent_activities || stats.recent_activities.length === 0" description="暂无动态" />
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { 
  getTodayEnergy, 
  getRealtimePower, 
  getDeviceOverview, 
  getEnergyTrend, 
  getPowerTrend,
  getRecentActivities 
} from '../../api/monitor';
import { IconCheckCircleFill } from '@arco-design/web-vue/es/icon';

const loading = ref(false);
const chartRef = ref<HTMLElement | null>(null);
const powerChartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
let powerChartInstance: echarts.ECharts | null = null;
const timers = ref<number[]>([]);

const stats = ref({
  total_energy: 0,
  total_power: 0,
  active_alarms: 0,
  online_rate: 0,
  total_devices: 0,
  energy_trend: [] as number[],
  dates: [] as string[],
  power_trend: [] as number[],
  power_times: [] as string[],
  recent_activities: [] as any[]
});

const initChart = (data: number[], dates?: string[]) => {
  if (chartRef.value) {
    if (chartInstance) {
      chartInstance.setOption({
        xAxis: {
          data: dates || ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        series: [{ data: data }]
      });
      return;
    }
    chartInstance = echarts.init(chartRef.value);
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates || ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        axisLine: {
          lineStyle: {
            color: '#86909C'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: 'kWh',
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#E5E6EB'
          }
        }
      },
      series: [
        {
          data: data,
          type: 'line',
          smooth: true,
          showSymbol: false,
          itemStyle: {
            color: '#165DFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(22, 93, 255, 0.5)' },
              { offset: 1, color: 'rgba(22, 93, 255, 0.1)' }
            ])
          }
        }
      ],
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#fff',
        borderColor: '#E5E6EB',
        textStyle: {
          color: '#1D2129'
        }
      }
    };
    chartInstance.setOption(option);
  }
};

const initPowerChart = (data: number[], times?: string[]) => {
  if (powerChartRef.value) {
    if (powerChartInstance) {
      powerChartInstance.setOption({
        xAxis: { data: times || [] },
        series: [{ data: data }]
      });
      return;
    }
    powerChartInstance = echarts.init(powerChartRef.value);
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: times || [],
        axisLine: { lineStyle: { color: '#86909C' } }
      },
      yAxis: {
        type: 'value',
        name: 'kW',
        splitLine: { lineStyle: { type: 'dashed', color: '#E5E6EB' } }
      },
      series: [
        {
          data: data,
          type: 'line',
          smooth: true,
          showSymbol: false,
          itemStyle: { color: '#F53F3F' }, 
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(245, 63, 63, 0.5)' },
              { offset: 1, color: 'rgba(245, 63, 63, 0.1)' }
            ])
          }
        }
      ],
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#fff',
        borderColor: '#E5E6EB',
        textStyle: { color: '#1D2129' }
      }
    };
    powerChartInstance.setOption(option);
  }
};

// Independent fetch functions
const fetchRealtimeData = async () => {
  try {
    const [energyRes, powerRes] = await Promise.all([
      getTodayEnergy(), 
      getRealtimePower()
    ]);
    stats.value.total_energy = energyRes.value;
    stats.value.total_power = powerRes.value;
  } catch (e) { console.error("Realtime data fetch error", e); }
};

const fetchStatusData = async () => {
  try {
    const [overviewRes, activitiesRes] = await Promise.all([
      getDeviceOverview(),
      getRecentActivities()
    ]);
    stats.value.active_alarms = overviewRes.active_alarms;
    stats.value.online_rate = overviewRes.online_rate;
    stats.value.total_devices = overviewRes.total_devices;
    stats.value.recent_activities = activitiesRes.activities;
  } catch (e) { console.error("Status data fetch error", e); }
};

const fetchChartData = async () => {
  try {
    const [trendRes, powerTrendRes] = await Promise.all([
      getEnergyTrend(),
      getPowerTrend()
    ]);
    stats.value.energy_trend = trendRes.trend;
    stats.value.dates = trendRes.dates || [];
    initChart(stats.value.energy_trend, stats.value.dates);

    stats.value.power_trend = powerTrendRes.trend;
    stats.value.power_times = powerTrendRes.times || [];
    initPowerChart(stats.value.power_trend, stats.value.power_times);
  } catch (e) { console.error("Chart data fetch error", e); }
};

const initData = async () => {
  loading.value = true;
  await Promise.all([fetchRealtimeData(), fetchStatusData(), fetchChartData()]);
  loading.value = false;
};

onMounted(() => {
  initData();
  window.addEventListener('resize', handleResize);

  // 1. High frequency (5s): Energy & Power
  timers.value.push(window.setInterval(fetchRealtimeData, 5000));

  // 2. Medium frequency (15s): Status & Activities
  timers.value.push(window.setInterval(fetchStatusData, 15000));

  // 3. Low frequency (60s): Charts
  timers.value.push(window.setInterval(fetchChartData, 60000));
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (chartInstance) {
    chartInstance.dispose();
  }
  if (powerChartInstance) {
    powerChartInstance.dispose();
  }
  // Clear all timers
  timers.value.forEach(timer => clearInterval(timer));
  timers.value = [];
});

const handleResize = () => {
  chartInstance?.resize();
  powerChartInstance?.resize();
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: var(--color-fill-2);
  min-height: 100vh;
}

.welcome-header {
  background: var(--color-bg-2);
  padding: 20px 24px;
  border-radius: 4px;
}

.welcome-text .title {
  font-size: 20px;
  color: var(--color-text-1);
  font-weight: 500;
  margin-bottom: 4px;
}

.welcome-text .subtitle {
  font-size: 14px;
  color: var(--color-text-3);
}

.stat-item {
  text-align: center;
  padding: 0 16px;
  position: relative;
}

.stat-item:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 16px;
  width: 1px;
  background-color: var(--color-border);
}

.stat-item .label {
  font-size: 12px;
  color: var(--color-text-3);
  margin-bottom: 4px;
}

.stat-item .value {
  font-size: 24px;
  color: var(--color-text-1);
  font-weight: 500;
  font-family: 'Bebas Neue', sans-serif; /* 假设有这种数字字体 */
}

.data-card {
  height: 100%;
  transition: all 0.3s;
}

.data-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.general-card {
  border-radius: 4px;
  border: none;
}

:deep(.arco-statistic-title) {
  margin-bottom: 10px;
}
</style>
