2026-11-21 14:09:59 +08:00
import React ,{ useEffect , 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 { ArrowLeft , Bold , Heading2 , Heading3 , Image as ImageIcon , Italic , Link as LinkIcon , List , Plus , Save , Trash2 , Undo2 , Redo2 } from 'lucide-react' ;
2026-11-22 10:14:44 +08:00
import { API , assetUrl } from './api' ;
2026-11-21 14:09:59 +08:00
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 Props = { productCode? :string ; onBack : () => void };
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 [ attributes , setAttributes ] = useState < Attribute [] >([]); const [ specifications , setSpecifications ] = useState < Specification [] >([]); const [ categories , setCategories ] = useState < any [] >([]);
const [ seo , setSeo ] = useState ({ title : '' , description : '' , keywords : '' , h1 : '' , canonicalUrl : '' , robots : 'index,follow' , ogTitle : '' , ogDescription : '' , ogImageUrl : '' , status : 'DRAFT' }); const [ headings , setHeadings ] = useState < Heading [] >([]);
const [ saving , setSaving ] = useState ( false ); const [ notice , setNotice ] = useState ( '' );
const editor = useEditor ({ extensions : [ StarterKit , Link . configure ({ openOnClick :false }), Image ], content : '<p></p>' });
useEffect (() => { post ( '/products/categories/list' ,{ siteCode :SITE }). then ( x => setCategories ( x . items || [])); if ( ! productCode ) return ; post ( '/products/detail' ,{ siteCode :SITE , productCode }). then ( d => { setForm ({... d , coverMediaUrl :d.coverMediaUrl || '' }); setAttributes ( d . attributes || []); setSpecifications ( d . specifications || []); editor ? . commands . setContent ( d . productContent || '<p></p>' )}); 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 ( file? :File ) => { if ( ! file ) return ; try { 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 . ok ) throw new Error (( await r . json ()). message || '上传失败' ); const d = await r . json (); setForm ({... form , coverMediaCode :d.mediaCode , coverMediaUrl :d.url })} catch ( e ){ setNotice ( e instanceof Error ? e . message : '上传失败' )}};
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 :editor.getHTML (), coverMediaCode :form.coverMediaCode , 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 < div className = "product-editor" >< div className = "editor-top" >< div className = "breadcrumb-title" >< button className = "back" onClick = { onBack }>< ArrowLeft size = { 17 }/> 产品管理 </ button >< span > / </ span >< h1 >{ productCode ? '编辑产品' : '新增产品' }</ h1 >{ notice && < em >{ notice }</ em >}</ div >< div className = "editor-actions" >< button onClick = { onBack }> 取消 </ button >< button className = "primary" disabled = { saving ||! form . productName ||! form . slug } onClick = { save }>< Save size = { 16 }/>{ saving ? '保存中' : '保存' }</ button ></ div ></ div >< div className = "editor-layout" >< div className = "editor-main" >
< section className = "edit-section" >< h2 > 基础信息 </ h2 >< div className = "edit-grid" >< Field label = "产品标题 *" >< input value = { form . productName } onChange = { e => setForm ({... form , productName :e.target.value })}/></ Field >< Field label = "英文路径 *" >< input value = { form . slug } onChange = { e => setForm ({... form , slug :e.target.value.toLowerCase (). replace ( /[^a-z0-9-]/g , '-' )})}/></ Field >< Field label = "产品分类" >< select value = { form . primaryCategoryCode } onChange = { e => setForm ({... form , primaryCategoryCode :e.target.value })}>< option value = "" > 请选择 </ option >{ categories . map ( x => < option key = { x . categoryCode } value = { x . categoryCode }>{ x . categoryName }</ option >)}</ select ></ Field >< Field label = "产品型号" >< input value = { form . model || '' } onChange = { e => setForm ({... form , model :e.target.value })}/></ Field >< Field label = "排序" >< input type = "number" value = { form . sortNo } onChange = { e => setForm ({... form , sortNo :Number ( e . target . value )})}/></ Field >< Field wide label = "产品简介 *" >< textarea rows = { 4 } value = { form . summary || '' } onChange = { e => setForm ({... form , summary :e.target.value })}/></ Field ></ div ></ section >
2026-11-22 10:14:44 +08:00
< section className = "edit-section" >< h2 > 产品主图 </ h2 >< div className = "cover-upload" >{ form . coverMediaUrl ? < img src = { assetUrl ( form . coverMediaUrl )} alt = "产品主图预览" /> : < ImageIcon size = { 42 }/>}< label >< span > 选择图片 </ span >< input type = "file" accept = "image/jpeg,image/png,image/webp,image/gif" onChange = { e => upload ( e . target . files ? .[ 0 ])}/></ label >< p > 支持 JPG 、 PNG 、 WebP 、 GIF ,单图不超过 10 MB </ p ></ div ></ section >
2026-11-21 14:09:59 +08:00
< section className = "edit-section" >< div className = "section-head" >< h2 > 产品属性 </ h2 >< button onClick = {() => setAttributes ([... attributes ,{ attributeName : '' , value : '' , unit : '' , sortNo :attributes.length }])}>< Plus size = { 16 }/> 添加属性 </ button ></ div >{ attributes . map (( a , i ) => < div className = "repeat-row" key = { i }>< input placeholder = "Attribute name" value = { a . attributeName } onChange = { e => setAttributes ( attributes . map (( x , j ) => j === i ? {... x , attributeName :e.target.value } : x ))}/>< input placeholder = "Value" value = { a . value } onChange = { e => setAttributes ( attributes . map (( x , j ) => j === i ? {... x , value :e.target.value } : x ))}/>< input placeholder = "Unit" value = { a . unit || '' } onChange = { e => setAttributes ( attributes . map (( x , j ) => j === i ? {... x , unit :e.target.value } : x ))}/>< button title = "删除属性" onClick = {() => setAttributes ( attributes . filter (( _ , j ) => j !== i ))}>< Trash2 size = { 17 }/></ button ></ div >)}</ section >
< section className = "edit-section" >< div className = "section-head" >< h2 > 弱规格参数 </ h2 >< button onClick = {() => setSpecifications ([... specifications ,{ groupName : '' , name : '' , value : '' , unit : '' , sortNo :specifications.length }])}>< Plus size = { 16 }/> 添加规格 </ button ></ div >{ specifications . map (( s , i ) => < div className = "repeat-row specs-row" key = { i }>< input placeholder = "Group" value = { s . groupName || '' } onChange = { e => setSpecifications ( specifications . map (( x , j ) => j === i ? {... x , groupName :e.target.value } : x ))}/>< input placeholder = "Name" value = { s . name } onChange = { e => setSpecifications ( specifications . map (( x , j ) => j === i ? {... x , name :e.target.value } : x ))}/>< input placeholder = "Value" value = { s . value } onChange = { e => setSpecifications ( specifications . map (( x , j ) => j === i ? {... x , value :e.target.value } : x ))}/>< input placeholder = "Unit" value = { s . unit || '' } onChange = { e => setSpecifications ( specifications . map (( x , j ) => j === i ? {... x , unit :e.target.value } : x ))}/>< button title = "删除规格" onClick = {() => setSpecifications ( specifications . filter (( _ , j ) => j !== i ))}>< Trash2 size = { 17 }/></ button ></ div >)}</ section >
< section className = "edit-section" >< h2 > 产品详情 * </ h2 >< div className = "rich-editor" >< div className = "rich-toolbar" >< Tool title = "撤销" onClick = {() => editor ? . chain (). focus (). undo (). run ()}>< Undo2 /></ Tool >< Tool title = "重做" onClick = {() => editor ? . chain (). focus (). redo (). run ()}>< Redo2 /></ Tool >< Tool title = "粗体" active = { editor ? . isActive ( 'bold' )} onClick = {() => editor ? . chain (). focus (). toggleBold (). run ()}>< Bold /></ Tool >< Tool title = "斜体" active = { editor ? . isActive ( 'italic' )} onClick = {() => editor ? . chain (). focus (). toggleItalic (). run ()}>< Italic /></ Tool >< Tool title = "二级标题" active = { editor ? . isActive ( 'heading' ,{ level :2 })} onClick = {() => editor ? . chain (). focus (). toggleHeading ({ level :2 }). run ()}>< Heading2 /></ Tool >< Tool title = "三级标题" active = { editor ? . isActive ( 'heading' ,{ level :3 })} onClick = {() => editor ? . chain (). focus (). toggleHeading ({ level :3 }). run ()}>< Heading3 /></ Tool >< Tool title = "项目列表" onClick = {() => editor ? . chain (). focus (). toggleBulletList (). run ()}>< List /></ Tool >< Tool title = "链接" onClick = { addLink }>< LinkIcon /></ Tool >< Tool title = "插入图片" onClick = { addImage }>< ImageIcon /></ Tool ></ div >< EditorContent editor = { editor }/></ div ></ section >
</ div >< aside className = "editor-side" >< section className = "edit-section" >< h2 > 发布 </ h2 >< Field label = "状态" >< select value = { form . status } onChange = { e => setForm ({... form , status :e.target.value })}>< option value = "DRAFT" > 草稿 </ option >< option value = "PUBLISHED" > 上架 </ option >< option value = "OFFLINE" > 下线 </ option ></ select ></ Field >< label className = "check" >< input type = "checkbox" checked = { form . inquiryEnabled } onChange = { e => setForm ({... form , inquiryEnabled :e.target.checked })}/> 启用产品询盘 </ label >< label className = "check" >< input type = "checkbox" checked = { form . featured } onChange = { e => setForm ({... form , featured :e.target.checked })}/> 推荐产品 </ label ></ section >< section className = "edit-section" >< h2 > 搜索引擎优化 </ h2 >< Field label = "SEO 标题" >< input maxLength = { 70 } value = { seo . title } onChange = { e => setSeo ({... seo , title :e.target.value })}/></ Field >< Field label = "SEO 描述" >< textarea maxLength = { 160 } rows = { 4 } value = { seo . description } onChange = { e => setSeo ({... seo , description :e.target.value })}/></ Field >< Field label = "SEO 关键词" >< input value = { seo . keywords } onChange = { e => setSeo ({... seo , keywords :e.target.value })}/></ Field >< Field label = "H1" >< input maxLength = { 120 } value = { seo . h1 } onChange = { e => setSeo ({... seo , h1 :e.target.value })}/></ Field >< Field label = "Canonical" >< input value = { seo . canonicalUrl } placeholder = { `/products/ ${ form . slug } ` } onChange = { e => setSeo ({... seo , canonicalUrl :e.target.value })}/></ Field >< div className = "section-head" >< h3 > H2 / H3 标签 </ h3 >< button onClick = {() => setHeadings ([... headings ,{ level :2 , text : '' , sortNo :headings.length }])}>< Plus size = { 15 }/></ button ></ div >{ headings . map (( h , i ) => < div className = "heading-row" key = { i }>< select value = { h . level } onChange = { e => setHeadings ( headings . map (( x , j ) => j === i ? {... x , level :Number ( e . target . value )} : x ))}>< option value = { 2 }> H2 </ option >< option value = { 3 }> H3 </ option ></ select >< input value = { h . text } onChange = { e => setHeadings ( headings . map (( x , j ) => j === i ? {... x , text :e.target.value } : x ))}/>< button onClick = {() => setHeadings ( headings . filter (( _ , j ) => j !== i ))}>< Trash2 size = { 15 }/></ button ></ div >)}</ section ></ aside ></ div ></ div >
}
function Field ({ label , wide , children } : { label :string ; wide? :boolean ; children :React.ReactNode }){ return < label className = { wide ? 'wide' : '' }>< span >{ label }</ span >{ children }</ label >}
function Tool ({ title , active , onClick , children } : { title :string ; active? :boolean ; onClick : () => void ; children :React.ReactElement }){ return < button type = "button" title = { title } className = { active ? 'active' : '' } onClick = { onClick }>{ React . cloneElement ( children ,{ size :18 } as any )}</ button >}