| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655 |
- 'use client';
- import { useState, useEffect, useMemo } from 'react';
- import api from '@/lib/api';
- import {
- Plus,
- RefreshCw,
- Search,
- FileJson,
- Package,
- CheckCircle2,
- XCircle,
- Layers,
- Filter,
- X,
- RotateCcw,
- Sparkles
- } from 'lucide-react';
- import { toast } from 'react-hot-toast';
- import ProductList from '@/components/admin/products/ProductList';
- import ProductModal from '@/components/admin/products/ProductModal';
- import RoutingManager from '@/components/admin/products/RoutingManager';
- import SchemaManager from '@/components/admin/products/SchemaManager';
- import ProductDetailDrawer from '@/components/admin/products/ProductDetailDrawer';
- import Pagination from '@/components/common/Pagination';
- import { Product, SchemaItem } from '@/types';
- export default function AdminProductsPage() {
- const [allProducts, setAllProducts] = useState<Product[]>([]);
- const [schemas, setSchemas] = useState<SchemaItem[]>([]);
- const [loading, setLoading] = useState(true);
- const [statusTab, setStatusTab] = useState<'all' | 'active' | 'inactive'>('all');
- const [keyword, setKeyword] = useState('');
- const [selectedVisaType, setSelectedVisaType] = useState<string>('all');
- const [selectedCountry, setSelectedCountry] = useState<string>('all');
- const [selectedProvider, setSelectedProvider] = useState<string>('all');
- const [selectedSchemaFilter, setSelectedSchemaFilter] = useState<'all' | 'bound' | 'unbound'>('all');
- const [page, setPage] = useState(1);
- const [pageSize] = useState(10);
- const [isProductModalOpen, setProductModalOpen] = useState(false);
- const [isRoutingModalOpen, setRoutingModalOpen] = useState(false);
- const [isSchemaModalOpen, setSchemaModalOpen] = useState(false);
- const [isDrawerOpen, setIsDrawerOpen] = useState(false);
- const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
- useEffect(() => {
- fetchInitialData();
- }, []);
- const fetchInitialData = async () => {
- setLoading(true);
- try {
- const [prodRes, schemaRes] = await Promise.allSettled([
- api.get('/api/vas/product/list', { params: { size: 1000 } }),
- api.get('/api/vas/schema/list'),
- ]);
- if (prodRes.status === 'fulfilled') {
- const data = prodRes.value.data?.data || {};
- if (Array.isArray(data)) {
- setAllProducts(data);
- } else if (Array.isArray(data.items)) {
- setAllProducts(data.items);
- } else {
- setAllProducts([]);
- }
- } else {
- setAllProducts([]);
- }
- if (schemaRes.status === 'fulfilled') {
- const schemaData = schemaRes.value.data?.data;
- setSchemas(Array.isArray(schemaData) ? schemaData : []);
- }
- } catch {
- toast.error('加载商品列表失败');
- } finally {
- setLoading(false);
- }
- };
- const fetchProductsOnly = async () => {
- setLoading(true);
- try {
- const res = await api.get('/api/vas/product/list', { params: { size: 1000 } });
- const data = res.data?.data || {};
- if (Array.isArray(data)) {
- setAllProducts(data);
- } else if (Array.isArray(data.items)) {
- setAllProducts(data.items);
- } else {
- setAllProducts([]);
- }
- } catch {
- toast.error('刷新商品列表失败');
- } finally {
- setLoading(false);
- }
- };
- const availableCountries = useMemo(() => {
- const set = new Set<string>();
- allProducts.forEach((p) => {
- if (p.country && p.country.trim()) set.add(p.country.trim());
- });
- return Array.from(set).sort();
- }, [allProducts]);
- const availableProviders = useMemo(() => {
- const set = new Set<string>();
- allProducts.forEach((p) => {
- if (p.provider && p.provider.trim()) set.add(p.provider.trim());
- });
- return Array.from(set).sort();
- }, [allProducts]);
- const stats = useMemo(() => {
- const total = allProducts.length;
- const active = allProducts.filter((p) => Boolean(p.enabled)).length;
- const inactive = total - active;
- const withSchema = allProducts.filter((p) => p.schema_id && p.schema_id > 0).length;
- const schemaCoverage = total > 0 ? Math.round((withSchema / total) * 100) : 0;
- return { total, active, inactive, withSchema, schemaCoverage };
- }, [allProducts]);
- const filteredProducts = useMemo(() => {
- let list = [...allProducts];
- if (statusTab === 'active') {
- list = list.filter((p) => Boolean(p.enabled));
- } else if (statusTab === 'inactive') {
- list = list.filter((p) => !Boolean(p.enabled));
- }
- if (keyword.trim()) {
- const lowerKey = keyword.trim().toLowerCase();
- list = list.filter((p) => {
- const idMatch = String(p.id).includes(lowerKey);
- const titleMatch = (p.title || '').toLowerCase().includes(lowerKey);
- const countryMatch = (p.country || '').toLowerCase().includes(lowerKey);
- const cityMatch = (p.city || '').toLowerCase().includes(lowerKey);
- const providerMatch = (p.provider || '').toLowerCase().includes(lowerKey);
- return idMatch || titleMatch || countryMatch || cityMatch || providerMatch;
- });
- }
- if (selectedVisaType !== 'all') {
- list = list.filter((p) => (p.visa_type || 'Tourist').toLowerCase() === selectedVisaType.toLowerCase());
- }
- if (selectedCountry !== 'all') {
- list = list.filter((p) => p.country === selectedCountry);
- }
- if (selectedProvider !== 'all') {
- list = list.filter((p) => p.provider === selectedProvider);
- }
- if (selectedSchemaFilter === 'bound') {
- list = list.filter((p) => p.schema_id && p.schema_id > 0);
- } else if (selectedSchemaFilter === 'unbound') {
- list = list.filter((p) => !p.schema_id || p.schema_id === 0);
- }
- list.sort((a, b) => {
- const scoreA = typeof a.recommend_score === 'number' ? a.recommend_score : 0;
- const scoreB = typeof b.recommend_score === 'number' ? b.recommend_score : 0;
- if (scoreB !== scoreA) return scoreB - scoreA;
- return b.id - a.id;
- });
- return list;
- }, [
- allProducts,
- statusTab,
- keyword,
- selectedVisaType,
- selectedCountry,
- selectedProvider,
- selectedSchemaFilter,
- ]);
- const paginatedProducts = useMemo(() => {
- const start = (page - 1) * pageSize;
- return filteredProducts.slice(start, start + pageSize);
- }, [filteredProducts, page, pageSize]);
- const handleResetFilters = () => {
- setStatusTab('all');
- setKeyword('');
- setSelectedVisaType('all');
- setSelectedCountry('all');
- setSelectedProvider('all');
- setSelectedSchemaFilter('all');
- setPage(1);
- };
- const hasActiveFilters =
- statusTab !== 'all' ||
- keyword.trim() !== '' ||
- selectedVisaType !== 'all' ||
- selectedCountry !== 'all' ||
- selectedProvider !== 'all' ||
- selectedSchemaFilter !== 'all';
- const handleSaveProduct = async (data: any) => {
- try {
- if (data.id) {
- await api.post('/api/vas/product/update', data, { params: { id: data.id } });
- toast.success(`商品 #${data.id} 更新成功`);
- } else {
- await api.post('/api/vas/product/create', data);
- toast.success('新商品发布成功');
- }
- fetchProductsOnly();
- if (selectedProduct && selectedProduct.id === data.id) {
- setSelectedProduct({ ...selectedProduct, ...data });
- }
- } catch (error: any) {
- toast.error('操作失败: ' + (error.response?.data?.detail || error.message));
- throw error;
- }
- };
- const handleToggleStatus = async (product: Product) => {
- const newStatus = product.enabled ? 0 : 1;
- const actionText = newStatus ? '上架' : '下架';
- try {
- await api.post(
- '/api/vas/product/update',
- {
- ...product,
- enabled: newStatus,
- },
- { params: { id: product.id } }
- );
- toast.success(`商品 #${product.id} 已${actionText}`);
- setAllProducts((prev) =>
- prev.map((item) => (item.id === product.id ? { ...item, enabled: newStatus } : item))
- );
- if (selectedProduct && selectedProduct.id === product.id) {
- setSelectedProduct({ ...selectedProduct, enabled: newStatus });
- }
- } catch (e: any) {
- toast.error(`${actionText}操作失败: ` + (e.response?.data?.detail || e.message));
- throw e;
- }
- };
- const handleViewDetail = (product: Product) => {
- setSelectedProduct(product);
- setIsDrawerOpen(true);
- };
- const handleOpenCreate = () => {
- setSelectedProduct(null);
- setProductModalOpen(true);
- };
- const handleOpenEdit = (product: Product) => {
- setSelectedProduct(product);
- setProductModalOpen(true);
- };
- const handleOpenRouting = (product: Product) => {
- setSelectedProduct(product);
- setRoutingModalOpen(true);
- };
- const handleOpenSchemaManager = () => {
- setSchemaModalOpen(true);
- };
- return (
- <div className="space-y-6 font-mono">
-
- {/* 1. 顶部标头与主操作按钮 */}
- <div className="bg-neutral-100 border-2 border-black p-6 shadow-[6px_6px_0px_#000] flex flex-col md:flex-row md:items-center justify-between gap-4">
- <div>
- <div className="text-[10px] font-bold text-neutral-500 uppercase tracking-widest">[ VAS-CATALOG // 签证服务商品库 ]</div>
- <h1 className="text-xl sm:text-2xl font-black text-black uppercase mt-1">
- 商品配置中心与 SCHEMA 表单
- </h1>
- <p className="text-xs text-neutral-600 font-sans mt-0.5">
- 统一管理可售签证及增值服务、动态表单 Schema 绑定与后台自动化分发路由策略。
- </p>
- </div>
- {/* 顶部右侧主要操作 */}
- <div className="flex flex-wrap items-center gap-2">
- <button
- onClick={fetchProductsOnly}
- disabled={loading}
- className="p-2 bg-neutral-50 hover:bg-neutral-200 border-2 border-black text-black transition shadow-[2px_2px_0px_#000]"
- title="刷新数据"
- >
- <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
- </button>
- <button
- onClick={handleOpenSchemaManager}
- className="flex items-center gap-1.5 px-3.5 py-1.5 bg-white hover:bg-neutral-100 text-black border-2 border-black font-bold text-xs shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5 uppercase"
- >
- <FileJson size={14} />
- <span>[ 表单 SCHEMA 库 ]</span>
- </button>
- <button
- onClick={handleOpenCreate}
- className="flex items-center gap-1.5 px-4 py-1.5 bg-amber-300 hover:bg-amber-400 text-black border-2 border-black font-black text-xs shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5 uppercase whitespace-nowrap"
- >
- <Plus size={15} />
- <span>[ 发布新商品 ]</span>
- </button>
- </div>
- </div>
- {/* 2. 统计指标概览卡片 (4 列布局) */}
- <div className="grid grid-cols-2 lg:grid-cols-4 gap-3.5">
- {/* 卡片 1 */}
- <div
- onClick={() => {
- setStatusTab('all');
- setPage(1);
- }}
- className={`p-4 border-2 border-black cursor-pointer bg-white transition active:translate-x-0.5 active:translate-y-0.5 ${
- statusTab === 'all'
- ? 'bg-amber-100 shadow-[4px_4px_0px_#000]'
- : 'shadow-[2px_2px_0px_#000] hover:bg-neutral-50'
- }`}
- >
- <div className="flex items-center justify-between text-neutral-500 mb-2 border-b-2 border-black pb-1.5">
- <span className="text-[10px] font-black uppercase text-black">[ 全部服务商品 ]</span>
- <Package size={14} className="text-black" />
- </div>
- <div className="text-2xl font-black text-black">{stats.total} 个</div>
- <div className="text-[10px] text-neutral-500 font-sans mt-0.5">全量已配置服务</div>
- </div>
- {/* 卡片 2 */}
- <div
- onClick={() => {
- setStatusTab('active');
- setPage(1);
- }}
- className={`p-4 border-2 border-black cursor-pointer bg-white transition active:translate-x-0.5 active:translate-y-0.5 ${
- statusTab === 'active'
- ? 'bg-amber-300 shadow-[4px_4px_0px_#000]'
- : 'shadow-[2px_2px_0px_#000] hover:bg-neutral-50'
- }`}
- >
- <div className="flex items-center justify-between text-neutral-500 mb-2 border-b-2 border-black pb-1.5">
- <span className="text-[10px] font-black uppercase text-black">[ 上架在售 ]</span>
- <CheckCircle2 size={14} className="text-black" />
- </div>
- <div className="text-2xl font-black text-black">{stats.active} 个</div>
- <div className="text-[10px] text-neutral-500 font-sans mt-0.5">
- 占比 {stats.total > 0 ? Math.round((stats.active / stats.total) * 100) : 0}% 处于可售状态
- </div>
- </div>
- {/* 卡片 3 */}
- <div
- onClick={() => {
- setStatusTab('inactive');
- setPage(1);
- }}
- className={`p-4 border-2 border-black cursor-pointer bg-white transition active:translate-x-0.5 active:translate-y-0.5 ${
- statusTab === 'inactive'
- ? 'bg-neutral-200 shadow-[4px_4px_0px_#000]'
- : 'shadow-[2px_2px_0px_#000] hover:bg-neutral-50'
- }`}
- >
- <div className="flex items-center justify-between text-neutral-500 mb-2 border-b-2 border-black pb-1.5">
- <span className="text-[10px] font-black uppercase text-black">[ 已下架停售 ]</span>
- <XCircle size={14} className="text-black" />
- </div>
- <div className="text-2xl font-black text-black">{stats.inactive} 个</div>
- <div className="text-[10px] text-neutral-500 font-sans mt-0.5">暂停前台对外申请</div>
- </div>
- {/* 卡片 4 */}
- <div
- onClick={() => {
- setSelectedSchemaFilter(selectedSchemaFilter === 'bound' ? 'all' : 'bound');
- setPage(1);
- }}
- className={`p-4 border-2 border-black cursor-pointer bg-white transition active:translate-x-0.5 active:translate-y-0.5 ${
- selectedSchemaFilter === 'bound'
- ? 'bg-amber-200 shadow-[4px_4px_0px_#000]'
- : 'shadow-[2px_2px_0px_#000] hover:bg-neutral-50'
- }`}
- >
- <div className="flex items-center justify-between text-neutral-500 mb-2 border-b-2 border-black pb-1.5">
- <span className="text-[10px] font-black uppercase text-black">[ SCHEMA 覆盖率 ]</span>
- <FileJson size={14} className="text-black" />
- </div>
- <div className="text-2xl font-black text-black">
- {stats.withSchema} <span className="text-xs text-neutral-500 font-normal">/ {stats.total}</span>
- </div>
- <div className="text-[10px] text-neutral-500 font-sans mt-0.5">覆盖率 {stats.schemaCoverage}%</div>
- </div>
- </div>
- {/* 3. 筛选与操作工具栏 */}
- <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] space-y-3.5">
-
- {/* 状态 Tabs 与快速搜索 */}
- <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3">
-
- {/* Tabs 切换 */}
- <div className="flex gap-1 overflow-x-auto">
- <button
- onClick={() => {
- setStatusTab('all');
- setPage(1);
- }}
- className={`px-3 py-1.5 border-2 text-xs font-bold uppercase transition ${
- statusTab === 'all'
- ? 'bg-amber-300 border-black text-black shadow-[2px_2px_0px_#000]'
- : 'bg-neutral-50 border-black text-neutral-700 hover:bg-neutral-100'
- }`}
- >
- [ 全部 ({stats.total}) ]
- </button>
- <button
- onClick={() => {
- setStatusTab('active');
- setPage(1);
- }}
- className={`px-3 py-1.5 border-2 text-xs font-bold uppercase transition ${
- statusTab === 'active'
- ? 'bg-amber-300 border-black text-black shadow-[2px_2px_0px_#000]'
- : 'bg-neutral-50 border-black text-neutral-700 hover:bg-neutral-100'
- }`}
- >
- [ 上架在售 ({stats.active}) ]
- </button>
- <button
- onClick={() => {
- setStatusTab('inactive');
- setPage(1);
- }}
- className={`px-3 py-1.5 border-2 text-xs font-bold uppercase transition ${
- statusTab === 'inactive'
- ? 'bg-amber-300 border-black text-black shadow-[2px_2px_0px_#000]'
- : 'bg-neutral-50 border-black text-neutral-700 hover:bg-neutral-100'
- }`}
- >
- [ 已下架 ({stats.inactive}) ]
- </button>
- </div>
- {/* 搜索框 */}
- <div className="relative w-full lg:w-80">
- <input
- type="text"
- placeholder="搜索商品 / 国家 / 城市 / Provider..."
- className="w-full pl-9 pr-8 py-1.5 border-2 border-black bg-neutral-50 text-xs font-mono focus:bg-white outline-none shadow-[2px_2px_0px_#000] text-black"
- value={keyword}
- onChange={(e) => {
- setKeyword(e.target.value);
- setPage(1);
- }}
- />
- <Search size={14} className="absolute left-3 top-2 text-black pointer-events-none" />
- {keyword && (
- <button
- onClick={() => {
- setKeyword('');
- setPage(1);
- }}
- className="absolute right-2.5 top-1.5 text-black hover:text-rose-600 font-bold"
- >
- ✕
- </button>
- )}
- </div>
- </div>
- {/* 次级下拉组合筛选 */}
- <div className="flex flex-wrap items-center gap-2 pt-2 border-t-2 border-dashed border-neutral-300 text-xs">
- <div className="flex items-center gap-1 text-black font-bold uppercase mr-1">
- <Filter size={12} />
- <span>[ 维度过滤 ]:</span>
- </div>
- {/* 国家下拉 */}
- <select
- className="border-2 border-black px-2 py-1 bg-neutral-50 text-black text-xs font-bold outline-none shadow-[1px_1px_0px_#000]"
- value={selectedCountry}
- onChange={(e) => {
- setSelectedCountry(e.target.value);
- setPage(1);
- }}
- >
- <option value="all">[ 全部国家/地区 ]</option>
- {availableCountries.map((c) => (
- <option key={c} value={c}>
- {c}
- </option>
- ))}
- </select>
- {/* 签证类型下拉 */}
- <select
- className="border-2 border-black px-2 py-1 bg-neutral-50 text-black text-xs font-bold outline-none shadow-[1px_1px_0px_#000]"
- value={selectedVisaType}
- onChange={(e) => {
- setSelectedVisaType(e.target.value);
- setPage(1);
- }}
- >
- <option value="all">[ 全部签证类型 ]</option>
- <option value="Tourist">旅游签证 (Tourist)</option>
- <option value="Business">商务签证 (Business)</option>
- <option value="Family">探亲访友 (Family)</option>
- <option value="Student">留学签证 (Student)</option>
- <option value="Work">工作签证 (Work)</option>
- <option value="Transit">过境签证 (Transit)</option>
- <option value="e-Visa">电子签证 (e-Visa)</option>
- </select>
- {/* Provider 下拉 */}
- <select
- className="border-2 border-black px-2 py-1 bg-neutral-50 text-black text-xs font-bold outline-none shadow-[1px_1px_0px_#000]"
- value={selectedProvider}
- onChange={(e) => {
- setSelectedProvider(e.target.value);
- setPage(1);
- }}
- >
- <option value="all">[ 全部 Provider ]</option>
- {availableProviders.map((p) => (
- <option key={p} value={p}>
- {p}
- </option>
- ))}
- </select>
- {/* Schema 绑定下拉 */}
- <select
- className="border-2 border-black px-2 py-1 bg-neutral-50 text-black text-xs font-bold outline-none shadow-[1px_1px_0px_#000]"
- value={selectedSchemaFilter}
- onChange={(e: any) => {
- setSelectedSchemaFilter(e.target.value);
- setPage(1);
- }}
- >
- <option value="all">[ Schema 绑定状态 ]</option>
- <option value="bound">已绑定 Schema</option>
- <option value="unbound">未绑定 Schema</option>
- </select>
- {/* 重置筛选按钮 */}
- {hasActiveFilters && (
- <button
- onClick={handleResetFilters}
- className="px-2 py-1 bg-rose-100 hover:bg-rose-200 border border-black text-rose-800 text-[11px] font-bold shadow-[1px_1px_0px_#000] uppercase"
- >
- [ 清空筛选 ]
- </button>
- )}
- <div className="ml-auto text-[11px] text-neutral-500 font-bold uppercase">
- MATCHED: <span className="text-black">{filteredProducts.length}</span> ITEMS
- </div>
- </div>
- </div>
- {/* 4. 商品列表组件 */}
- <ProductList
- products={paginatedProducts}
- schemas={schemas}
- loading={loading}
- onViewDetail={handleViewDetail}
- onEdit={handleOpenEdit}
- onManageRouting={handleOpenRouting}
- onToggleStatus={handleToggleStatus}
- />
- {/* 5. 分页组件 */}
- {filteredProducts.length > 0 && (
- <div className="mt-4 flex justify-center md:justify-end">
- <Pagination
- currentPage={page}
- total={filteredProducts.length}
- pageSize={pageSize}
- onPageChange={(newPage) => setPage(newPage)}
- />
- </div>
- )}
- {/* 6. 商品全景详情抽屉 */}
- <ProductDetailDrawer
- isOpen={isDrawerOpen}
- onClose={() => setIsDrawerOpen(false)}
- product={selectedProduct}
- schemas={schemas}
- onEdit={(p) => {
- setIsDrawerOpen(false);
- handleOpenEdit(p);
- }}
- onManageRouting={(p) => {
- handleOpenRouting(p);
- }}
- onManageSchemas={() => {
- handleOpenSchemaManager();
- }}
- onToggleStatus={handleToggleStatus}
- />
- {/* 7. 新增/编辑商品弹窗 */}
- <ProductModal
- isOpen={isProductModalOpen}
- onClose={() => setProductModalOpen(false)}
- product={selectedProduct}
- onSubmit={handleSaveProduct}
- onManageSchemas={handleOpenSchemaManager}
- />
- {/* 8. 路由策略管理弹窗 */}
- {selectedProduct && (
- <RoutingManager
- isOpen={isRoutingModalOpen}
- productId={selectedProduct.id}
- productTitle={selectedProduct.title}
- onClose={() => {
- setRoutingModalOpen(false);
- fetchProductsOnly();
- }}
- />
- )}
- {/* 9. 表单 Schema 库管理器 */}
- <SchemaManager
- isOpen={isSchemaModalOpen}
- onClose={() => {
- setSchemaModalOpen(false);
- api.get('/api/vas/schema/list').then((res) => {
- setSchemas(Array.isArray(res.data?.data) ? res.data.data : []);
- });
- }}
- />
- </div>
- );
- }
|