import React, { useEffect, useRef, useState } from "react"; import { EditorContent, useEditor } from "@tiptap/react"; import StarterKit from "@tiptap/starter-kit"; import Link from "@tiptap/extension-link"; import Image from "@tiptap/extension-image"; import { ArrowDown, ArrowLeft, ArrowUp, Bold, Check, Heading2, Heading3, Image as ImageIcon, Italic, Link as LinkIcon, List, Plus, Save, Search, Trash2, Undo2, Redo2, X, } from "lucide-react"; import { API, assetUrl } from "./api"; const SITE = "SIT0000000000001"; async function post(path: string, body: unknown) { const r = await fetch(API + path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!r.ok) throw new Error((await r.json()).message || "请求失败"); return r.json(); } type Attribute = { attributeCode?: string; attributeName: string; value: string; unit: string; sortNo: number; }; type Specification = { groupName: string; name: string; value: string; unit: string; sortNo: number; }; type Heading = { level: number; text: string; sortNo: number }; type ProductImage = { mediaCode: string; url: string; sortNo: number }; type MediaItem = { mediaCode: string; url: string; originalFileName: string; mediaType: string; altText?: string; }; type ProductCategory = { categoryCode: string; parentCategoryCode: string; categoryName: string; status: string; }; type ProductCategoryOption = ProductCategory & { depth: number }; type Props = { productCode?: string; onBack: () => void }; /** 将产品分类转换为带层级深度的下拉选项。 */ function buildCategoryOptions( categories: ProductCategory[], ): ProductCategoryOption[] { const children = new Map(); categories.forEach((category) => { const parentCode = category.parentCategoryCode || ""; children.set(parentCode, [...(children.get(parentCode) || []), category]); }); const result: ProductCategoryOption[] = []; const append = (parentCode: string, depth: number) => { (children.get(parentCode) || []).forEach((category) => { result.push({ ...category, depth }); append(category.categoryCode, depth + 1); }); }; append("", 0); return result; } /** 合并名称、分组和单位相同的历史规格,多个规格值使用斜杠分隔展示。 */ function mergeSpecifications(items: Specification[]): Specification[] { const merged = new Map(); items.forEach((item) => { const key = JSON.stringify([ item.groupName || "", item.name || "", item.unit || "", ]); const current = merged.get(key); if (!current) { merged.set(key, { ...item, sortNo: merged.size }); return; } const values = [ ...new Set( [...current.value.split("/"), ...item.value.split("/")] .map((value) => value.trim()) .filter(Boolean), ), ]; current.value = values.join(" / "); }); return [...merged.values()]; } /** 将误存为普通文本的富文本标签恢复为可编辑 HTML,正常富文本保持不变。 */ function normalizeRichTextHtml(content: string): string { if ( !content || !/&(?:amp;)?lt;\/?(?:h[1-6]|p|ul|ol|li|blockquote|table|img|a)\b/i.test( content, ) ) return content; const decoder = document.createElement("textarea"); let decoded = content; for (let index = 0; index < 2; index += 1) { decoder.innerHTML = decoded; const next = decoder.value; if (next === decoded) break; decoded = next; } decoded = decoded .replace(/^\s*
/i, "")
    .replace(/<\/code><\/pre>(?:

<\/p>)?\s*$/i, ""); if (!/<\/?(?:h[1-6]|p|ul|ol|li|blockquote|table|img|a)\b/i.test(decoded)) return content; const container = document.createElement("div"); container.innerHTML = decoded; return container.innerHTML; } export default function ProductEditor({ productCode, onBack }: Props) { const [form, setForm] = useState({ productName: "", slug: "", model: "", summary: "", primaryCategoryCode: "", coverMediaCode: "", coverMediaUrl: "", featured: false, inquiryEnabled: true, sortNo: 30, status: "DRAFT", }); const [images, setImages] = useState([]); const [attributes, setAttributes] = useState([]); const [specifications, setSpecifications] = useState([]); const [categories, setCategories] = useState([]); const [categoriesLoading, setCategoriesLoading] = useState(true); const [categoriesError, setCategoriesError] = useState(""); const [seo, setSeo] = useState({ title: "", description: "", keywords: "", h1: "", canonicalUrl: "", robots: "index,follow", ogTitle: "", ogDescription: "", ogImageUrl: "", status: "DRAFT", }); const [headings, setHeadings] = useState([]); const [saving, setSaving] = useState(false); const [notice, setNotice] = useState(""); const [mediaOpen, setMediaOpen] = useState(false); const [mediaItems, setMediaItems] = useState([]); const [mediaLoading, setMediaLoading] = useState(false); const [mediaQuery, setMediaQuery] = useState(""); const [selectedMedia, setSelectedMedia] = useState([]); const [uploading, setUploading] = useState(false); const coverInputRef = useRef(null); const editor = useEditor({ extensions: [StarterKit, Link.configure({ openOnClick: false }), Image], content: "

", }); useEffect(() => { let active = true; setCategoriesLoading(true); setCategoriesError(""); post("/products/categories/list", { siteCode: SITE }) .then((data) => { if (active) setCategories(buildCategoryOptions(data.items || [])); }) .catch((error) => { if (active) setCategoriesError( error instanceof Error ? error.message : "产品分类加载失败", ); }) .finally(() => { if (active) setCategoriesLoading(false); }); return () => { active = false; }; }, []); useEffect(() => { if (!productCode) return; post("/products/detail", { siteCode: SITE, productCode }).then((d) => { setForm({ ...d, coverMediaUrl: d.coverMediaUrl || "" }); setImages( d.images?.length ? d.images : d.coverMediaCode && d.coverMediaUrl ? [{ mediaCode: d.coverMediaCode, url: d.coverMediaUrl, sortNo: 0 }] : [], ); setAttributes(d.attributes || []); setSpecifications(mergeSpecifications(d.specifications || [])); editor?.commands.setContent( normalizeRichTextHtml(d.productContent || "

"), ); }); post("/seo/detail", { siteCode: SITE, pageType: "PRODUCT_DETAIL", targetCode: productCode, }) .then((d) => { setSeo({ title: d.title, description: d.description, keywords: d.keywords || "", h1: d.h1, canonicalUrl: d.canonicalUrl || "", robots: d.robots, ogTitle: d.ogTitle || "", ogDescription: d.ogDescription || "", ogImageUrl: d.ogImageUrl || "", status: d.status, }); setHeadings(d.headings || []); }) .catch(() => {}); }, [productCode, editor]); /** 校验并批量上传产品图片,保持用户选择顺序。 */ const upload = async (files?: FileList | null) => { if (!files?.length) return; const selected = [...files]; if (images.length + selected.length > 12) { setNotice("产品图片最多 12 张"); return; } if (selected.some((file) => file.size > 10 * 1024 * 1024)) { setNotice("单张图片不能超过 10MB"); return; } try { setUploading(true); setNotice(""); const uploaded: ProductImage[] = []; for (const file of selected) { const body = new FormData(); body.append("siteCode", SITE); body.append("altText", form.productName); body.append("file", file); const r = await fetch(API + "/media/upload-image", { method: "POST", body, }); if (r.status === 413) throw new Error( "图片超过服务器上传限制,请联系管理员调整 Nginx 上传上限", ); if (!r.ok) throw new Error( (await r.json().catch(() => ({}))).message || "上传失败", ); const d = await r.json(); uploaded.push({ mediaCode: d.mediaCode, url: d.url, sortNo: images.length + uploaded.length, }); } setImages((current) => [...current, ...uploaded].map((image, index) => ({ ...image, sortNo: index, })), ); setNotice(`成功上传 ${uploaded.length} 张产品图片`); } catch (e) { setNotice(e instanceof Error ? e.message : "上传失败"); } finally { setUploading(false); if (coverInputRef.current) coverInputRef.current.value = ""; } }; /** 调整产品图片顺序。 */ const moveImage = (index: number, direction: -1 | 1) => { const target = index + direction; if (target < 0 || target >= images.length) return; const next = [...images]; [next[index], next[target]] = [next[target], next[index]]; setImages(next.map((image, position) => ({ ...image, sortNo: position }))); }; const openMediaLibrary = async () => { setMediaOpen(true); setMediaLoading(true); try { const data = await post("/media/list", { siteCode: SITE, mediaType: "IMAGE", }); setMediaItems(data.items || []); } catch (e) { setNotice(e instanceof Error ? e.message : "素材库加载失败"); } finally { setMediaLoading(false); } }; const confirmMediaSelection = () => { const chosen = mediaItems.filter((item) => selectedMedia.includes(item.mediaCode), ); const room = 12 - images.length; if (chosen.length > room) { setNotice(`最多还可添加 ${room} 张图片`); return; } setImages((current) => [ ...current, ...chosen.map((item, index) => ({ mediaCode: item.mediaCode, url: item.url, sortNo: current.length + index, })), ]); setSelectedMedia([]); setMediaOpen(false); }; const save = async () => { if (!editor) return; try { setSaving(true); setNotice(""); const result = await post("/products/save", { productCode, siteCode: SITE, primaryCategoryCode: form.primaryCategoryCode, productName: form.productName, slug: form.slug, model: form.model, summary: form.summary, productContent: normalizeRichTextHtml(editor.getHTML()), coverMediaCode: images[0]?.mediaCode || "", images: images.map((image, index) => ({ mediaCode: image.mediaCode, sortNo: index, })), featured: form.featured, inquiryEnabled: form.inquiryEnabled, sortNo: form.sortNo, status: form.status, specifications, attributes, }); await post("/seo/save", { siteCode: SITE, pageType: "PRODUCT_DETAIL", targetCode: result.productCode, title: seo.title || form.productName, description: seo.description || form.summary, keywords: seo.keywords, h1: seo.h1 || form.productName, canonicalUrl: seo.canonicalUrl || `/products/${form.slug}`, robots: seo.robots, ogTitle: seo.ogTitle, ogDescription: seo.ogDescription, ogImageUrl: seo.ogImageUrl, structuredData: null, status: form.status, headings, }); setNotice("产品与 SEO 已保存"); if (!productCode) setTimeout(onBack, 500); } catch (e) { setNotice(e instanceof Error ? e.message : "保存失败"); } finally { setSaving(false); } }; const addLink = () => { const href = window.prompt("请输入链接地址"); if (href) editor?.chain().focus().setLink({ href }).run(); }; const addImage = () => { const src = window.prompt("请输入图片地址"); if (src) editor?.chain().focus().setImage({ src }).run(); }; return (
/

{productCode ? "编辑产品" : "新增产品"}

{notice && {notice}}

基础信息

setForm({ ...form, productName: e.target.value }) } /> setForm({ ...form, slug: e.target.value .toLowerCase() .replace(/[^a-z0-9-]/g, "-"), }) } /> setForm({ ...form, model: e.target.value })} /> setForm({ ...form, sortNo: Number(e.target.value) }) } />