/**
 * Dashboard View
 * Statistics and overview cards
 */

import { adminApi } from '../api/admin.js';

const { ref, onMounted } = Vue;

export default {
  name: 'Dashboard',
  template: `
    <div class="dashboard-view">
      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else class="stats-grid">
        <div class="stats-card">
          <div class="label">今日收入 (CNY)</div>
          <div class="value">¥{{ stats.todayIncome / 100 }}</div>
          <div class="growth" :class="stats.dayIncomeGrowth < 0 ? 'down' : 'up'">
            {{ stats.dayIncomeGrowth }}% 较昨日
          </div>
        </div>
        
        <div class="stats-card">
          <div class="label">本月收入 (CNY)</div>
          <div class="value">¥{{ stats.currentMonthIncome / 100 }}</div>
          <div class="growth" :class="stats.monthIncomeGrowth < 0 ? 'down' : 'up'">
            {{ stats.monthIncomeGrowth }}% 较上月
          </div>
        </div>
        
        <div class="stats-card">
          <div class="label">总用户数</div>
          <div class="value">{{ stats.totalUsers }}</div>
          <div class="growth up">{{ stats.currentMonthNewUsers }} 本月新增</div>
        </div>
        
        <div class="stats-card">
          <div class="label">实时在线 (用户/设备)</div>
          <div class="value">{{ stats.onlineUsers }} / {{ stats.onlineDevices }}</div>
          <div class="sub">活跃节点: {{ stats.onlineNodes }}</div>
        </div>
      </div>
      
      <div class="traffic-section" v-if="!loading">
        <h3>流量概览</h3>
        <div class="traffic-grid">
           <div class="traffic-item">
             <span>今日已用:</span> <strong>{{ formatTraffic(stats.todayTraffic.total) }}</strong>
           </div>
           <div class="traffic-item">
             <span>本月已用:</span> <strong>{{ formatTraffic(stats.monthTraffic.total) }}</strong>
           </div>
           <div class="traffic-item">
             <span>累计已用:</span> <strong>{{ formatTraffic(stats.totalTraffic.total) }}</strong>
           </div>
        </div>
      </div>
    </div>
  `,
  setup() {
    const stats = ref({});
    const loading = ref(true);

    const loadStats = async () => {
      try {
        const res = await adminApi.getDashboardSummary();
        stats.value = res.data || res;
      } catch (e) {
        console.error('Failed to load dashboard stats', e);
      } finally {
        loading.value = false;
      }
    };

    const formatTraffic = (bytes) => {
        if (!bytes) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    onMounted(loadStats);

    return {
      stats,
      loading,
      formatTraffic
    };
  }
};
