import { ref, onMounted, computed } from "vue";
import {
  getOverview,
  getStatistics,
  getQuickLinks,
  getDeviceStatus
} from "@/api/dashboard";
import type { OverviewData, StatisticsData, QuickLink, DeviceStatus } from "./types";

export function useDashboard() {
  const loading = ref(false);
  const overviewData = ref<OverviewData | null>(null);
  const statisticsRawData = ref<Record<string, any>>({});
  const quickLinksRawData = ref<Record<string, any>>({});
  const deviceStatusRawList = ref<{name: string; value: number; color: string}[]>([]);
  const statisticsType = ref("week");

  const statisticsData = computed<StatisticsData[]>(() => {
    const raw = statisticsRawData.value;
    const dates = raw.dates || [];
    const salesData = raw.salesData || [];
    const ordersData = raw.ordersData || [];
    
    return dates.map((date: string, index: number) => ({
      date,
      orders: ordersData[index] || 0,
      revenue: salesData[index] || 0,
      users: 0
    }));
  });

  const quickLinks = computed<QuickLink[]>(() => {
    const raw = quickLinksRawData.value;
    return [
      { id: 1, title: "设备管理", icon: "ri:device-line", path: "/device/list", count: raw.needRestock || 0 },
      { id: 2, title: "订单管理", icon: "ri:shopping-cart-line", path: "/order/list", count: raw.unpaidOrders || 0 },
      { id: 3, title: "用户管理", icon: "ri:user-3-line", path: "/user/list" },
      { id: 4, title: "库存管理", icon: "ri:stack-line", path: "/inventory/list" },
      { id: 5, title: "营销活动", icon: "ri:gift-line", path: "/marketing/activity" },
      { id: 6, title: "优惠券", icon: "ri:coupon-line", path: "/marketing/coupon" }
    ];
  });

  const deviceStatusList = computed<DeviceStatus[]>(() => {
    const list = deviceStatusRawList.value;
    if (!list || list.length === 0) return [];
    
    return list.map((item, index) => {
      const isOnline = item.name === "在线" || item.name?.includes("在线");
      return {
        deviceId: String(index + 1),
        deviceName: `设备 ${index + 1}`,
        shopName: "",
        status: isOnline ? 1 : 0,
        lastOnlineTime: "",
        temperature: 0,
        doorStatus: 0
      };
    });
  });

  async function fetchOverview() {
    try {
      const { data } = await getOverview();
      overviewData.value = data;
    } catch (error) {
      console.error("获取概览数据失败:", error);
    }
  }

  async function fetchStatistics() {
    try {
      const { data } = await getStatistics(statisticsType.value);
      statisticsRawData.value = data;
    } catch (error) {
      console.error("获取统计数据失败:", error);
    }
  }

  async function fetchQuickLinks() {
    try {
      const { data } = await getQuickLinks();
      quickLinksRawData.value = data;
    } catch (error) {
      console.error("获取快捷入口失败:", error);
    }
  }

  async function fetchDeviceStatus() {
    try {
      const { data } = await getDeviceStatus();
      deviceStatusRawList.value = data;
    } catch (error) {
      console.error("获取设备状态失败:", error);
    }
  }

  function changeStatisticsType(type: string) {
    statisticsType.value = type;
    fetchStatistics();
  }

  async function refreshAll() {
    loading.value = true;
    try {
      await Promise.all([
        fetchOverview(),
        fetchStatistics(),
        fetchQuickLinks(),
        fetchDeviceStatus()
      ]);
    } finally {
      loading.value = false;
    }
  }

  onMounted(() => {
    refreshAll();
  });

  return {
    loading,
    overviewData,
    statisticsData,
    quickLinks,
    deviceStatusList,
    statisticsType,
    changeStatisticsType,
    refreshAll
  };
}
