/**
 * 主布局与路由配置。
 *
 * - Ant Design Layout：Sider + Content + Footer（状态栏）
 * - react-router-dom：路由守卫 + 7 个一级菜单模块
 * - 路由守卫：未登录重定向到登录页
 *
 * CHANGE 2026-03-23 | Task 6 Change B：新增「定时任务」菜单项和 /trigger-jobs 路由；
 *   新增租户管理员、AI 监控子菜单组（4 子路由）、开发调试日志路由；
 *   import 7 个新页面组件（TriggerJobs/TenantAdmins/AIDashboard/AITriggerJobs/AIRunLogs/AIOperations/DevTrace）
 * CHANGE 2026-07-14 | Task 7.1：侧边栏菜单从 11 个一级项重组为 7 个；
 *   新增 Dashboard/ETLTasks/TriggerManager 占位页面；路由重构（新增重定向、移动路由）；
 *   移除 LogViewer 及不再直接路由的页面 import；登录后导航到 /dashboard
 */

import React, { useEffect, useState, useCallback } from "react";
import { Routes, Route, Navigate, useNavigate, useLocation } from "react-router-dom";
import { Layout, Menu, Spin, Space, Typography, Tag, Button, Tooltip } from "antd";
import {
  SettingOutlined,
  UnorderedListOutlined,
  DashboardOutlined,
  ClockCircleOutlined,
  LogoutOutlined,
  TeamOutlined,
  BugOutlined,
  ApartmentOutlined,
  RobotOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
import { useAuthStore } from "./store/authStore";
import { useBusinessDayStore } from "./store/businessDayStore";
import { fetchQueue } from "./api/execution";
import type { QueuedTask } from "./types";
import Login from "./pages/Login";
import EnvConfig from "./pages/EnvConfig";
import DBViewer from "./pages/DBViewer";
import TenantAdmins from "./pages/TenantAdmins";
import AIRunLogs from "./pages/AIRunLogs";
import AIDashboard from "./pages/AIDashboard";
import AIOperations from "./pages/AIOperations";
import AITriggerJobs from "./pages/AITriggerJobs";
import AIPrewarm from "./pages/AIPrewarm";
import DevTrace from "./pages/DevTrace";
import TriggerJobs from "./pages/TriggerJobs";
import TransferLog from "./pages/TransferLog";
import PendingReview from "./pages/PendingReview";
import TaskEngineConfig from "./pages/TaskEngineConfig";
import Dashboard from "./pages/Dashboard";
import ETLTasks from "./pages/ETLTasks";
import TriggerManager from "./pages/TriggerManager";
import RuntimeContextPage from "./pages/RuntimeContext";

const { Sider, Content, Footer } = Layout;
const { Text } = Typography;

/* ------------------------------------------------------------------ */
/*  侧边栏导航配置（7 个一级菜单）                                      */
/* ------------------------------------------------------------------ */

export const NAV_ITEMS: MenuProps["items"] = [
  { key: "/dashboard", icon: <DashboardOutlined />, label: "运行状态" },
  { key: "/etl-tasks", icon: <UnorderedListOutlined />, label: "ETL 任务管理" },
  {
    key: "task-engine-group", icon: <ApartmentOutlined />, label: "小程序任务管理",
    children: [
      { key: "/task-engine/trigger-jobs", label: "定时任务" },
      { key: "/task-engine/transfer-log", label: "转移日志" },
      { key: "/task-engine/pending-review", label: "待审核任务" },
      { key: "/task-engine/config", label: "参数管理" },
    ],
  },
  { key: "/triggers", icon: <ClockCircleOutlined />, label: "触发器管理" },
  {
    key: "ai-group", icon: <RobotOutlined />, label: "AI 管理",
    children: [
      { key: "/ai/dashboard", label: "总览" },
      { key: "/ai/operations", label: "手动操作" },
      { key: "/ai/prewarm", label: "预热进度" },
      { key: "/triggers?tab=ai", label: "触发器设置" },
      { key: "/ai/trigger-jobs", label: "调度历史" },
    ],
  },
  { key: "/tenant-admins", icon: <TeamOutlined />, label: "租户管理员" },
  {
    key: "settings-group", icon: <SettingOutlined />, label: "系统设置",
    children: [
      { key: "/settings/env-config", label: "环境配置" },
      { key: "/settings/runtime-context", label: "业务运行上下文 / 沙箱" },
      { key: "/triggers?tab=biz", label: "触发器配置" },
    ],
  },
  {
    key: "logs-group", icon: <BugOutlined />, label: "日志调试",
    children: [
      { key: "/logs/dev-trace", label: "DevTrace" },
      { key: "/logs/ai-run-logs", label: "AI 调用明细" },
      { key: "/logs/db-viewer", label: "数据库查看器" },
    ],
  },
];

/* ------------------------------------------------------------------ */
/*  侧边栏高亮辅助函数                                                 */
/* ------------------------------------------------------------------ */

/** 根据当前路径计算 selectedKeys */
export function getSelectedKeys(pathname: string, search: string): string[] {
  const fullPath = pathname + search;
  // 精确匹配含查询参数的菜单项（如 /triggers?tab=biz / ?tab=ai）
  if (fullPath === "/triggers?tab=biz") return ["/triggers?tab=biz"];
  if (fullPath === "/triggers?tab=ai") return ["/triggers?tab=ai"];
  // 子路由匹配
  if (pathname.startsWith("/task-engine/")) return [pathname];
  if (pathname.startsWith("/settings/")) return [pathname];
  if (pathname.startsWith("/logs/")) return [pathname];
  if (pathname.startsWith("/ai/")) return [pathname];
  // 一级路由直接匹配
  return [pathname];
}

/** 根据当前路径计算 defaultOpenKeys */
export function getDefaultOpenKeys(pathname: string): string[] {
  const keys: string[] = [];
  if (pathname.startsWith("/task-engine/")) keys.push("task-engine-group");
  if (pathname.startsWith("/settings/")) keys.push("settings-group");
  if (pathname.startsWith("/logs/")) keys.push("logs-group");
  if (pathname.startsWith("/ai/")) keys.push("ai-group");
  // 从 AI 菜单跳过来的"触发器设置"（/triggers?tab=ai）也展开 ai-group
  // 注：此函数参数只接收 pathname，无法判断 tab，交由路由侧 searchParams 处理默认展开
  // 触发器配置跳转入口也需要展开系统设置
  if (pathname === "/triggers") keys.push("settings-group");
  return keys;
}

/* ------------------------------------------------------------------ */
/*  路由守卫                                                           */
/* ------------------------------------------------------------------ */

const PrivateRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  return isAuthenticated ? <>{children}</> : <Navigate to="/login" replace />;
};

/* ------------------------------------------------------------------ */
/*  主布局                                                             */
/* ------------------------------------------------------------------ */

const AppLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const logout = useAuthStore((s) => s.logout);

  const [runningTask, setRunningTask] = useState<QueuedTask | null>(null);

  const pollQueue = useCallback(async () => {
    try {
      const queue = await fetchQueue();
      const running = queue.find((t) => t.status === "running") ?? null;
      setRunningTask(running);
    } catch {
      // 网络异常时不更新状态
    }
  }, []);

  useEffect(() => {
    pollQueue();
    const timer = setInterval(pollQueue, 5_000);
    return () => clearInterval(timer);
  }, [pollQueue]);

  const onMenuClick: MenuProps["onClick"] = ({ key }) => { navigate(key); };

  const handleLogout = () => {
    logout();
    navigate("/login", { replace: true });
  };

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider
        collapsible
        style={{
          overflow: "auto",
          height: "100vh",
          position: "sticky",
          top: 0,
          left: 0,
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div
          style={{
            height: 48,
            margin: "12px 16px",
            color: "#fff",
            fontWeight: 700,
            fontSize: 18,
            textAlign: "center",
            lineHeight: "48px",
            whiteSpace: "nowrap",
            overflow: "hidden",
            letterSpacing: 1,
          }}
        >
          NeoZQYY
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={getSelectedKeys(location.pathname, location.search)}
          defaultOpenKeys={getDefaultOpenKeys(location.pathname)}
          items={NAV_ITEMS}
          onClick={onMenuClick}
        />
        <div style={{ flex: 1 }} />
        <div style={{ padding: "12px 16px" }}>
          <Tooltip title="退出登录">
            <Button
              type="text" icon={<LogoutOutlined />}
              onClick={handleLogout}
              style={{ color: "rgba(255,255,255,0.65)", width: "100%" }}
            >
              退出
            </Button>
          </Tooltip>
        </div>
      </Sider>
      <Layout>
        <Content style={{ margin: 16, minHeight: 280 }}>
          <Routes>
            {/* 重定向 */}
            <Route path="/" element={<Navigate to="/dashboard" replace />} />
            <Route path="/log-viewer" element={<Navigate to="/etl-tasks?tab=queue" replace />} />

            {/* 新页面 */}
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/etl-tasks" element={<ETLTasks />} />
            <Route path="/triggers" element={<TriggerManager />} />

            {/* 小程序任务管理 */}
            <Route path="/task-engine/trigger-jobs" element={<TriggerJobs />} />
            <Route path="/task-engine/transfer-log" element={<TransferLog />} />
            <Route path="/task-engine/pending-review" element={<PendingReview />} />
            <Route path="/task-engine/config" element={<TaskEngineConfig />} />

            {/* 系统设置 */}
            <Route path="/settings/env-config" element={<EnvConfig />} />
            <Route path="/settings/runtime-context" element={<RuntimeContextPage />} />

            {/* AI 管理 */}
            <Route path="/ai/dashboard" element={<AIDashboard />} />
            <Route path="/ai/operations" element={<AIOperations />} />
            <Route path="/ai/prewarm" element={<AIPrewarm />} />
            <Route path="/ai/trigger-jobs" element={<AITriggerJobs />} />

            {/* 日志调试 */}
            <Route path="/logs/dev-trace" element={<DevTrace />} />
            <Route path="/logs/ai-run-logs" element={<AIRunLogs />} />
            <Route path="/logs/db-viewer" element={<DBViewer />} />

            {/* 不变 */}
            <Route path="/tenant-admins" element={<TenantAdmins />} />
          </Routes>
        </Content>
        <Footer
          style={{
            textAlign: "center",
            padding: "6px 16px",
            background: "#fafafa",
            borderTop: "1px solid #f0f0f0",
          }}
        >
          {runningTask ? (
            <Space size={8}>
              <Spin size="small" />
              <Text>执行中</Text>
              <Tag color="processing">{runningTask.config.flow}</Tag>
              <Text type="secondary" style={{ fontSize: 12 }}>
                {runningTask.config.tasks.slice(0, 3).join(", ")}
                {runningTask.config.tasks.length > 3 && ` +${runningTask.config.tasks.length - 3}`}
              </Text>
            </Space>
          ) : (
            <Text type="secondary" style={{ fontSize: 12 }}>无任务执行中</Text>
          )}
        </Footer>
      </Layout>
    </Layout>
  );
};

/* ------------------------------------------------------------------ */
/*  根组件                                                             */
/* ------------------------------------------------------------------ */

const App: React.FC = () => {
  const hydrate = useAuthStore((s) => s.hydrate);
  const initBusinessDay = useBusinessDayStore((s) => s.init);
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    hydrate();
    setHydrated(true);
    // 启动时请求一次营业日配置，降级策略在 store 内部处理
    initBusinessDay();
  }, [hydrate, initBusinessDay]);

  /* hydrate 完成前不渲染路由，避免 PrivateRoute 误判跳转到 /login */
  if (!hydrated) return <Spin style={{ display: "flex", justifyContent: "center", marginTop: 120 }} />;

  return (
    <Routes>
      <Route path="/login" element={<Login />} />
      <Route
        path="/*"
        element={
          <PrivateRoute>
            <AppLayout />
          </PrivateRoute>
        }
      />
    </Routes>
  );
};

export default App;
