import { App, Form } from "antd"; import { useMutation, useQuery } from "@tanstack/react-query"; import type { QueryClient } from "@tanstack/react-query"; import { useCallback, useEffect, useMemo, useState } from "react"; import type { FormInstance } from "antd"; import type { AdminTemplateContent, BrandProfile, Offering, TemplateAdminSection, TrustContent, } from "@personal-brand/api-client"; import { createApiClient } from "../../lib/api.js"; import { getFullFormValues } from "../../lib/form-values.js"; import { applyBrandPreviewValues, applyPresentationValues, applyStandardBrandValues, presentationFieldName, readPresentationValue, type PresentationValues, } from "../../lib/presentation/presentation-bindings.js"; const standardBrandBindings = [ "brand.name", "brand.tagline", "brand.avatarUrl", "brand.description", "brand.contactPhone", "brand.contactWechat", "brand.address", ] as const; export interface BrandPresentationFormState { form: FormInstance; initialValues: PresentationValues; } export function useBrandPresentationSections( templateContent: AdminTemplateContent | null | undefined, ): TemplateAdminSection[] { return useMemo(() => { const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({ ...field, binding: field.binding ?? `brand.config.templateData.${field.key}`, })); return [ ...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({ key: `template-data:${page}`, title: "页面方案专属内容", description: "这些字段由当前页面方案定义,保存后发布才会对外展示。", page, target: "brand" as const, fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page), })), ...(templateContent?.admin.sections ?? []), ].map((section) => ({ ...section, fields: section.fields.filter( (field) => field.binding.startsWith("brand.config.") || (standardBrandBindings as readonly string[]).includes(field.binding), ), })); }, [templateContent]); } export function useBrandPresentationForm({ brand, config, sections, }: { brand: BrandProfile; config: Record | null | undefined; sections: TemplateAdminSection[]; }): BrandPresentationFormState { const [form] = Form.useForm(); const initialValues = useMemo(() => { const values: PresentationValues = {}; for (const section of sections) { for (const field of section.fields) { values[presentationFieldName(section.key, field.key)] = readPresentationValue( config, field.binding, field, brand as unknown as Record, ); } } return values; }, [brand, config, sections]); return { form, initialValues }; } interface BrandSaveMutationOptions extends BrandPresentationFormState { brand: BrandProfile; config: Record | null | undefined; sections: TemplateAdminSection[]; queryClient: QueryClient; onSaved: () => void; } export function useBrandSaveMutation({ brand, config, sections, queryClient, onSaved, }: BrandSaveMutationOptions) { const { message } = App.useApp(); return useMutation({ mutationFn: (values: PresentationValues) => { const nextConfig = applyPresentationValues(config, sections, values); const standard = applyStandardBrandValues( brand as unknown as Record, sections, values, ); const changed = Object.fromEntries( Object.entries(standard).filter( ([key, value]) => key !== "config" && value !== (brand as unknown as Record)[key], ), ); return createApiClient().updateAdminBrand({ ...changed, config: nextConfig }); }, onSuccess: () => { onSaved(); message.success("页面内容已保存为草稿,发布后小程序才会更新"); window.dispatchEvent(new Event("template-preview-refresh")); void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] }); }, }); } export function useBrandPreviewDraft({ brand, config, sections, form, onDirty, }: { brand: BrandProfile; config: Record | null | undefined; sections: TemplateAdminSection[]; form: BrandPresentationFormState["form"]; onDirty: () => void; }) { const [previewConfig, setPreviewConfig] = useState(config ?? {}); const [previewBrandValues, setPreviewBrandValues] = useState>({}); useEffect(() => { setPreviewConfig(config ?? {}); setPreviewBrandValues({}); }, [config, form]); const handleValuesChange = (changed: PresentationValues, allValues: PresentationValues) => { onDirty(); const synchronized: PresentationValues = { ...getFullFormValues(form), ...allValues, }; for (const section of sections) { for (const field of section.fields) { const name = presentationFieldName(section.key, field.key); if (!Object.prototype.hasOwnProperty.call(changed, name)) continue; for (const peer of sections) { for (const item of peer.fields) { if (item.binding === field.binding) synchronized[presentationFieldName(peer.key, item.key)] = changed[name]; } } } } form.setFieldsValue(synchronized); const next = applyBrandPreviewValues( brand as unknown as Record, config, sections, synchronized, ); setPreviewConfig((next.config as Record) ?? {}); setPreviewBrandValues(next); }; const previewBrand = useMemo( () => ({ ...brand, ...previewBrandValues, config: previewConfig }), [brand, previewBrandValues, previewConfig], ); const resetPreview = useCallback(() => { setPreviewConfig(config ?? {}); setPreviewBrandValues({}); }, [config]); return { previewBrand, handleValuesChange, resetPreview, }; } export function usePresentationRecordQueries( source: "offering" | "trust" | undefined, recordId: string | undefined, ) { const offeringsQuery = useQuery({ queryKey: ["admin-offerings"], queryFn: () => createApiClient().listAdminOfferings(), enabled: source === "offering", refetchOnMount: "always", }); const trustQuery = useQuery({ queryKey: ["trust-content"], queryFn: () => createApiClient().listAdminTrustContent(), enabled: source === "trust", }); const selectedRecord = source === "offering" ? offeringsQuery.data?.find((item: Offering) => item.id === recordId) : source === "trust" ? trustQuery.data?.find((item: TrustContent) => item.id === recordId) : undefined; return { offeringsQuery, trustQuery, selectedRecord }; }