import { computed, ref } from "vue";
import { onPullDownRefresh, onShow } from "@dcloudio/uni-app";

import type { AuthMenu } from "../../api/auth";
import {
  getHomeSummary,
  getProductionTrend,
  getWorkOrderStatus,
  type HomeSummary,
  type ProductionTrend,
  type WorkOrderStatus,
} from "../../api/home";
import { getAttendanceSummaryPage } from "../../api/hrm";
import { getPurchaseOrderPage } from "../../api/purchase";
import { getMaterialStockPage } from "../../api/wls";
import { appRouteMap } from "../../config/app-routes";
import { useAuth } from "../../stores/auth";
import { useNotify } from "../../stores/notify";

export interface CompanyHomeAction {
  name: string;
  detail: string;
  mark: string;
  tone: string;
  route: string;
  component: string;
}

export interface AttendanceOverview {
  headCount: number;
  attendanceRate: string;
  averageActualDays: string;
  lateCount: number;
  absentCount: number;
  leaveHours: number;
}

export interface SupplyOverview {
  stockQuantity: number;
  availableQuantity: number;
  purchaseTotal: number;
  pendingPurchaseTotal: number;
}

const ATTENDANCE_COMPONENT = "hrm/attendance/clock/index";
const actions: CompanyHomeAction[] = [
  { name: "考勤打卡", detail: "上下班打卡", mark: "勤", tone: "teal", route: "/pages/hrm/attendance-clock/index", component: ATTENDANCE_COMPONENT },
  { name: "生产报工", detail: "登记生产产出", mark: "报", tone: "blue", route: "/pages/mes/pro/feedback/index", component: "mes/pro/feedback/index" },
  { name: "生产工单", detail: "跟踪作业进度", mark: "单", tone: "violet", route: "/pages/mes/pro/workorder/index", component: "mes/pro/workorder/index" },
  { name: "质量管理", detail: "查看质检记录", mark: "质", tone: "amber", route: "/pages/mes/qc/ledger/index", component: "mes/qc/ledger/index" },
  { name: "设备点检", detail: "掌握设备状态", mark: "检", tone: "green", route: "/pages/mes/dv/checkrecord/index", component: "mes/dv/checkrecord/index" },
  { name: "物料库存", detail: "查询库存台账", mark: "库", tone: "cyan", route: "/pages/wls/material-stock/index", component: "wls/materialstock/index" },
  { name: "采购订单", detail: "采购业务管理", mark: "采", tone: "violet", route: "/pages/purchase/order/index", component: "erp/purchase/order/index" },
  { name: "销售订单", detail: "销售业务管理", mark: "销", tone: "blue", route: "/pages/sale/order/index", component: "erp/sale/order/index" },
];

function collectMenuComponents(menus: AuthMenu[]) {
  const result = new Set<string>();
  const visit = (items: AuthMenu[]) => items.forEach(item => {
    if (!item.visible) return;
    if (item.component) result.add(item.component);
    if (item.children?.length) visit(item.children);
  });
  visit(menus);
  return result;
}

export function useCompanyDashboard() {
  const { state, isLoggedIn, restoreUser } = useAuth();
  const { state: notifyState, refreshUnreadCount } = useNotify();
  const summary = ref<HomeSummary | null>(null);
  const trend = ref<ProductionTrend[]>([]);
  const workOrderStatus = ref<WorkOrderStatus[]>([]);
  const attendanceOverview = ref<AttendanceOverview | null>(null);
  const supplyOverview = ref<SupplyOverview | null>(null);
  const loading = ref(false);
  const loadError = ref("");

  const userName = computed(() => state.user?.nickname || state.user?.username || "同事");
  const greeting = computed(() => {
    const hour = new Date().getHours();
    if (hour < 6) return "夜深了";
    if (hour < 9) return "早上好";
    if (hour < 12) return "上午好";
    if (hour < 14) return "中午好";
    if (hour < 18) return "下午好";
    return "晚上好";
  });
  const today = computed(() => {
    const value = new Date();
    const weeks = ["日", "一", "二", "三", "四", "五", "六"];
    return `${value.getMonth() + 1}月${value.getDate()}日 星期${weeks[value.getDay()]}`;
  });
  const qualityRate = computed(() => {
    if (!summary.value) return "0.0";
    const total = summary.value.todayQualifiedQuantity + summary.value.todayUnqualifiedQuantity;
    return total ? (summary.value.todayQualifiedQuantity / total * 100).toFixed(1) : "0.0";
  });
  const equipmentRate = computed(() => {
    if (!summary.value?.machineryTotal) return "0";
    return (summary.value.machineryProducing / summary.value.machineryTotal * 100).toFixed(0);
  });
  const outputChange = computed(() => (summary.value?.todayOutput || 0) - (summary.value?.yesterdayOutput || 0));
  const trendMax = computed(() => Math.max(...trend.value.map(item => item.quantity), 1));
  const totalWorkOrders = computed(() => workOrderStatus.value.reduce((total, item) => total + item.count, 0));
  const menuComponents = computed(() => collectMenuComponents(state.menus));
  const visibleActions = computed(() => {
    const preferred = actions.filter(item => item.component === ATTENDANCE_COMPONENT || menuComponents.value.has(item.component));
    const used = new Set(preferred.map(item => item.component));
    const fallback: CompanyHomeAction[] = [];
    const visit = (items: AuthMenu[]) => items.forEach(item => {
      if (!item.visible) return;
      if (item.component && appRouteMap[item.component] && !used.has(item.component)) {
        used.add(item.component);
        fallback.push({
          name: item.name,
          detail: "快速进入",
          mark: item.name.slice(0, 1),
          tone: "slate",
          route: appRouteMap[item.component],
          component: item.component,
        });
      }
      if (item.children?.length) visit(item.children);
    });
    visit(state.menus);
    return preferred.concat(fallback).slice(0, 6);
  });

  const tabRoutes = ["/pages/home/index", "/pages/workbench/index", "/pages/message/index", "/pages/profile/index"];
  function openRoute(route?: string) {
    if (!route) return;
    if (tabRoutes.includes(route)) uni.switchTab({ url: route });
    else uni.navigateTo({ url: route });
  }
  function goMessages() { uni.switchTab({ url: "/pages/message/index" }); }
  function goLogin() { uni.navigateTo({ url: "/pages/login/index" }); }
  function formatDate(value: string) {
    const matched = value.match(/(\d{1,2})[-/](\d{1,2})$/);
    return matched ? `${matched[1]}/${matched[2]}` : value.slice(5);
  }
  function statusPercent(count: number) {
    return totalWorkOrders.value ? Math.max(count / totalWorkOrders.value * 100, 4) : 0;
  }

  async function loadDashboard() {
    if (!state.accessToken || loading.value) return;
    loading.value = true;
    loadError.value = "";
    try {
      const now = new Date();
      const yearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
      const [summaryData, trendData, statusData, attendanceData, stockData, purchaseData, pendingPurchaseData] = await Promise.all([
        getHomeSummary(state.accessToken),
        getProductionTrend(state.accessToken),
        getWorkOrderStatus(state.accessToken),
        getAttendanceSummaryPage(state.accessToken, { pageNo: 1, pageSize: 200, yearMonth }).catch(() => null),
        getMaterialStockPage(state.accessToken, { pageNo: 1, pageSize: 200 }).catch(() => null),
        getPurchaseOrderPage(state.accessToken, { pageNo: 1, pageSize: 1 }).catch(() => null),
        getPurchaseOrderPage(state.accessToken, { pageNo: 1, pageSize: 1, status: 10 }).catch(() => null),
      ]);
      summary.value = summaryData;
      trend.value = trendData;
      workOrderStatus.value = statusData;
      if (attendanceData) {
        const rows = attendanceData.list;
        const workDays = rows.reduce((total, item) => total + Number(item.workDays || 0), 0);
        const actualDays = rows.reduce((total, item) => total + Number(item.actualDays || 0), 0);
        attendanceOverview.value = {
          headCount: attendanceData.total,
          attendanceRate: workDays ? (actualDays / workDays * 100).toFixed(1) : "0.0",
          averageActualDays: rows.length ? (actualDays / rows.length).toFixed(1) : "0.0",
          lateCount: rows.reduce((total, item) => total + Number(item.lateCount || 0), 0),
          absentCount: rows.reduce((total, item) => total + Number(item.absentCount || 0), 0),
          leaveHours: rows.reduce((total, item) => total + Number(item.leaveHours || 0), 0),
        };
      }
      if (stockData || purchaseData || pendingPurchaseData) {
        const stockRows = stockData?.list || [];
        supplyOverview.value = {
          stockQuantity: stockRows.reduce((total, item) => total + Number(item.quantity || 0), 0),
          availableQuantity: stockRows.reduce((total, item) => total + Number(item.availableQuantity || 0), 0),
          purchaseTotal: purchaseData?.total || 0,
          pendingPurchaseTotal: pendingPurchaseData?.total || 0,
        };
      }
    } catch (cause) {
      loadError.value = cause instanceof Error ? cause.message : "首页数据加载失败";
    } finally {
      loading.value = false;
    }
  }
  async function refreshPage() {
    await restoreUser();
    try { await refreshUnreadCount(); } catch { /* 消息异常不影响首页 */ }
    await loadDashboard();
  }

  onShow(refreshPage);
  onPullDownRefresh(async () => { await refreshPage(); uni.stopPullDownRefresh(); });

  return {
    attendanceOverview, equipmentRate, formatDate, goLogin, goMessages, greeting, isLoggedIn, loadDashboard,
    loadError, loading, notifyState, openRoute, outputChange, qualityRate, statusPercent,
    summary, supplyOverview, today, totalWorkOrders, trend, trendMax, userName, visibleActions, workOrderStatus,
  };
}
