import { useMemo, useState } from "react"; import { useMutation, useQuery } from "@tanstack/react-query"; import { App, Button, Dropdown, Form, Input, Modal, Popconfirm, Select, Tabs, type FormInstance } from "antd"; import { Box, Check, ChevronDown, FileText, Image as ImageIcon, Link2, Music2, Plus, RefreshCw, Sparkles, Trash2, UserRound, Video, VolumeX } from "lucide-react"; import { WorkspaceState } from "@/components/layout/workspace-state"; import { WorkspaceSignalIcon } from "@/components/ui/aceternity/workspace-signal-icon"; import { resourceFileUrl, resourceIdFromStorageKey } from "@/services/api/resources"; import { bindProjectCharacterVoice, confirmProjectAssetCandidate, createProjectAssetVersion, createProjectCharacter, linkProjectAsset, listVoiceProfiles, replaceProjectCharacterRepresentations, unbindProjectCharacterVoice, unlinkProjectAsset, updateProjectAssetCategory, updateProjectCharacter, type ProjectAsset, } from "@/services/api/projects"; import { saveRemoteUserDataNow } from "@/services/user-data-sync"; import { useAssetStore, type Asset, type AssetCategory, type AssetStatus, type EntityAsset, type ImageAsset } from "@/stores/use-asset-store"; import { useConfigStore, useEffectiveConfig } from "@/stores/use-config-store"; import { ProjectCharacterCard } from "./project-character-card"; import { generateCharacterTurnaround } from "./project-character-media"; import { categoryLabels, categoryLabel, mediaLabel, StatusPill, formatTime, type ProjectDetailViewProps } from "./shared"; const categories = ["all", "character", "environment", "wardrobe", "prop", "weapon", "style", "other"]; const characterFields = [ ["role", "剧情定位与人物关系"], ["aliases", "别名"], ["appearance", "稳定外貌"], ["physique", "身高、体型与体态"], ["clothing", "默认服装造型"], ["personality", "性格与表演基线"], ["props", "固定道具"], ["consistencyPrompt", "跨镜头一致性约束"], ["multiViewPrompt", "三视图补充约束"], ["voiceLanguage", "语言与口音"], ["voiceAge", "声音年龄感"], ["voiceTimbre", "音色气质"], ] as const; type CharacterForm = { name: string } & Record<(typeof characterFields)[number][0], string>; export default function ProjectAssetsView({ detail, refreshProject }: ProjectDetailViewProps) { const { message } = App.useApp(); const personalAssets = useAssetStore((state) => state.assets); const updatePersonalAsset = useAssetStore((state) => state.updateAsset); const effectiveConfig = useEffectiveConfig(); const isAiConfigReady = useConfigStore((state) => state.isAiConfigReady); const [category, setCategory] = useState("all"); const [addOpen, setAddOpen] = useState(false); const [assetId, setAssetId] = useState(""); const [assetCategory, setAssetCategory] = useState("other"); const [editorAsset, setEditorAsset] = useState(null); const [imageAsset, setImageAsset] = useState(null); const [voiceAsset, setVoiceAsset] = useState(null); const [imageSelection, setImageSelection] = useState(""); const [voiceProfileId, setVoiceProfileId] = useState(""); const [voiceInstructions, setVoiceInstructions] = useState(""); const [form] = Form.useForm(); const projectAssetIds = new Set(detail.assets.map((asset) => asset.id)); const availableAssets = personalAssets.filter((asset) => !projectAssetIds.has(asset.id)); const selectedPersonalAsset = personalAssets.find((asset) => asset.id === assetId); const imageAssets = personalAssets.filter((asset): asset is ImageAsset => asset.kind === "image"); const pendingCandidates = detail.assetCandidates.filter((candidate) => candidate.category === "character" && candidate.status === "pending_confirmation"); const characterAssets = detail.assets.filter((asset) => asset.category === "character" && asset.character); const mediaAssetCount = detail.assets.filter((asset) => asset.category !== "character").length; const visibleAssets = useMemo(() => category === "all" ? detail.assets : detail.assets.filter((asset) => asset.category === category), [category, detail.assets]); const categoryCounts = categories.map((value) => ({ value, count: value === "all" ? detail.assets.length : detail.assets.filter((asset) => asset.category === value).length })); const voices = useQuery({ queryKey: ["voice-profiles"], queryFn: listVoiceProfiles, enabled: Boolean(voiceAsset) }); const done = (content: string) => { refreshProject(); message.success(content); }; const failed = (fallback: string) => (error: unknown) => message.error(error instanceof Error ? error.message : fallback); const addMutation = useMutation({ mutationFn: () => linkProjectAsset(detail.project.id, { assetId, category: assetCategory }), onSuccess: ({ asset }) => { updatePersonalAsset(asset.id, { category: asset.category as AssetCategory, status: asset.status as AssetStatus, primaryVersionId: asset.primaryVersionId }); setAddOpen(false); setAssetId(""); done("资产已加入项目"); }, onError: failed("资产加入失败") }); const versionMutation = useMutation({ mutationFn: (id: string) => createProjectAssetVersion(detail.project.id, id, {}), onSuccess: () => done("已创建新版本"), onError: failed("版本创建失败") }); const unlinkMutation = useMutation({ mutationFn: (id: string) => unlinkProjectAsset(detail.project.id, id), onSuccess: () => done("资产已移出项目"), onError: failed("资产移除失败") }); const categoryMutation = useMutation({ mutationFn: ({ id, next }: { id: string; next: string }) => updateProjectAssetCategory(detail.project.id, id, next), onSuccess: ({ asset }) => { updatePersonalAsset(asset.id, { category: asset.category as AssetCategory }); done("资产分类已更新"); }, onError: failed("资产分类更新失败") }); const confirmMutation = useMutation({ mutationFn: ({ candidateId, targetAssetId }: { candidateId: string; targetAssetId?: string }) => confirmProjectAssetCandidate(detail.project.id, candidateId, targetAssetId), onSuccess: ({ asset }, variables) => { syncPersonalCharacterProjection(asset); done(variables.targetAssetId ? "候选信息已归并到角色新版本" : "角色卡已创建"); }, onError: failed("角色确认失败"), }); const saveCharacter = useMutation({ mutationFn: async (values: CharacterForm) => { const definition = characterDefinition(values); return editorAsset === "new" ? createProjectCharacter(detail.project.id, { name: values.name, definition }) : updateProjectCharacter(detail.project.id, editorAsset!.id, { name: values.name, definition }); }, onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setEditorAsset(null); done(editorAsset === "new" ? "角色卡已创建" : "角色设定已保存并生成新版本"); }, onError: failed("角色保存失败"), }); const generateMutation = useMutation({ mutationFn: async (asset: ProjectAsset) => { if (!asset.character) throw new Error("角色版本信息不完整"); const model = effectiveConfig.imageModel || effectiveConfig.model; const config = { ...effectiveConfig, model }; if (!isAiConfigReady(config, model)) throw new Error("请先在设置中配置可用的图片模型"); const representations = await generateCharacterTurnaround({ projectId: detail.project.id, assetId: asset.id, versionId: asset.character.versionId, name: asset.title, definition: asset.character.definition, config }); return replaceProjectCharacterRepresentations(detail.project.id, asset.id, representations); }, onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); done("三视图已生成并绑定到新角色版本"); }, onError: failed("三视图生成失败"), }); const bindImagesMutation = useMutation({ mutationFn: async () => { if (!imageAsset) throw new Error("未选择角色"); await saveRemoteUserDataNow(); const latest = useAssetStore.getState().assets; const selected = latest.find((asset) => asset.id === imageSelection); if (selected?.kind !== "image") throw new Error("请选择一张包含正面、侧面和背面的三视图设定图"); const resourceId = resourceIdFromStorageKey((selected as ImageAsset).data.storageKey); if (!resourceId) throw new Error("所选图片尚未同步到后端资源库"); return replaceProjectCharacterRepresentations(detail.project.id, imageAsset.id, [{ role: "turnaround_sheet", resourceId, metadata: { sourceAssetId: selected.id } }, { role: "primary", resourceId, metadata: { source: "turnaround_sheet", sourceAssetId: selected.id } }]); }, onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setImageAsset(null); done("三视图已绑定到新角色版本"); }, onError: failed("三视图绑定失败"), }); const bindVoiceMutation = useMutation({ mutationFn: () => voiceAsset ? bindProjectCharacterVoice(detail.project.id, voiceAsset.id, { voiceProfileId, instructions: voiceInstructions }) : Promise.reject(new Error("未选择角色")), onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setVoiceAsset(null); done("声音素材已绑定到新角色版本"); }, onError: failed("声音绑定失败") }); const unbindVoiceMutation = useMutation({ mutationFn: () => voiceAsset ? unbindProjectCharacterVoice(detail.project.id, voiceAsset.id) : Promise.reject(new Error("未选择角色")), onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setVoiceAsset(null); done("声音绑定已解除并生成新角色版本"); }, onError: failed("声音解绑失败") }); const openCharacterEditor = (asset: ProjectAsset | "new") => { setEditorAsset(asset); const definition = asset === "new" ? {} : asset.character?.definition || {}; form.setFieldsValue({ name: asset === "new" ? "" : asset.title, ...Object.fromEntries(characterFields.map(([key]) => [key, fieldValue(definition[key])])) } as CharacterForm); }; const openImages = (asset: ProjectAsset) => { setImageAsset(asset); setImageSelection(""); }; const openVoice = (asset: ProjectAsset) => { setVoiceAsset(asset); setVoiceProfileId(asset.character?.voice?.profile.id || ""); setVoiceInstructions(asset.character?.voice?.instructions || ""); }; return (

角色与资产

{detail.assets.length} 项
{characterAssets.length} 个角色 {mediaAssetCount} 项媒体 {pendingCandidates.length ? {pendingCandidates.length} 个待确认 : null}
{(category === "all" || category === "character") && pendingCandidates.length ?
剧情识别出的角色
{pendingCandidates.map((candidate) =>
{candidate.name}
待确认角色卡 · 来自章节分析
{characterAssets.length ? ({ key: asset.id, label: asset.title })), onClick: ({ key }) => confirmMutation.mutate({ candidateId: candidate.id, targetAssetId: key }) }}> : null}
)}
: null}
{category === "all" ? "全部资产" : categoryLabel(category)}{visibleAssets.length} 项
{visibleAssets.length ?
{visibleAssets.map((asset) => asset.category === "character" ? openCharacterEditor(asset)} onGenerate={() => generateMutation.mutate(asset)} onBindImages={() => openImages(asset)} onBindVoice={() => openVoice(asset)} onRemove={() => unlinkMutation.mutate(asset.id)} /> : item.id === asset.id)} onCategoryChange={(next) => categoryMutation.mutate({ id: asset.id, next })} onVersion={() => versionMutation.mutate(asset.id)} onRemove={() => unlinkMutation.mutate(asset.id)} loading={(categoryMutation.isPending && categoryMutation.variables?.id === asset.id) || (versionMutation.isPending && versionMutation.variables === asset.id) || (unlinkMutation.isPending && unlinkMutation.variables === asset.id)} />)}
: }
setAddOpen(false)} onOk={() => addMutation.mutate()} width={480}>
value !== "character").map(([value, label]) => ({ value, label }))} onChange={setAssetCategory} />
setEditorAsset(null)} onSave={() => form.validateFields().then((values) => saveCharacter.mutate(values))} /> setImageAsset(null)} onOk={() => bindImagesMutation.mutate()}>{imageAssets.length ?
{imageAssets.map((asset) => )}
: }
setVoiceAsset(null)} onOk={() => bindVoiceMutation.mutate()}>
; return
角色设定

{editing ? "调整角色设定" : "建立一张角色卡"}

{input("role")}{input("aliases")}{textArea("appearance", 4)}{input("physique")}{input("clothing")}{input("props")}{textArea("consistencyPrompt", 4)}{textArea("multiViewPrompt", 3)}
}, { key: "performance", label: "表演与声音", forceRender: true, children:
{textArea("personality", 4)}{input("voiceLanguage")}{input("voiceAge")}{input("voiceTimbre")}
}]} />
; } type CharacterFormKey = (typeof characterFields)[number][0]; function MediaAssetCard({ asset, personalAsset, onCategoryChange, onVersion, onRemove, loading }: { asset: ProjectAsset; personalAsset?: Asset; onCategoryChange: (category: string) => void; onVersion: () => void; onRemove: () => void; loading: boolean }) { const cover = personalAsset ? assetCover(personalAsset) : ""; return
{cover ? {asset.title} :
}
{mediaLabel(asset.mediaType)}

{asset.title}

value !== "character").map(([value, label]) => ({ key: value, label })), onClick: ({ key }) => onCategoryChange(key) }}>·v{Math.max(1, asset.versionCount)}
{formatTime(asset.updatedAt)}
; } function characterDefinition(values: CharacterForm) { const definition: Record = Object.fromEntries(characterFields.map(([key]) => [key, values[key]?.trim() || (key === "aliases" ? [] : "")])); definition.aliases = values.aliases?.split(/[,,]/).map((item) => item.trim()).filter(Boolean) || []; return definition; } function fieldValue(value: unknown) { return Array.isArray(value) ? value.join(",") : typeof value === "string" ? value : ""; } function syncPersonalCharacterProjection(asset: ProjectAsset) { if (!asset.character) return; const current = useAssetStore.getState().assets; const existing = current.find((item) => item.id === asset.id); const cover = asset.character.representations.find((item) => item.role === "turnaround_sheet") || asset.character.representations.find((item) => item.role === "primary") || asset.character.representations.find((item) => item.role === "front"); const projected: EntityAsset = { id: asset.id, kind: "entity", title: asset.title, coverUrl: cover ? resourceFileUrl(cover.resourceId) : existing?.coverUrl || "", tags: existing?.tags || [], category: "character", status: asset.status as AssetStatus, primaryVersionId: asset.primaryVersionId, source: existing?.source || "project-character", createdAt: existing?.createdAt || asset.updatedAt, updatedAt: asset.updatedAt, data: { definition: asset.character.definition }, }; useAssetStore.getState().replaceAssets([projected, ...current.filter((item) => item.id !== asset.id)]); } function assetCover(asset: Asset) { if (asset.coverUrl) return asset.coverUrl; if (asset.kind === "image") return asset.data.dataUrl; if (asset.kind === "video") return asset.data.url; return ""; } function MediaIcon({ kind }: { kind: string }) { if (kind === "image") return ; if (kind === "video") return