Files
persionalBrand/apps/admin/src/main.tsx
T

208 lines
7.0 KiB
TypeScript

import React, { Suspense, useState } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import {
App,
Button,
Card,
Form,
Input,
Layout,
Menu,
Select,
Space,
Typography,
message,
} from "antd";
import { createApiClient } from "./lib/api.js";
const FeatureInquiriesPage = React.lazy(() =>
import("./features/inquiries/InquiriesPage.js").then((module) => ({
default: module.InquiriesPage,
})),
);
const FeatureTrustContentPage = React.lazy(() =>
import("./features/trust-content/TrustContentPage.js").then((module) => ({
default: module.TrustContentPage,
})),
);
const FeatureServicesPage = React.lazy(() =>
import("./features/services/ServicesPage.js").then((module) => ({
default: module.ServicesPage,
})),
);
const FeatureBrandPage = React.lazy(() =>
import("./features/brand/BrandPage.js").then((module) => ({ default: module.BrandPage })),
);
const FeatureWorkspacePage = React.lazy(() =>
import("./features/workspace/WorkspacePage.js").then((module) => ({
default: module.WorkspacePage,
})),
);
const FeatureOverviewPage = React.lazy(() =>
import("./features/overview/OverviewPage.js").then((module) => ({
default: module.OverviewPage,
})),
);
const FeatureCapabilitiesPage = React.lazy(() =>
import("./features/capabilities/CapabilitiesPage.js").then((module) => ({
default: module.CapabilitiesPage,
})),
);
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import "antd/dist/reset.css";
const queryClient = new QueryClient();
const api = createApiClient;
function Login({ onLogin }: { onLogin: () => void }) {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await api().loginAdmin(values.username, values.password);
localStorage.setItem("adminToken", result.token);
onLogin();
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
} finally {
setLoading(false);
}
}
return (
<Card title="个人品牌后台" style={{ maxWidth: 420, margin: "120px auto" }}>
<Form form={form} layout="vertical" onFinish={submit}>
<Form.Item name="username" label="账号" initialValue="admin" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
登录
</Button>
</Form>
</Card>
);
}
function Dashboard({ onLogout }: { onLogout: () => void }) {
const navigate = useNavigate();
const location = useLocation();
const brand = useQuery({
queryKey: ["admin-shell-brand"],
queryFn: () => createApiClient().getAdminBrand(),
});
const memberships = useQuery({
queryKey: ["admin-brand-memberships"],
queryFn: () => createApiClient().listAdminBrands(),
});
const switchBrand = async (brandId: string) => {
try {
const result = await createApiClient().switchAdminBrand(brandId);
localStorage.setItem("adminToken", result.token);
window.location.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败");
}
};
const page = location.pathname.split("/")[2] || "overview";
const items = [
{ key: "overview", label: "当前品牌概览" },
{ key: "brand", label: "当前品牌表达" },
{ key: "trust", label: "信任内容" },
{ key: "services", label: "业务提供项" },
{ key: "workspace", label: "模板与设置" },
{ key: "capabilities", label: "能力插件" },
{ key: "inquiries", label: "咨询记录" },
];
return (
<Layout style={{ minHeight: "100vh" }}>
<Layout.Sider>
<Typography.Title level={4} style={{ color: "white", padding: 20 }}>
当前品牌工作区
</Typography.Title>
<Menu
theme="dark"
selectedKeys={[page]}
onClick={({ key }) => navigate(`/admin/${key}`)}
items={items}
/>
</Layout.Sider>
<Layout>
<Layout.Header
style={{
background: "white",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Space>
<Typography.Text strong>{brand.data?.name || "当前品牌"}</Typography.Text>
<Typography.Text type="secondary">品牌工作区</Typography.Text>
<Select
size="small"
value={brand.data?.id}
loading={memberships.isLoading}
onChange={(value) => {
if (value) void switchBrand(value);
}}
options={(memberships.data ?? []).map((item) => ({
value: item.brand.id,
label: item.brand.name,
}))}
/>
</Space>
<Button type="text" onClick={onLogout}>
退出登录
</Button>
</Layout.Header>
<Layout.Content style={{ padding: 24 }}>
<Suspense fallback={<Card loading />}>
<Routes>
<Route path="/admin/overview" element={<FeatureOverviewPage />} />
<Route path="/admin/brand" element={<FeatureBrandPage />} />
<Route path="/admin/workspace" element={<FeatureWorkspacePage />} />
<Route path="/admin/capabilities" element={<FeatureCapabilitiesPage />} />
<Route path="/admin/trust" element={<FeatureTrustContentPage />} />
<Route path="/admin/services" element={<FeatureServicesPage />} />
<Route path="/admin/inquiries" element={<FeatureInquiriesPage />} />
<Route path="*" element={<Navigate to="/admin/overview" replace />} />
</Routes>
</Suspense>
</Layout.Content>
</Layout>
</Layout>
);
}
function Root() {
const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = () => {
localStorage.removeItem("adminToken");
setLoggedIn(false);
};
return loggedIn ? <Dashboard onLogout={logout} /> : <Login onLogin={() => setLoggedIn(true)} />;
}
createRoot(document.getElementById("app")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App>
<BrowserRouter>
<Root />
</BrowserRouter>
</App>
</QueryClientProvider>
</React.StrictMode>,
);