other.js 324 KB
Newer Older
LiangLiu's avatar
LiangLiu committed
1
2
3
4
5
6
7
8
9
10
11
12
import { ref, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import i18n from './i18n'
import router from '../router'
export const t = i18n.global.t
export const locale = i18n.global.locale

        // 响应式数据
        const loading = ref(false);
        const loginLoading = ref(false);
        const initLoading = ref(false);
        const downloadLoading = ref(false);
LiangLiu's avatar
LiangLiu committed
13
        const downloadLoadingMessage = ref('');
LiangLiu's avatar
LiangLiu committed
14
        const isLoading = ref(false); // 页面加载loading状态
LiangLiu's avatar
LiangLiu committed
15
        const isPageLoading = ref(false); // 分页加载loading状态
LiangLiu's avatar
LiangLiu committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

        // 录音相关状态
        const isRecording = ref(false);
        const mediaRecorder = ref(null);
        const audioChunks = ref([]);
        const recordingDuration = ref(0);
        const recordingTimer = ref(null);
        const alert = ref({ show: false, message: '', type: 'info' });


        // 短信登录相关数据
        const phoneNumber = ref('');
        const verifyCode = ref('');
        const smsCountdown = ref(0);
        const showSmsForm = ref(false);
        const showErrorDetails = ref(false);
        const showFailureDetails = ref(false);

        // 任务类型下拉菜单
        const showTaskTypeMenu = ref(false);
        const showModelMenu = ref(false);

        // 任务状态轮询相关
        const pollingInterval = ref(null);
        const pollingTasks = ref(new Set()); // 正在轮询的任务ID集合
        const confirmDialog = ref({
            show: false,
            title: '',
            message: '',
            confirmText: '确认', // 使用静态文本,避免翻译依赖
            warning: null,
            confirm: () => { }
        });
        const submitting = ref(false);
LiangLiu's avatar
LiangLiu committed
50
51
        const templateLoading = ref(false); // 模板/任务复用加载状态
        const templateLoadingMessage = ref('');
LiangLiu's avatar
LiangLiu committed
52
53
54
55
56
57
58
59
        const taskSearchQuery = ref('');
        const sidebarCollapsed = ref(false);
        const showExpandHint = ref(false);
        const showGlow = ref(false);
        const isDefaultStateHidden = ref(false);
        const isCreationAreaExpanded = ref(false);
        const hasUploadedContent = ref(false);
        const isContracting = ref(false);
60
61
        const faceDetecting = ref(false);  // Face detection loading state
        const audioSeparating = ref(false);  // Audio separation loading state
LiangLiu's avatar
LiangLiu committed
62
63
64
65
66
67

        const showTaskDetailModal = ref(false);
        const modalTask = ref(null);

        // TTS 模态框状态
        const showVoiceTTSModal = ref(false);
68
        const showPodcastModal = ref(false);
LiangLiu's avatar
LiangLiu committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

        // TaskCarousel当前任务状态
        const currentTask = ref(null);

        // 视频加载状态跟踪
        const videoLoadedStates = ref(new Map()); // 跟踪每个视频的加载状态

        // 检查视频是否已加载完成
        const isVideoLoaded = (videoSrc) => {
            return videoLoadedStates.value.get(videoSrc) || false;
        };

        // 设置视频加载状态
        const setVideoLoaded = (videoSrc, loaded) => {
            videoLoadedStates.value.set(videoSrc, loaded);
        };

        // 灵感广场相关数据
        const inspirationSearchQuery = ref('');
        const selectedInspirationCategory = ref('');
        const inspirationItems = ref([]);
        const InspirationCategories = ref([]);

        // 灵感广场分页相关变量
        const inspirationPagination = ref(null);
        const inspirationCurrentPage = ref(1);
95
        const inspirationPageSize = ref(20);
LiangLiu's avatar
LiangLiu committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
        const inspirationPageInput = ref(1);
        const inspirationPaginationKey = ref(0);

        // 模板详情弹窗相关数据
        const showTemplateDetailModal = ref(false);
        const selectedTemplate = ref(null);

        // 图片放大弹窗相关数据
        const showImageZoomModal = ref(false);
        const zoomedImageUrl = ref('');

        // 任务文件缓存系统
        const taskFileCache = ref(new Map());
        const taskFileCacheLoaded = ref(false);

        // 模板文件缓存系统
        const templateFileCache = ref(new Map());
        const templateFileCacheLoaded = ref(false);

115
116
117
118
        // Podcast 音频 URL 缓存系统(模仿任务文件缓存)
        const podcastAudioCache = ref(new Map());
        const podcastAudioCacheLoaded = ref(false);

LiangLiu's avatar
LiangLiu committed
119
120
121
122
123
124
125
        // 防重复获取的状态管理
        const templateUrlFetching = ref(new Set()); // 正在获取的URL集合
        const taskUrlFetching = ref(new Map()); // 正在获取的任务URL集合

        // localStorage缓存相关常量
        const TASK_FILE_CACHE_KEY = 'lightx2v_task_files';
        const TEMPLATE_FILE_CACHE_KEY = 'lightx2v_template_files';
126
        const PODCAST_AUDIO_CACHE_KEY = 'lightx2v_podcast_audio';
LiangLiu's avatar
LiangLiu committed
127
        const TASK_FILE_CACHE_EXPIRY = 24 * 60 * 60 * 1000; // 24小时过期
128
        const PODCAST_AUDIO_CACHE_EXPIRY = 24 * 60 * 60 * 1000; // 24小时过期
LiangLiu's avatar
LiangLiu committed
129
130
131
132
133
134
135
136
137
        const MODELS_CACHE_KEY = 'lightx2v_models';
        const MODELS_CACHE_EXPIRY = 60 * 60 * 1000; // 1小时过期
        const TEMPLATES_CACHE_KEY = 'lightx2v_templates';
        const TEMPLATES_CACHE_EXPIRY = 24 * 60 * 60 * 1000; // 24小时过期
        const TASKS_CACHE_KEY = 'lightx2v_tasks';
        const TASKS_CACHE_EXPIRY = 5 * 60 * 1000; // 5分钟过期

        const imageTemplates = ref([]);
        const audioTemplates = ref([]);
138
        const mergedTemplates = ref([]);  // 合并后的模板列表
LiangLiu's avatar
LiangLiu committed
139
140
141
142
143
144
145
        const showImageTemplates = ref(false);
        const showAudioTemplates = ref(false);
        const mediaModalTab = ref('history');

        // Template分页相关变量
        const templatePagination = ref(null);
        const templateCurrentPage = ref(1);
146
        const templatePageSize = ref(20); // 图片模板每页12个,音频模板每页10个
LiangLiu's avatar
LiangLiu committed
147
148
149
150
        const templatePageInput = ref(1);
        const templatePaginationKey = ref(0);
        const imageHistory = ref([]);
        const audioHistory = ref([]);
LiangLiu's avatar
LiangLiu committed
151
        const ttsHistory = ref([]);
LiangLiu's avatar
LiangLiu committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

        // 模板文件缓存,避免重复下载
        const currentUser = ref({});
        const models = ref([]);
        const tasks = ref([]);
        const isLoggedIn = ref(null); // null表示未初始化,false表示未登录,true表示已登录

        const selectedTaskId = ref(null);
        const selectedTask = ref(null);
        const selectedModel = ref(null);
        const selectedTaskFiles = ref({ inputs: {}, outputs: {} }); // 存储任务的输入输出文件
        const loadingTaskFiles = ref(false); // 加载任务文件的状态
        const statusFilter = ref('ALL');
        const pagination = ref(null);
        const currentTaskPage = ref(1);
167
        const taskPageSize = ref(20);
LiangLiu's avatar
LiangLiu committed
168
169
170
171
172
173
        const taskPageInput = ref(1);
        const paginationKey = ref(0); // 用于强制刷新分页组件
        const taskMenuVisible = ref({}); // 管理每个任务的菜单显示状态
        const nameMap = computed(() => ({
            't2v': t('textToVideo'),
            'i2v': t('imageToVideo'),
174
175
            's2v': t('speechToVideo'),
            'animate': t('animate')
LiangLiu's avatar
LiangLiu committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
        }));

        // 任务类型提示信息
        const taskHints = computed(() => ({
            't2v': [
                t('t2vHint1'),
                t('t2vHint2'),
                t('t2vHint3'),
                t('t2vHint4')
            ],
            'i2v': [
                t('i2vHint1'),
                t('i2vHint2'),
                t('i2vHint3'),
                t('i2vHint4')
            ],
            's2v': [
                t('s2vHint1'),
                t('s2vHint2'),
                t('s2vHint3'),
                t('s2vHint4')
197
198
199
200
201
            ],
            'animate': [
                t('animateHint1') || '上传目标角色图片和参考视频',
                t('animateHint2') || '将视频中的角色替换为目标角色',
                ]
LiangLiu's avatar
LiangLiu committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
        }));

        // 当前任务类型的提示信息
        const currentTaskHints = computed(() => {
            return taskHints.value[selectedTaskId.value] || taskHints.value['s2v'];
        });

        // 滚动提示相关
        const currentHintIndex = ref(0);
        const hintInterval = ref(null);

        // 开始滚动提示
        const startHintRotation = () => {
            if (hintInterval.value) {
                clearInterval(hintInterval.value);
            }
            hintInterval.value = setInterval(() => {
                currentHintIndex.value = (currentHintIndex.value + 1) % currentTaskHints.value.length;
            }, 3000); // 每3秒切换一次
        };

        // 停止滚动提示
        const stopHintRotation = () => {
            if (hintInterval.value) {
                clearInterval(hintInterval.value);
                hintInterval.value = null;
            }
        };

        // 为三个任务类型分别创建独立的表单
        const t2vForm = ref({
            task: 't2v',
            model_cls: '',
235
            stage: '',
LiangLiu's avatar
LiangLiu committed
236
237
238
239
240
241
242
            prompt: '',
            seed: 42
        });

        const i2vForm = ref({
            task: 'i2v',
            model_cls: '',
243
            stage: '',
LiangLiu's avatar
LiangLiu committed
244
245
            imageFile: null,
            prompt: '',
246
247
            seed: 42,
            detectedFaces: []  // List of detected faces: [{ index, bbox, face_image, roleName, ... }]
LiangLiu's avatar
LiangLiu committed
248
249
250
251
252
        });

        const s2vForm = ref({
            task: 's2v',
            model_cls: '',
253
            stage: '',
LiangLiu's avatar
LiangLiu committed
254
255
256
            imageFile: null,
            audioFile: null,
            prompt: '',
257
258
259
260
261
262
263
264
265
266
267
268
269
270
            seed: 42,
            detectedFaces: [],  // List of detected faces: [{ index, bbox, face_image, roleName, ... }]
            separatedAudios: []  // List of separated audio tracks: [{ speaker_id, audio (base64), roleName, ... }]
        });

        const animateForm = ref({
            task: 'animate',
            model_cls: '',
            stage: '',
            imageFile: null,
            videoFile: null,
            prompt: '视频中的人在做动作',
            seed: 42,
            detectedFaces: []  // List of detected faces: [{ index, bbox, face_image, roleName, ... }]
LiangLiu's avatar
LiangLiu committed
271
272
273
274
275
276
277
278
279
280
281
        });

        // 根据当前选择的任务类型获取对应的表单
        const getCurrentForm = () => {
            switch (selectedTaskId.value) {
                case 't2v':
                    return t2vForm.value;
                case 'i2v':
                    return i2vForm.value;
                case 's2v':
                    return s2vForm.value;
282
283
                case 'animate':
                    return animateForm.value;
LiangLiu's avatar
LiangLiu committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
                default:
                    return t2vForm.value;
            }
        };

        // 控制默认状态显示/隐藏的方法
        const hideDefaultState = () => {
            isDefaultStateHidden.value = true;
        };

        const showDefaultState = () => {
            isDefaultStateHidden.value = false;
        };

        // 控制创作区域展开/收缩的方法
        const expandCreationArea = () => {
            isCreationAreaExpanded.value = true;
            // 添加show类来触发动画
            setTimeout(() => {
                const creationArea = document.querySelector('.creation-area');
                if (creationArea) {
                    creationArea.classList.add('show');
                }
            }, 10);
        };

        const contractCreationArea = () => {
            isContracting.value = true;
            const creationArea = document.querySelector('.creation-area');
            if (creationArea) {
                // 添加hide类来触发收起动画
                creationArea.classList.add('hide');
                creationArea.classList.remove('show');
            }
            // 等待动画完成后更新状态
            setTimeout(() => {
                isCreationAreaExpanded.value = false;
                isContracting.value = false;
                if (creationArea) {
                    creationArea.classList.remove('hide');
                }
            }, 400);
        };

        // 为每个任务类型创建独立的预览变量
        const i2vImagePreview = ref(null);
        const s2vImagePreview = ref(null);
        const s2vAudioPreview = ref(null);
332
333
        const animateImagePreview = ref(null);
        const animateVideoPreview = ref(null);
LiangLiu's avatar
LiangLiu committed
334
335
336

        // 监听上传内容变化
        const updateUploadedContentStatus = () => {
337
            hasUploadedContent.value = !!(getCurrentImagePreview() || getCurrentAudioPreview() || getCurrentVideoPreview() || getCurrentForm().prompt?.trim());
LiangLiu's avatar
LiangLiu committed
338
339
340
        };

        // 监听表单变化
341
        watch([i2vImagePreview, s2vImagePreview, s2vAudioPreview, animateImagePreview, animateVideoPreview, () => getCurrentForm().prompt], () => {
LiangLiu's avatar
LiangLiu committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
            updateUploadedContentStatus();
        }, { deep: true });

        // 监听任务类型变化,重置提示滚动
        watch(selectedTaskId, () => {
            currentHintIndex.value = 0;
            stopHintRotation();
            startHintRotation();
        });

        // 根据当前任务类型获取对应的预览变量
        const getCurrentImagePreview = () => {
            switch (selectedTaskId.value) {
                case 't2v':
                    return null;
                case 'i2v':
                    return i2vImagePreview.value;
                case 's2v':
                    return s2vImagePreview.value;
361
362
                case 'animate':
                    return animateImagePreview.value;
LiangLiu's avatar
LiangLiu committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
                default:
                    return null;
            }
        };

        const getCurrentAudioPreview = () => {
            switch (selectedTaskId.value) {
                case 't2v':
                    return null
                case 'i2v':
                    return null
                case 's2v':
                    return s2vAudioPreview.value;
                default:
                    return null;
            }
        };

        const setCurrentImagePreview = (value) => {
            switch (selectedTaskId.value) {
                case 't2v':
                    break;
                case 'i2v':
                    i2vImagePreview.value = value;
                    break;
                case 's2v':
                    s2vImagePreview.value = value;
                    break;
391
392
393
                case 'animate':
                    animateImagePreview.value = value;
                    break;
LiangLiu's avatar
LiangLiu committed
394
395
396
397
398
399
400
401
402
403
404
            }
            // 清除图片预览缓存,确保新图片能正确显示
            urlCache.value.delete('current_image_preview');
        };

        const setCurrentAudioPreview = (value) => {
            switch (selectedTaskId.value) {
                case 't2v':
                    break;
                case 'i2v':
                    break;
405
406
                case 'animate':
                    break;
LiangLiu's avatar
LiangLiu committed
407
408
409
410
411
412
413
414
                case 's2v':
                    s2vAudioPreview.value = value;
                    break;
            }
            // 清除音频预览缓存,确保新音频能正确显示
            urlCache.value.delete('current_audio_preview');
        };

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        // 获取当前任务类型的视频预览
        const getCurrentVideoPreview = () => {
            switch (selectedTaskId.value) {
                case 'animate':
                    return animateVideoPreview.value;
                default:
                    return null;
            }
        };

        // 设置当前任务类型的视频预览
        const setCurrentVideoPreview = (value) => {
            switch (selectedTaskId.value) {
                case 'animate':
                    animateVideoPreview.value = value;
                    break;
            }
            // 清除视频预览缓存,确保新视频能正确显示
            urlCache.value.delete('current_video_preview');
        };

LiangLiu's avatar
LiangLiu committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
        // 提示词模板相关
        const showTemplates = ref(false);
        const showHistory = ref(false);
        const showPromptModal = ref(false);
        const promptModalTab = ref('templates');

        // 计算属性
        const availableTaskTypes = computed(() => {
            const types = [...new Set(models.value.map(m => m.task))];
            // 重新排序,确保数字人在最左边
            const orderedTypes = [];

            // 检查是否有s2v模型,如果有则添加s2v类型
            const hasS2vModels = models.value.some(m =>
                m.task === 's2v'
            );

            // 优先添加数字人(如果存在相关模型)
            if (hasS2vModels) {
                orderedTypes.push('s2v');
            }
LiangLiu's avatar
LiangLiu committed
457

LiangLiu's avatar
LiangLiu committed
458
459
460
461
462
            // 然后添加其他类型
            types.forEach(type => {
                if (type !== 's2v') {
                    orderedTypes.push(type);
                }
LiangLiu's avatar
LiangLiu committed
463
464
            });

LiangLiu's avatar
LiangLiu committed
465
466
            return orderedTypes;
        });
LiangLiu's avatar
LiangLiu committed
467

LiangLiu's avatar
LiangLiu committed
468
469
        const availableModelClasses = computed(() => {
            if (!selectedTaskId.value) return [];
LiangLiu's avatar
LiangLiu committed
470

LiangLiu's avatar
LiangLiu committed
471
472
473
474
            return [...new Set(models.value
                .filter(m => m.task === selectedTaskId.value)
                .map(m => m.model_cls))];
        });
LiangLiu's avatar
LiangLiu committed
475

LiangLiu's avatar
LiangLiu committed
476
477
        const filteredTasks = computed(() => {
            let filtered = tasks.value;
LiangLiu's avatar
LiangLiu committed
478

LiangLiu's avatar
LiangLiu committed
479
480
481
482
            // 状态过滤
            if (statusFilter.value !== 'ALL') {
                filtered = filtered.filter(task => task.status === statusFilter.value);
            }
LiangLiu's avatar
LiangLiu committed
483

LiangLiu's avatar
LiangLiu committed
484
485
486
487
488
489
490
491
            // 搜索过滤
            if (taskSearchQuery.value) {
                filtered = filtered.filter(task =>
                task.params.prompt?.toLowerCase().includes(taskSearchQuery.value.toLowerCase()) ||
                task.task_id.toLowerCase().includes(taskSearchQuery.value.toLowerCase()) ||
                    nameMap.value[task.task_type].toLowerCase().includes(taskSearchQuery.value.toLowerCase())
            );
            }
LiangLiu's avatar
LiangLiu committed
492

LiangLiu's avatar
LiangLiu committed
493
494
495
496
497
            // 按时间排序,最新的任务在前面
            filtered = filtered.sort((a, b) => {
                const timeA = parseInt(a.create_t) || 0;
                const timeB = parseInt(b.create_t) || 0;
                return timeB - timeA; // 降序排列,最新的在前
LiangLiu's avatar
LiangLiu committed
498
499
            });

LiangLiu's avatar
LiangLiu committed
500
501
            return filtered;
        });
LiangLiu's avatar
LiangLiu committed
502

LiangLiu's avatar
LiangLiu committed
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
        // 监听状态筛选变化,重置分页到第一页
        watch(statusFilter, (newStatus, oldStatus) => {
            if (newStatus !== oldStatus) {
                currentTaskPage.value = 1;
                taskPageInput.value = 1;
                refreshTasks(true); // 强制刷新
            }
        });

        // 监听搜索查询变化,重置分页到第一页
        watch(taskSearchQuery, (newQuery, oldQuery) => {
            if (newQuery !== oldQuery) {
                currentTaskPage.value = 1;
                taskPageInput.value = 1;
                refreshTasks(true); // 强制刷新
            }
        });
LiangLiu's avatar
LiangLiu committed
520

LiangLiu's avatar
LiangLiu committed
521
522
523
        // 分页信息计算属性,确保响应式更新
        const paginationInfo = computed(() => {
            if (!pagination.value) return null;
LiangLiu's avatar
LiangLiu committed
524

LiangLiu's avatar
LiangLiu committed
525
526
527
528
529
            return {
                total: pagination.value.total || 0,
                total_pages: pagination.value.total_pages || 0,
                current_page: pagination.value.current_page || currentTaskPage.value,
                page_size: pagination.value.page_size || taskPageSize.value
LiangLiu's avatar
LiangLiu committed
530
            };
LiangLiu's avatar
LiangLiu committed
531
532
533
534
535
        });

        // Template分页信息计算属性
        const templatePaginationInfo = computed(() => {
            if (!templatePagination.value) return null;
LiangLiu's avatar
LiangLiu committed
536

LiangLiu's avatar
LiangLiu committed
537
538
539
540
541
            return {
                total: templatePagination.value.total || 0,
                total_pages: templatePagination.value.total_pages || 0,
                current_page: templatePagination.value.current_page || templateCurrentPage.value,
                page_size: templatePagination.value.page_size || templatePageSize.value
LiangLiu's avatar
LiangLiu committed
542
            };
LiangLiu's avatar
LiangLiu committed
543
        });
LiangLiu's avatar
LiangLiu committed
544

LiangLiu's avatar
LiangLiu committed
545
546
547
548
549
550
551
552
553
        // 灵感广场分页信息计算属性
        const inspirationPaginationInfo = computed(() => {
            if (!inspirationPagination.value) return null;

            return {
                total: inspirationPagination.value.total || 0,
                total_pages: inspirationPagination.value.total_pages || 0,
                current_page: inspirationPagination.value.current_page || inspirationCurrentPage.value,
                page_size: inspirationPagination.value.page_size || inspirationPageSize.value
LiangLiu's avatar
LiangLiu committed
554
            };
LiangLiu's avatar
LiangLiu committed
555
        });
LiangLiu's avatar
LiangLiu committed
556

LiangLiu's avatar
LiangLiu committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597

        // 通用URL缓存
        const urlCache = ref(new Map());

        // 通用URL缓存函数
        const getCachedUrl = (key, urlGenerator) => {
            if (urlCache.value.has(key)) {
                return urlCache.value.get(key);
            }

            const url = urlGenerator();
            urlCache.value.set(key, url);
            return url;
        };

        // 获取历史图片URL(带缓存)
        const getHistoryImageUrl = (history) => {
            if (!history || !history.thumbnail) return '';
            return getCachedUrl(`history_image_${history.filename}`, () => history.thumbnail);
        };

        // 获取用户头像URL(带缓存)
        const getUserAvatarUrl = (user) => {
            if (!user || !user.avatar) return '';
            return getCachedUrl(`user_avatar_${user.username}`, () => user.avatar);
        };

        // 获取当前图片预览URL(带缓存)
        const getCurrentImagePreviewUrl = () => {
            const preview = getCurrentImagePreview();
            if (!preview) return '';
            return getCachedUrl(`current_image_preview`, () => preview);
        };

        // 获取当前音频预览URL(带缓存)
        const getCurrentAudioPreviewUrl = () => {
            const preview = getCurrentAudioPreview();
            if (!preview) return '';
            return getCachedUrl(`current_audio_preview`, () => preview);
        };

598
599
600
601
602
603
        const getCurrentVideoPreviewUrl = () => {
            const preview = getCurrentVideoPreview();
            if (!preview) return '';
            return getCachedUrl(`current_video_preview`, () => preview);
        };

LiangLiu's avatar
LiangLiu committed
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
        // Alert定时器,用于清除之前的定时器
        let alertTimeout = null;

        // 方法
        const showAlert = (message, type = 'info', action = null) => {
            // 清除之前的定时器
            if (alertTimeout) {
                clearTimeout(alertTimeout);
                alertTimeout = null;
            }

            // 如果当前有alert正在显示,先关闭它
            if (alert.value && alert.value.show) {
                alert.value.show = false;
                // 等待transition完成(约400ms)后再显示新的alert
LiangLiu's avatar
LiangLiu committed
619
                setTimeout(() => {
LiangLiu's avatar
LiangLiu committed
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
                    createNewAlert(message, type, action);
                }, 450);
            } else {
                // 如果没有alert在显示,立即创建新的
                // 如果alert存在但已关闭,先重置它以确保状态干净
                if (alert.value && !alert.value.show) {
                    alert.value = { show: false, message: '', type: 'info', action: null };
                }
                // 立即创建新alert,不需要等待nextTick
                createNewAlert(message, type, action);
            }
        };

        // 创建新alert的辅助函数
        const createNewAlert = (message, type, action) => {
            // 再次清除定时器,防止重复设置
            if (alertTimeout) {
                clearTimeout(alertTimeout);
                alertTimeout = null;
            }

            // 创建全新的对象,使用时间戳确保每次都是新对象
            const newAlert = {
                show: true,
                message: String(message),
                type: String(type),
                action: action ? {
                    label: String(action.label),
                    onClick: action.onClick
                } : null,
                // 添加一个时间戳确保每次都是新对象,用于key
                _timestamp: Date.now()
            };

            // 直接赋值新对象
            alert.value = newAlert;

            // 设置自动关闭定时器
            alertTimeout = setTimeout(() => {
                if (alert.value && alert.value.show && alert.value._timestamp === newAlert._timestamp) {
                alert.value.show = false;
                }
                alertTimeout = null;
            }, 5000);
        };

        // 显示确认对话框
        const showConfirmDialog = (options) => {
            return new Promise((resolve) => {
                confirmDialog.value = {
                    show: true,
                    title: options.title || '确认操作',
                    message: options.message || '确定要执行此操作吗?',
                    confirmText: options.confirmText || '确认',
                    warning: options.warning || null,
                    confirm: () => {
                        confirmDialog.value.show = false;
                        resolve(true);
                    },
                    cancel: () => {
                        confirmDialog.value.show = false;
                        resolve(false);
LiangLiu's avatar
LiangLiu committed
682
                    }
LiangLiu's avatar
LiangLiu committed
683
684
685
                };
            });
        };
LiangLiu's avatar
LiangLiu committed
686

LiangLiu's avatar
LiangLiu committed
687
688
689
        const setLoading = (value) => {
            loading.value = value;
        };
LiangLiu's avatar
LiangLiu committed
690

LiangLiu's avatar
LiangLiu committed
691
692
693
694
695
        const apiCall = async (endpoint, options = {}) => {
            const url = `${endpoint}`;
            const headers = {
                'Content-Type': 'application/json',
                ...options.headers
LiangLiu's avatar
LiangLiu committed
696
697
            };

LiangLiu's avatar
LiangLiu committed
698
699
700
            if (localStorage.getItem('accessToken')) {
                headers['Authorization'] = `Bearer ${localStorage.getItem('accessToken')}`;
            }
LiangLiu's avatar
LiangLiu committed
701

LiangLiu's avatar
LiangLiu committed
702
703
704
            const response = await fetch(url, {
                ...options,
                headers
LiangLiu's avatar
LiangLiu committed
705
706
            });

LiangLiu's avatar
LiangLiu committed
707
            if (response.status === 401) {
708
                logout(false);
709
                showAlert(t('authFailedPleaseRelogin'), 'warning', {
710
711
712
                    label: t('login'),
                    onClick: login
                });
713
                throw new Error(t('authFailedPleaseRelogin'));
LiangLiu's avatar
LiangLiu committed
714
715
716
717
718
719
            }
            if (response.status === 400) {
                const error = await response.json();
                showAlert(error.message, 'danger');
                throw new Error(error.message);
            }
LiangLiu's avatar
LiangLiu committed
720

LiangLiu's avatar
LiangLiu committed
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
            // 添加50ms延迟,防止触发服务端频率限制
            await new Promise(resolve => setTimeout(resolve, 50));

            return response;
        };

        const loginWithGitHub = async () => {
            try {
                console.log('starting GitHub login')
                const response = await fetch('/auth/login/github');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                localStorage.setItem('loginSource', 'github');
                window.location.href = data.auth_url;
            } catch (error) {
                console.log('GitHub login error:', error);
739
                showAlert(t('getGitHubAuthUrlFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
            }
        };

        const loginWithGoogle = async () => {
            try {
                console.log('starting Google login')
                const response = await fetch('/auth/login/google');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                localStorage.setItem('loginSource', 'google');
                window.location.href = data.auth_url;
            } catch (error) {
                console.error('Google login error:', error);
755
                showAlert(t('getGoogleAuthUrlFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
756
757
            }
        };
LiangLiu's avatar
LiangLiu committed
758

LiangLiu's avatar
LiangLiu committed
759
760
761
        // 发送短信验证码
        const sendSmsCode = async () => {
            if (!phoneNumber.value) {
762
                showAlert(t('pleaseEnterPhoneNumber'), 'warning');
LiangLiu's avatar
LiangLiu committed
763
764
                return;
            }
LiangLiu's avatar
LiangLiu committed
765

LiangLiu's avatar
LiangLiu committed
766
767
768
            // 简单的手机号格式验证
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(phoneNumber.value)) {
769
                showAlert(t('pleaseEnterValidPhoneNumber'), 'warning');
LiangLiu's avatar
LiangLiu committed
770
771
                return;
            }
LiangLiu's avatar
LiangLiu committed
772

LiangLiu's avatar
LiangLiu committed
773
774
775
            try {
                const response = await fetch(`./auth/login/sms?phone_number=${phoneNumber.value}`);
                const data = await response.json();
LiangLiu's avatar
LiangLiu committed
776

LiangLiu's avatar
LiangLiu committed
777
                if (response.ok) {
778
                    showAlert(t('verificationCodeSent'), 'success');
LiangLiu's avatar
LiangLiu committed
779
780
781
                    // 开始倒计时
                    startSmsCountdown();
                } else {
782
                    showAlert(data.message || t('sendVerificationCodeFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
783
784
                }
            } catch (error) {
785
                showAlert(t('sendVerificationCodeFailedRetry'), 'danger');
LiangLiu's avatar
LiangLiu committed
786
787
            }
        };
LiangLiu's avatar
LiangLiu committed
788

LiangLiu's avatar
LiangLiu committed
789
790
791
        // 短信验证码登录
        const loginWithSms = async () => {
            if (!phoneNumber.value || !verifyCode.value) {
792
                showAlert(t('pleaseEnterPhoneAndCode'), 'warning');
LiangLiu's avatar
LiangLiu committed
793
794
                return;
            }
LiangLiu's avatar
LiangLiu committed
795

LiangLiu's avatar
LiangLiu committed
796
797
798
            try {
                const response = await fetch(`./auth/callback/sms?phone_number=${phoneNumber.value}&verify_code=${verifyCode.value}`);
                const data = await response.json();
LiangLiu's avatar
LiangLiu committed
799

LiangLiu's avatar
LiangLiu committed
800
801
                if (response.ok) {
                    localStorage.setItem('accessToken', data.access_token);
802
803
804
                    if (data.refresh_token) {
                        localStorage.setItem('refreshToken', data.refresh_token);
                    }
LiangLiu's avatar
LiangLiu committed
805
806
                    localStorage.setItem('currentUser', JSON.stringify(data.user_info));
                    currentUser.value = data.user_info;
LiangLiu's avatar
LiangLiu committed
807

LiangLiu's avatar
LiangLiu committed
808
809
                    // 登录成功后初始化数据
                    await init();
LiangLiu's avatar
LiangLiu committed
810

LiangLiu's avatar
LiangLiu committed
811
812
813
                    router.push('/generate');
                    console.log('login with sms success');
                    isLoggedIn.value = true;
LiangLiu's avatar
LiangLiu committed
814

815
                    showAlert(t('loginSuccess'), 'success');
LiangLiu's avatar
LiangLiu committed
816
                } else {
817
                    showAlert(data.message || t('verificationCodeErrorOrExpired'), 'danger');
LiangLiu's avatar
LiangLiu committed
818
819
                }
            } catch (error) {
820
                showAlert(t('loginFailedRetry'), 'danger');
LiangLiu's avatar
LiangLiu committed
821
822
823
824
825
826
827
828
829
            }
        };

        // 处理手机号输入框回车键
        const handlePhoneEnter = () => {
            if (phoneNumber.value && !smsCountdown.value) {
                sendSmsCode();
            }
        };
LiangLiu's avatar
LiangLiu committed
830

LiangLiu's avatar
LiangLiu committed
831
832
833
834
835
836
        // 处理验证码输入框回车键
        const handleVerifyCodeEnter = () => {
            if (phoneNumber.value && verifyCode.value) {
                loginWithSms();
            }
        };
LiangLiu's avatar
LiangLiu committed
837

LiangLiu's avatar
LiangLiu committed
838
839
840
841
842
843
844
        // 移动端检测和样式应用
        const applyMobileStyles = () => {
            if (window.innerWidth <= 640) {
                // 为左侧功能区添加移动端样式
                const leftNav = document.querySelector('.relative.w-20.pl-5.flex.flex-col.z-10');
                if (leftNav) {
                    leftNav.classList.add('mobile-bottom-nav');
LiangLiu's avatar
LiangLiu committed
845
846
                }

LiangLiu's avatar
LiangLiu committed
847
848
849
850
                // 为导航按钮容器添加移动端样式
                const navContainer = document.querySelector('.p-2.flex.flex-col.justify-center.h-full');
                if (navContainer) {
                    navContainer.classList.add('mobile-nav-buttons');
LiangLiu's avatar
LiangLiu committed
851
852
                }

LiangLiu's avatar
LiangLiu committed
853
854
855
856
                // 为所有导航按钮添加移动端样式
                const navButtons = document.querySelectorAll('.relative.w-20.pl-5.flex.flex-col.z-10 button');
                navButtons.forEach(btn => {
                    btn.classList.add('mobile-nav-btn');
LiangLiu's avatar
LiangLiu committed
857
858
                });

LiangLiu's avatar
LiangLiu committed
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
                // 为主内容区域添加移动端样式
                const contentAreas = document.querySelectorAll('.flex-1.flex.flex-col.min-h-0');
                contentAreas.forEach(area => {
                    area.classList.add('mobile-content');
                });
            }
        };

        // 短信验证码倒计时
        const startSmsCountdown = () => {
            smsCountdown.value = 60;
            const timer = setInterval(() => {
                smsCountdown.value--;
                if (smsCountdown.value <= 0) {
                    clearInterval(timer);
                }
            }, 1000);
        };

        // 切换短信登录表单显示
        const toggleSmsLogin = () => {
            showSmsForm.value = !showSmsForm.value;
            if (!showSmsForm.value) {
                // 重置表单数据
                phoneNumber.value = '';
                verifyCode.value = '';
                smsCountdown.value = 0;
            }
        };
LiangLiu's avatar
LiangLiu committed
888

LiangLiu's avatar
LiangLiu committed
889
890
891
892
893
894
895
        const handleLoginCallback = async (code, source) => {
            try {
                const response = await fetch(`/auth/callback/${source}?code=${code}`);
                if (response.ok) {
                    const data = await response.json();
                    console.log(data);
                    localStorage.setItem('accessToken', data.access_token);
896
897
898
                    if (data.refresh_token) {
                        localStorage.setItem('refreshToken', data.refresh_token);
                    }
LiangLiu's avatar
LiangLiu committed
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
                    localStorage.setItem('currentUser', JSON.stringify(data.user_info));
                    currentUser.value = data.user_info;
                    isLoggedIn.value = true;

                    // 在进入新页面前显示loading
                    isLoading.value = true;

                    // 登录成功后初始化数据
                    await init();

                    // 检查是否有分享数据需要导入
                    const shareData = localStorage.getItem('shareData');
                    if (shareData) {
                        // 解析分享数据获取shareId
                        try {
                            const parsedShareData = JSON.parse(shareData);
                            const shareId = parsedShareData.share_id || parsedShareData.task_id;
                            if (shareId) {
                                localStorage.removeItem('shareData');
                                // 跳转回分享页面,让createSimilar函数处理数据
                                router.push(`/share/${shareId}`);
                                return;
                            }
                        } catch (error) {
                            console.warn('Failed to parse share data:', error);
                        }
                        localStorage.removeItem('shareData');
                    }

                    // 默认跳转到生成页面
                    router.push('/generate');
                    console.log('login with callback success');

                    // 清除URL中的code参数
                    window.history.replaceState({}, document.title, window.location.pathname);
                } else {
                    const error = await response.json();
936
                    showAlert(`${t('loginFailedRetry')}: ${error.detail}`, 'danger');
LiangLiu's avatar
LiangLiu committed
937
938
                }
            } catch (error) {
939
                showAlert(t('loginError'), 'danger');
LiangLiu's avatar
LiangLiu committed
940
941
942
943
                console.error(error);
            }
        };

944
945
946
        let refreshPromise = null;

        const logout = (showMessage = true) => {
LiangLiu's avatar
LiangLiu committed
947
            localStorage.removeItem('accessToken');
948
            localStorage.removeItem('refreshToken');
LiangLiu's avatar
LiangLiu committed
949
            localStorage.removeItem('currentUser');
950
            refreshPromise = null;
LiangLiu's avatar
LiangLiu committed
951
952
953
954
955
956
957

            clearAllCache();
            switchToLoginView();
            isLoggedIn.value = false;

            models.value = [];
            tasks.value = [];
958
            if (showMessage) {
959
                showAlert(t('loggedOut'), 'info');
960
            }
LiangLiu's avatar
LiangLiu committed
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
        };

        const login = () => {
            switchToLoginView();
            isLoggedIn.value = false;
        };

        const loadModels = async (forceRefresh = false) => {
            try {
                // 如果不是强制更新,先尝试从缓存加载
                if (!forceRefresh) {
                    const cachedModels = loadFromCache(MODELS_CACHE_KEY, MODELS_CACHE_EXPIRY);
                    if (cachedModels) {
                        console.log('成功从缓存加载模型列表');
                        models.value = cachedModels;
                        return;
                        }
LiangLiu's avatar
LiangLiu committed
978
979
                }

LiangLiu's avatar
LiangLiu committed
980
981
982
983
984
985
986
987
988
989
990
991
992
                console.log('开始加载模型列表...');
                const response = await apiRequest('/api/v1/model/list');
                if (response && response.ok) {
                    const data = await response.json();
                    console.log('模型列表数据:', data);
                    const modelsData = data.models || [];
                    models.value = modelsData;

                    // 保存到缓存
                    saveToCache(MODELS_CACHE_KEY, modelsData);
                    console.log('模型列表已缓存');
                } else if (response) {
                    console.error('模型列表API响应失败:', response);
993
                    showAlert(t('loadModelListFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
994
995
996
997
                }
                // 如果response为null,说明是认证错误,apiRequest已经处理了
            } catch (error) {
                console.error('加载模型失败:', error);
998
                showAlert(`${t('loadModelFailed')}: ${error.message}`, 'danger');
LiangLiu's avatar
LiangLiu committed
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
            }
        };

        const refreshTemplateFileUrl = (templatesData) => {
            for (const img of templatesData.images) {
                console.log('刷新图片素材文件URL:', img.filename, img.url);
                setTemplateFileToCache(img.filename, {url: img.url, timestamp: Date.now()});
            }
            for (const audio of templatesData.audios) {
                console.log('刷新音频素材文件URL:', audio.filename, audio.url);
                setTemplateFileToCache(audio.filename, {url: audio.url, timestamp: Date.now()});
            }
            for (const video of templatesData.videos) {
                console.log('刷新视频素材文件URL:', video.filename, video.url);
                setTemplateFileToCache(video.filename, {url: video.url, timestamp: Date.now()});
            }
        }

        // 加载模板文件
        const loadImageAudioTemplates = async (forceRefresh = false) => {
            try {
                // 如果不是强制刷新,先尝试从缓存加载
1021
                const cacheKey = `${TEMPLATES_CACHE_KEY}_IMAGE_AUDIO_MERGED_${templateCurrentPage.value}_${templatePageSize.value}`;
LiangLiu's avatar
LiangLiu committed
1022
1023
1024
1025
1026
                if (!forceRefresh) {
                // 构建缓存键,包含分页和过滤条件
                const cachedTemplates = loadFromCache(cacheKey, TEMPLATES_CACHE_EXPIRY);
                    if (cachedTemplates && cachedTemplates.templates) {
                    console.log('成功从缓存加载模板列表');
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
                        // 优先使用合并后的模板列表
                        if (cachedTemplates.templates.merged) {
                            mergedTemplates.value = cachedTemplates.templates.merged || [];
                            // 从合并列表中提取图片和音频
                            const images = [];
                            const audios = [];
                            mergedTemplates.value.forEach(template => {
                                if (template.image) {
                                    images.push(template.image);
                                }
                                if (template.audio) {
                                    audios.push(template.audio);
                                }
                            });
                            imageTemplates.value = images;
                            audioTemplates.value = audios;
                        } else {
                            // 向后兼容:如果没有合并列表,使用旧的格式
                            imageTemplates.value = cachedTemplates.templates.images || [];
                            audioTemplates.value = cachedTemplates.templates.audios || [];
                        }
LiangLiu's avatar
LiangLiu committed
1048
1049
1050
                        templatePagination.value = cachedTemplates.pagination || null;
                    return;
                    }
LiangLiu's avatar
LiangLiu committed
1051
1052
                }

LiangLiu's avatar
LiangLiu committed
1053
1054
1055
1056
1057
                console.log('开始加载图片音乐素材库...');
                const response = await publicApiCall(`/api/v1/template/list?page=${templateCurrentPage.value}&page_size=${templatePageSize.value}`);
                if (response.ok) {
                    const data = await response.json();
                    console.log('图片音乐素材库数据:', data);
LiangLiu's avatar
LiangLiu committed
1058

1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
                    // 使用合并后的模板列表
                    const merged = data.templates?.merged || [];
                    mergedTemplates.value = merged;

                    // 为了保持向后兼容,从合并列表中提取图片和音频
                    const images = [];
                    const audios = [];
                    merged.forEach(template => {
                        if (template.image) {
                            images.push(template.image);
                        }
                        if (template.audio) {
                            audios.push(template.audio);
                        }
                    });

                    refreshTemplateFileUrl({ images, audios, videos: data.templates?.videos || [] });
LiangLiu's avatar
LiangLiu committed
1076
                    const templatesData = {
1077
1078
1079
                        images: images,
                        audios: audios,
                        merged: merged
LiangLiu's avatar
LiangLiu committed
1080
                    };
LiangLiu's avatar
LiangLiu committed
1081

1082
1083
                    imageTemplates.value = images;
                    audioTemplates.value = audios;
LiangLiu's avatar
LiangLiu committed
1084
                    templatePagination.value = data.pagination || null;
LiangLiu's avatar
LiangLiu committed
1085

LiangLiu's avatar
LiangLiu committed
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
                    // 保存到缓存
                    saveToCache(cacheKey, {
                        templates: templatesData,
                        pagination: templatePagination.value
                    });
                    console.log('图片音乐素材库已缓存:', templatesData);

                } else {
                    console.warn('加载素材库失败');
                }
            } catch (error) {
                console.warn('加载素材库失败:', error);
            }
        };
LiangLiu's avatar
LiangLiu committed
1100

LiangLiu's avatar
LiangLiu committed
1101
1102
1103
        // 获取素材文件的通用函数(带缓存)
        const getTemplateFile = async (template) => {
            const cacheKey = template.url;
LiangLiu's avatar
LiangLiu committed
1104

LiangLiu's avatar
LiangLiu committed
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
            // 先检查内存缓存
            if (templateFileCache.value.has(cacheKey)) {
                console.log('从内存缓存获取素材文件:', template.filename);
                return templateFileCache.value.get(cacheKey);
            }

            // 如果缓存中没有,则下载并缓存
            console.log('下载素材文件:', template.filename);
            const response = await fetch(template.url, {
                cache: 'force-cache' // 强制使用浏览器缓存
LiangLiu's avatar
LiangLiu committed
1115
1116
            });

LiangLiu's avatar
LiangLiu committed
1117
1118
            if (response.ok) {
                const blob = await response.blob();
LiangLiu's avatar
LiangLiu committed
1119

LiangLiu's avatar
LiangLiu committed
1120
1121
1122
                // 根据文件扩展名确定正确的MIME类型
                let mimeType = blob.type;
                const extension = template.filename.toLowerCase().split('.').pop();
LiangLiu's avatar
LiangLiu committed
1123

LiangLiu's avatar
LiangLiu committed
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
                if (extension === 'wav') {
                    mimeType = 'audio/wav';
                } else if (extension === 'mp3') {
                    mimeType = 'audio/mpeg';
                } else if (extension === 'm4a') {
                    mimeType = 'audio/mp4';
                } else if (extension === 'ogg') {
                    mimeType = 'audio/ogg';
                } else if (extension === 'webm') {
                    mimeType = 'audio/webm';
LiangLiu's avatar
LiangLiu committed
1134
1135
                }

LiangLiu's avatar
LiangLiu committed
1136
                console.log('文件扩展名:', extension, 'MIME类型:', mimeType);
LiangLiu's avatar
LiangLiu committed
1137

LiangLiu's avatar
LiangLiu committed
1138
                const file = new File([blob], template.filename, { type: mimeType });
LiangLiu's avatar
LiangLiu committed
1139

LiangLiu's avatar
LiangLiu committed
1140
1141
1142
1143
1144
1145
1146
1147
                // 缓存文件对象
                templateFileCache.value.set(cacheKey, file);
                console.log('下载素材文件完成:', template.filename);
                return file;
            } else {
                throw new Error('下载素材文件失败');
            }
        };
LiangLiu's avatar
LiangLiu committed
1148

LiangLiu's avatar
LiangLiu committed
1149
1150
1151
1152
        // 选择图片素材
        const selectImageTemplate = async (template) => {
            try {
                const file = await getTemplateFile(template);
LiangLiu's avatar
LiangLiu committed
1153

LiangLiu's avatar
LiangLiu committed
1154
1155
                if (selectedTaskId.value === 'i2v') {
                    i2vForm.value.imageFile = file;
1156
                    i2vForm.value.detectedFaces = [];  // Reset detected faces
LiangLiu's avatar
LiangLiu committed
1157
1158
                } else if (selectedTaskId.value === 's2v') {
                    s2vForm.value.imageFile = file;
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
                    s2vForm.value.detectedFaces = [];  // Reset detected faces
                } else if (selectedTaskId.value === 'animate') {
                    animateForm.value.imageFile = file;
                    animateForm.value.detectedFaces = [];  // Reset detected faces
                }

                // 获取图片的 http/https URL(用于人脸识别和预览)
                let imageUrl = null;
                // 优先使用 template.url(如果是 http/https URL)
                if (template.url && (template.url.startsWith('http://') || template.url.startsWith('https://'))) {
                    imageUrl = template.url;
                } else if (template.inputs && template.inputs.input_image) {
                    // 如果有 inputs.input_image,使用 getTemplateFileUrlAsync 获取 URL
                    imageUrl = await getTemplateFileUrlAsync(template.inputs.input_image, 'images');
                } else if (template.filename) {
                    // 如果有 filename,尝试使用 getTemplateFileUrlAsync
                    imageUrl = await getTemplateFileUrlAsync(template.filename, 'images');
                }

                // 创建预览(使用 data URL 作为预览)
LiangLiu's avatar
LiangLiu committed
1179
                const reader = new FileReader();
1180
1181
1182
1183
1184
1185
1186
1187
                reader.onload = async (e) => {
                    const imageDataUrl = e.target.result;
                    // 如果有 http/https URL,使用它作为预览;否则使用 data URL
                    setCurrentImagePreview(imageUrl || imageDataUrl);
                    updateUploadedContentStatus();
                    showImageTemplates.value = false;
                    showAlert(t('imageTemplateSelected'), 'success');
                    // 不再自动检测人脸,等待用户手动打开多角色模式开关
LiangLiu's avatar
LiangLiu committed
1188
1189
                };
                reader.readAsDataURL(file);
LiangLiu's avatar
LiangLiu committed
1190

LiangLiu's avatar
LiangLiu committed
1191
            } catch (error) {
1192
                showAlert(`${t('loadImageTemplateFailed')}: ${error.message}`, 'danger');
LiangLiu's avatar
LiangLiu committed
1193
1194
            }
        };
LiangLiu's avatar
LiangLiu committed
1195

LiangLiu's avatar
LiangLiu committed
1196
1197
1198
1199
1200
1201
        // 选择音频素材
        const selectAudioTemplate = async (template) => {
            try {
                const file = await getTemplateFile(template);

                s2vForm.value.audioFile = file;
LiangLiu's avatar
LiangLiu committed
1202

LiangLiu's avatar
LiangLiu committed
1203
1204
1205
1206
1207
                // 创建预览
                const reader = new FileReader();
                reader.onload = (e) => {
                    setCurrentAudioPreview(e.target.result);
                    updateUploadedContentStatus();
LiangLiu's avatar
LiangLiu committed
1208
                };
LiangLiu's avatar
LiangLiu committed
1209
                reader.readAsDataURL(file);
LiangLiu's avatar
LiangLiu committed
1210

LiangLiu's avatar
LiangLiu committed
1211
                showAudioTemplates.value = false;
1212
                showAlert(t('audioTemplateSelected'), 'success');
LiangLiu's avatar
LiangLiu committed
1213
            } catch (error) {
1214
                showAlert(`${t('loadAudioTemplateFailed')}: ${error.message}`, 'danger');
LiangLiu's avatar
LiangLiu committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
            }
        };

        // 预览音频素材
        const previewAudioTemplate = (template) => {
            console.log('预览音频模板:', template);
            const audioUrl = getTemplateFileUrl(template.filename, 'audios');
            console.log('音频URL:', audioUrl);
            if (!audioUrl) {
1224
                showAlert(t('audioFileUrlFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
1225
1226
                return;
            }
LiangLiu's avatar
LiangLiu committed
1227

LiangLiu's avatar
LiangLiu committed
1228
1229
1230
1231
1232
1233
            // 停止当前播放的音频
            if (currentPlayingAudio) {
                currentPlayingAudio.pause();
                currentPlayingAudio.currentTime = 0;
                currentPlayingAudio = null;
            }
LiangLiu's avatar
LiangLiu committed
1234

LiangLiu's avatar
LiangLiu committed
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
            const audio = new Audio(audioUrl);
            currentPlayingAudio = audio;

            // 监听音频播放结束事件
            audio.addEventListener('ended', () => {
                currentPlayingAudio = null;
                // 调用停止回调
                if (audioStopCallback) {
                    audioStopCallback();
                    audioStopCallback = null;
LiangLiu's avatar
LiangLiu committed
1245
                }
LiangLiu's avatar
LiangLiu committed
1246
            });
LiangLiu's avatar
LiangLiu committed
1247

LiangLiu's avatar
LiangLiu committed
1248
1249
            audio.addEventListener('error', () => {
                console.error('音频播放失败:', audio.error);
1250
                showAlert(t('audioPlaybackFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
1251
1252
1253
1254
1255
1256
1257
                currentPlayingAudio = null;
                // 调用停止回调
                if (audioStopCallback) {
                    audioStopCallback();
                    audioStopCallback = null;
                }
            });
LiangLiu's avatar
LiangLiu committed
1258

LiangLiu's avatar
LiangLiu committed
1259
1260
            audio.play().catch(error => {
                console.error('音频播放失败:', error);
1261
                showAlert(t('audioPlaybackFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
1262
1263
1264
                currentPlayingAudio = null;
            });
        };
LiangLiu's avatar
LiangLiu committed
1265

1266
        const handleImageUpload = async (event) => {
LiangLiu's avatar
LiangLiu committed
1267
1268
1269
1270
            const file = event.target.files[0];
            if (file) {
                if (selectedTaskId.value === 'i2v') {
                    i2vForm.value.imageFile = file;
1271
                    i2vForm.value.detectedFaces = [];  // Reset detected faces
LiangLiu's avatar
LiangLiu committed
1272
1273
                } else if (selectedTaskId.value === 's2v') {
                    s2vForm.value.imageFile = file;
1274
1275
1276
1277
                    s2vForm.value.detectedFaces = [];  // Reset detected faces
                } else if (selectedTaskId.value === 'animate') {
                    animateForm.value.imageFile = file;
                    animateForm.value.detectedFaces = [];  // Reset detected faces
LiangLiu's avatar
LiangLiu committed
1278
                }
LiangLiu's avatar
LiangLiu committed
1279
                const reader = new FileReader();
1280
1281
1282
                reader.onload = async (e) => {
                    const imageDataUrl = e.target.result;
                    setCurrentImagePreview(imageDataUrl);
LiangLiu's avatar
LiangLiu committed
1283
                    updateUploadedContentStatus();
1284
1285

                    // 不再自动检测人脸,等待用户手动打开多角色模式开关
LiangLiu's avatar
LiangLiu committed
1286
1287
1288
1289
1290
1291
1292
                };
                reader.readAsDataURL(file);
            } else {
                // 用户取消了选择,保持原有图片不变
                // 不做任何操作
            }
        };
LiangLiu's avatar
LiangLiu committed
1293

1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
        // Crop face image from original image based on bbox coordinates
        const cropFaceImage = (imageUrl, bbox) => {
            return new Promise((resolve, reject) => {
                // Validate bbox
                if (!bbox || bbox.length !== 4) {
                    reject(new Error('Invalid bbox coordinates'))
                    return
                }

                const [x1, y1, x2, y2] = bbox
                const width = x2 - x1
                const height = y2 - y1

                if (width <= 0 || height <= 0) {
                    reject(new Error(`Invalid bbox dimensions: ${width}x${height}`))
                    return
                }

                const img = new Image()

                // For data URLs, crossOrigin is not needed
                if (imageUrl.startsWith('data:')) {
                    img.onload = () => {
                        try {
                            // Create Canvas to crop image
                            const canvas = document.createElement('canvas')
                            canvas.width = width
                            canvas.height = height
                            const ctx = canvas.getContext('2d')

                            // Draw the cropped region to Canvas
                            ctx.drawImage(
                                img,
                                x1, y1, width, height,  // Source image crop region
                                0, 0, width, height     // Canvas drawing position
                            )

                            // Convert to base64
                            const base64 = canvas.toDataURL('image/png')
                            resolve(base64)
                        } catch (error) {
                            reject(error)
                        }
                    }
                    img.onerror = (e) => {
                        reject(new Error('Failed to load image for cropping'))
                    }
                    img.src = imageUrl
                } else {
                    // For other URLs, set crossOrigin
                    img.crossOrigin = 'anonymous'
                    img.onload = () => {
                        try {
                            // Create Canvas to crop image
                            const canvas = document.createElement('canvas')
                            canvas.width = width
                            canvas.height = height
                            const ctx = canvas.getContext('2d')

                            // Draw the cropped region to Canvas
                            ctx.drawImage(
                                img,
                                x1, y1, width, height,  // Source image crop region
                                0, 0, width, height     // Canvas drawing position
                            )

                            // Convert to base64
                            const base64 = canvas.toDataURL('image/png')
                            resolve(base64)
                        } catch (error) {
                            reject(error)
                        }
                    }
                    img.onerror = (e) => {
                        reject(new Error('Failed to load image for cropping (CORS or network error)'))
                    }
                    img.src = imageUrl
                }
            })
        }

        // Detect faces in uploaded image
        const detectFacesInImage = async (imageDataUrl) => {
            try {
                // 验证输入
                if (!imageDataUrl || imageDataUrl.trim() === '') {
                    console.error('detectFacesInImage: imageDataUrl is empty');
                    return;
                }

                faceDetecting.value = true;

                // Convert blob URL to data URL (backend can't access blob URLs)
                // For http/https URLs, send directly to backend
                let imageInput = imageDataUrl;
                if (imageDataUrl.startsWith('blob:')) {
                    // Blob URL: convert to data URL since backend can't access blob URLs
                    try {
                        const response = await fetch(imageDataUrl);
                        if (!response.ok) {
                            throw new Error(`Failed to fetch image: ${response.statusText}`);
                        }
                        const blob = await response.blob();
                        imageInput = await new Promise((resolve, reject) => {
                            const reader = new FileReader();
                            reader.onload = () => resolve(reader.result);
                            reader.onerror = reject;
                            reader.readAsDataURL(blob);
                        });
                    } catch (error) {
                        console.error('Failed to convert blob URL to data URL:', error);
                        throw error;
                    }
                }
                // For data URLs and http/https URLs, send directly to backend

                // 再次验证 imageInput
                if (!imageInput || imageInput.trim() === '') {
                    console.error('detectFacesInImage: imageInput is empty after processing');
                    return;
                }

                const response = await apiCall('/api/v1/face/detect', {
                    method: 'POST',
                    body: JSON.stringify({
                        image: imageInput
                    })
                });

                if (!response.ok) {
                    console.error('Face detection failed:', response.status, response.statusText);
                    return;
                }

                const data = await response.json();
                console.log('Face detection response:', data);

                if (data && data.faces) {
                    // Crop face images for each detected face
                    // Use the original imageDataUrl for cropping (cropFaceImage can handle both data URLs and regular URLs)
                    const facesWithImages = await Promise.all(
                        data.faces.map(async (face, index) => {
                            try {
                                // Crop face image from original image based on bbox
                                const croppedImage = await cropFaceImage(imageDataUrl, face.bbox)

                                // Remove data URL prefix, keep only base64 part (consistent with backend format)
                                // croppedImage is in format: "data:image/png;base64,xxxxx"
                                let base64Data = croppedImage
                                if (croppedImage.includes(',')) {
                                    base64Data = croppedImage.split(',')[1]
                                }

                                if (!base64Data) {
                                    console.error(`Failed to extract base64 from cropped image for face ${index}`)
                                    base64Data = null
                                }

                                return {
                                    ...face,
                                    face_image: base64Data,  // Base64 encoded face region image (without data URL prefix)
                                    roleName: `角色${index + 1}`,
                                    isEditing: false  // Track editing state for each face
                                }
                            } catch (error) {
                                console.error(`Failed to crop face ${index}:`, error, 'bbox:', face.bbox);
                                // Return face without face_image if cropping fails
                                return {
                                    ...face,
                                    face_image: null,
                                    roleName: `角色${index + 1}`,
                                    isEditing: false
                                }
                            }
                        })
                    );

                    const currentForm = getCurrentForm();
                    if (currentForm) {
                        currentForm.detectedFaces = facesWithImages;
                        console.log('Updated detectedFaces:', currentForm.detectedFaces.length, 'faces with images');
                        // 音频分离由统一的 watch 监听器处理,不需要在这里手动调用
                    }
                }
            } catch (error) {
                console.error('Face detection error:', error);
                // Silently fail, don't show error to user
            } finally {
                faceDetecting.value = false;
            }
        };

        // Update role name for a detected face
        const updateFaceRoleName = (faceIndex, roleName) => {
            const currentForm = getCurrentForm();
            if (currentForm && currentForm.detectedFaces && currentForm.detectedFaces[faceIndex]) {
                // 使用展开运算符创建新对象,确保响应式更新
                currentForm.detectedFaces[faceIndex] = {
                    ...currentForm.detectedFaces[faceIndex],
                    roleName: roleName
                };
                // 触发响应式更新
                currentForm.detectedFaces = [...currentForm.detectedFaces];
            }
        };

        // Toggle editing state for a face
        const toggleFaceEditing = (faceIndex) => {
            const currentForm = getCurrentForm();
            if (currentForm && currentForm.detectedFaces && currentForm.detectedFaces[faceIndex]) {
                // 使用展开运算符创建新对象,确保响应式更新
                currentForm.detectedFaces[faceIndex] = {
                    ...currentForm.detectedFaces[faceIndex],
                    isEditing: !currentForm.detectedFaces[faceIndex].isEditing
                };
                // 触发响应式更新
                currentForm.detectedFaces = [...currentForm.detectedFaces];
            }
        };

        // Save face role name and exit editing
        const saveFaceRoleName = (faceIndex, roleName) => {
            const currentForm = getCurrentForm();
            if (currentForm && currentForm.detectedFaces && currentForm.detectedFaces[faceIndex]) {
                // 同时更新 roleName 和 isEditing,确保响应式更新
                currentForm.detectedFaces[faceIndex] = {
                    ...currentForm.detectedFaces[faceIndex],
                    roleName: roleName || currentForm.detectedFaces[faceIndex].roleName,
                    isEditing: false
                };
                // 触发响应式更新
                currentForm.detectedFaces = [...currentForm.detectedFaces];
            }
            // 同步更新所有关联的音频播放器角色名
            // 只有当任务类型是 s2v 且有分离的音频时才需要更新
            if (selectedTaskId.value === 's2v' && s2vForm.value.separatedAudios) {
                s2vForm.value.separatedAudios.forEach((audio, index) => {
                    // 如果音频的 roleIndex 等于当前修改的 faceIndex,则更新其 roleName
                    if (audio.roleIndex === faceIndex) {
                        s2vForm.value.separatedAudios[index].roleName = roleName || `角色${faceIndex + 1}`;
                    }
                });
                // 使用展开运算符确保响应式更新
                s2vForm.value.separatedAudios = [...s2vForm.value.separatedAudios];
            }
        };

LiangLiu's avatar
LiangLiu committed
1541
        const selectTask = (taskType) => {
1542
1543
1544
1545
1546
1547
1548
1549
            console.log('[selectTask] 开始切换任务类型:', {
                taskType,
                currentSelectedTaskId: selectedTaskId.value,
                currentSelectedModel: selectedModel.value,
                currentFormModel: getCurrentForm().model_cls,
                currentFormStage: getCurrentForm().stage
            });

LiangLiu's avatar
LiangLiu committed
1550
1551
1552
            for (const t of models.value.map(m => m.task)) {
                if (getTaskTypeName(t) === taskType) {
                    taskType = t;
LiangLiu's avatar
LiangLiu committed
1553
                }
LiangLiu's avatar
LiangLiu committed
1554
1555
1556
            }
            selectedTaskId.value = taskType;

1557
1558
1559
1560
1561
            console.log('[selectTask] 任务类型已更新:', {
                newTaskType: selectedTaskId.value,
                availableModels: models.value.filter(m => m.task === taskType)
            });

LiangLiu's avatar
LiangLiu committed
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
            // 根据任务类型恢复对应的预览
            if (taskType === 'i2v' && i2vForm.value.imageFile) {
                // 恢复图片预览
                const reader = new FileReader();
                reader.onload = (e) => {
                    setCurrentImagePreview(e.target.result);
                };
                reader.readAsDataURL(i2vForm.value.imageFile);
            } else if (taskType === 's2v') {
                // 恢复数字人任务的图片和音频预览
                if (s2vForm.value.imageFile) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        setCurrentImagePreview(e.target.result);
                    };
                    reader.readAsDataURL(s2vForm.value.imageFile);
                }
                if (s2vForm.value.audioFile) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        setCurrentAudioPreview(e.target.result);
                    };
                    reader.readAsDataURL(s2vForm.value.audioFile);
LiangLiu's avatar
LiangLiu committed
1585
                }
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
            } else if (taskType === 'animate') {
                // 恢复角色替换任务的图片和视频预览
                if (animateForm.value.imageFile) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        setCurrentImagePreview(e.target.result);
                    };
                    reader.readAsDataURL(animateForm.value.imageFile);
                }
                if (animateForm.value.videoFile) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        setCurrentVideoPreview(e.target.result);
                    };
                    reader.readAsDataURL(animateForm.value.videoFile);
                }
                // 确保 animate 任务类型有默认 prompt
                if (!animateForm.value.prompt || animateForm.value.prompt.trim() === '') {
                    animateForm.value.prompt = '视频中的人在做动作';
                }
LiangLiu's avatar
LiangLiu committed
1606
            }
LiangLiu's avatar
LiangLiu committed
1607

1608
            // 自动选择该任务类型下的第一个模型(仅在当前模型无效且 URL 中没有 model 参数时)
LiangLiu's avatar
LiangLiu committed
1609
            const currentForm = getCurrentForm();
1610
1611
1612
1613
            const urlParams = new URLSearchParams(window.location.search);
            const hasModelInUrl = urlParams.has('model');

            // 获取新任务类型下的可用模型
LiangLiu's avatar
LiangLiu committed
1614
            const availableModels = models.value.filter(m => m.task === taskType);
1615

LiangLiu's avatar
LiangLiu committed
1616
            if (availableModels.length > 0) {
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
                // 检查当前选择的模型和stage是否属于新任务类型
                const currentModel = currentForm.model_cls || selectedModel.value;
                const currentStage = currentForm.stage;
                const isCurrentModelValid = currentModel && availableModels.some(m =>
                    m.model_cls === currentModel && m.stage === currentStage
                );

                // 如果当前模型无效且 URL 中没有 model 参数,自动选择第一个模型
                if (!isCurrentModelValid || !hasModelInUrl) {
                    const firstModel = availableModels[0];
                    console.log('[selectTask] 自动选择第一个模型:', {
                        firstModel: firstModel.model_cls,
                        firstStage: firstModel.stage,
                        reason: !isCurrentModelValid ? '当前模型或stage无效' : 'URL中没有model参数',
                        currentModel,
                        currentStage
                    });
                    // 直接调用 selectModel 来确保路由也会更新
                    selectModel(firstModel.model_cls);
                } else {
                    console.log('[selectTask] 不自动选择模型:', {
                        isCurrentModelValid,
                        hasModelInUrl,
                        currentModel,
                        currentStage
                    });
LiangLiu's avatar
LiangLiu committed
1643
                }
LiangLiu's avatar
LiangLiu committed
1644
1645
            }
        };
LiangLiu's avatar
LiangLiu committed
1646

LiangLiu's avatar
LiangLiu committed
1647
        const selectModel = (model) => {
1648
1649
1650
1651
1652
1653
1654
1655
            console.log('[selectModel] 开始切换模型:', {
                model,
                currentSelectedModel: selectedModel.value,
                currentTaskType: selectedTaskId.value,
                currentFormModel: getCurrentForm().model_cls,
                currentFormStage: getCurrentForm().stage
            });

LiangLiu's avatar
LiangLiu committed
1656
            selectedModel.value = model;
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
            const currentForm = getCurrentForm();
            currentForm.model_cls = model;
            // 自动设置 stage 为模型对应的第一个 stage
            const availableStages = models.value
                .filter(m => m.task === selectedTaskId.value && m.model_cls === model)
                .map(m => m.stage);
            if (availableStages.length > 0) {
                currentForm.stage = availableStages[0];
                console.log('[selectModel] 自动设置 stage:', {
                    stage: currentForm.stage,
                    availableStages
                });
            }

            console.log('[selectModel] 模型切换完成:', {
                selectedModel: selectedModel.value,
                formModel: currentForm.model_cls,
                formStage: currentForm.stage
            });
LiangLiu's avatar
LiangLiu committed
1676
        };
LiangLiu's avatar
LiangLiu committed
1677

LiangLiu's avatar
LiangLiu committed
1678
1679
1680
        const triggerImageUpload = () => {
            document.querySelector('input[type="file"][accept="image/*"]').click();
        };
LiangLiu's avatar
LiangLiu committed
1681

LiangLiu's avatar
LiangLiu committed
1682
        const triggerAudioUpload = () => {
LiangLiu's avatar
LiangLiu committed
1683
            const audioInput = document.querySelector('input[type="file"][data-role="audio-input"]');
LiangLiu's avatar
LiangLiu committed
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
            if (audioInput) {
                audioInput.click();
            } else {
                console.warn('音频输入框未找到');
            }
        };

        const removeImage = () => {
            setCurrentImagePreview(null);
            if (selectedTaskId.value === 'i2v') {
                i2vForm.value.imageFile = null;
1695
                i2vForm.value.detectedFaces = [];
LiangLiu's avatar
LiangLiu committed
1696
1697
            } else if (selectedTaskId.value === 's2v') {
                s2vForm.value.imageFile = null;
1698
1699
1700
1701
                s2vForm.value.detectedFaces = [];
            } else if (selectedTaskId.value === 'animate') {
                animateForm.value.imageFile = null;
                animateForm.value.detectedFaces = [];
LiangLiu's avatar
LiangLiu committed
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
            }
            updateUploadedContentStatus();
            // 重置文件输入框,确保可以重新选择相同文件
            const imageInput = document.querySelector('input[type="file"][accept="image/*"]');
            if (imageInput) {
                imageInput.value = '';
            }
        };

        const removeAudio = () => {
            setCurrentAudioPreview(null);
            s2vForm.value.audioFile = null;
1714
            s2vForm.value.separatedAudios = [];
LiangLiu's avatar
LiangLiu committed
1715
1716
1717
            updateUploadedContentStatus();
            console.log('音频已移除');
            // 重置音频文件输入框,确保可以重新选择相同文件
LiangLiu's avatar
LiangLiu committed
1718
            const audioInput = document.querySelector('input[type="file"][data-role="audio-input"]');
LiangLiu's avatar
LiangLiu committed
1719
1720
1721
1722
            if (audioInput) {
                audioInput.value = '';
            }
        };
LiangLiu's avatar
LiangLiu committed
1723

1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
        // 删除视频(用于 animate 任务类型)
        const removeVideo = () => {
            setCurrentVideoPreview(null);
            animateForm.value.videoFile = null;
            updateUploadedContentStatus();
            console.log('视频已移除');
            // 重置视频文件输入框,确保可以重新选择相同文件
            const videoInput = document.querySelector('input[type="file"][data-role="video-input"]');
            if (videoInput) {
                videoInput.value = '';
            }
        };

        // Update role assignment for separated audio
        const updateSeparatedAudioRole = (speakerIndex, roleIndex) => {
            if (s2vForm.value.separatedAudios && s2vForm.value.separatedAudios[speakerIndex]) {
                const currentForm = getCurrentForm();
                const detectedFaces = currentForm?.detectedFaces || [];

                if (roleIndex >= 0 && roleIndex < detectedFaces.length) {
                    s2vForm.value.separatedAudios[speakerIndex].roleName = detectedFaces[roleIndex].roleName || `角色${roleIndex + 1}`;
                    s2vForm.value.separatedAudios[speakerIndex].roleIndex = roleIndex;
                }
            }
        };

        // Update audio name for a separated audio
        const updateSeparatedAudioName = (audioIndex, audioName) => {
            if (s2vForm.value.separatedAudios && s2vForm.value.separatedAudios[audioIndex]) {
                s2vForm.value.separatedAudios[audioIndex].audioName = audioName;
            }
        };

        // Toggle editing state for a separated audio
        const toggleSeparatedAudioEditing = (audioIndex) => {
            if (s2vForm.value.separatedAudios && s2vForm.value.separatedAudios[audioIndex]) {
                s2vForm.value.separatedAudios[audioIndex].isEditing = !s2vForm.value.separatedAudios[audioIndex].isEditing;
            }
        };

        // Save separated audio name and exit editing
        const saveSeparatedAudioName = (audioIndex, audioName) => {
            updateSeparatedAudioName(audioIndex, audioName);
            toggleSeparatedAudioEditing(audioIndex);
        };

LiangLiu's avatar
LiangLiu committed
1770
1771
1772
1773
1774
1775
        const getAudioMimeType = () => {
            if (s2vForm.value.audioFile) {
                return s2vForm.value.audioFile.type;
            }
            return 'audio/mpeg'; // 默认类型
        };
LiangLiu's avatar
LiangLiu committed
1776

1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
        // Separate audio tracks for multiple speakers
        const separateAudioTracks = async (audioDataUrl, numSpeakers) => {
            audioSeparating.value = true;  // 开始音频分割,显示加载状态
            try {
                // 优先使用 audioFile(如果存在),因为它包含完整的文件信息,避免 data URL 格式问题
                const currentForm = getCurrentForm();
                let audioData = audioDataUrl;

                if (currentForm?.audioFile && currentForm.audioFile instanceof File) {
                    // 使用 File 对象,读取为 base64,确保格式正确
                    try {
                        const fileDataUrl = await new Promise((resolve, reject) => {
                            const reader = new FileReader();
                            reader.onload = () => resolve(reader.result);
                            reader.onerror = reject;
                            reader.readAsDataURL(currentForm.audioFile);
                        });
                        audioData = fileDataUrl;
                        console.log('Using audioFile for separation, format:', currentForm.audioFile.type);
                    } catch (error) {
                        console.warn('Failed to read audioFile, falling back to audioDataUrl:', error);
                        // 如果读取失败,继续使用 audioDataUrl
                    }
                }

                // Clean and validate base64 string before sending
                let cleanedAudioData = audioData;
                if (audioData.includes(',')) {
                    // If it's a data URL, extract the base64 part
                    const parts = audioData.split(',');
                    if (parts.length > 1) {
                        cleanedAudioData = parts.slice(1).join(','); // Join in case there are multiple commas
                    }
                }

                // Remove any whitespace and newlines
                cleanedAudioData = cleanedAudioData.trim().replace(/\s/g, '');

                // Check if it's a valid base64 string length (must be multiple of 4)
                const missingPadding = cleanedAudioData.length % 4;
                if (missingPadding !== 0) {
                    console.warn(`[separateAudioTracks] Base64 string length (${cleanedAudioData.length}) is not a multiple of 4, adding padding`);
                    cleanedAudioData += '='.repeat(4 - missingPadding);
                }

                // Reconstruct data URL if it was originally a data URL
                if (audioData.startsWith('data:')) {
                    const header = audioData.split(',')[0];
                    cleanedAudioData = `${header},${cleanedAudioData}`;
                }

                console.log(`[separateAudioTracks] Sending audio for separation, length: ${cleanedAudioData.length}, num_speakers: ${numSpeakers}`);

                const response = await apiCall('/api/v1/audio/separate', {
                    method: 'POST',
                    body: JSON.stringify({
                        audio: cleanedAudioData,
                        num_speakers: numSpeakers
                    })
                });

                if (!response.ok) {
                    console.error('Audio separation failed:', response.status, response.statusText);
                    audioSeparating.value = false;
                    return;
                }

                const data = await response.json();
                console.log('Audio separation response:', data);

                if (data && data.speakers && data.speakers.length > 0) {
                    const currentForm = getCurrentForm();
                    const detectedFaces = currentForm?.detectedFaces || [];

                    // Map separated speakers to detected faces
                    // Initialize with first role if available
                    const separatedAudios = data.speakers.map((speaker, index) => {
                        const faceIndex = index < detectedFaces.length ? index : 0;
                        return {
                            speaker_id: speaker.speaker_id,
                            audio: speaker.audio,  // Base64 encoded audio
                            audioDataUrl: `data:audio/wav;base64,${speaker.audio}`,  // Data URL for preview
                            audioName: `音色${index + 1}`,  // 音频名称,默认显示为"音色1"、"音色2"等
                            roleName: detectedFaces[faceIndex]?.roleName || `角色${faceIndex + 1}`,  // 关联的角色名称
                            roleIndex: faceIndex,
                            isEditing: false,  // 编辑状态
                            sample_rate: speaker.sample_rate,
                            segments: speaker.segments
                        };
                    });

                    // Update separatedAudios and trigger reactivity
                    s2vForm.value.separatedAudios = [...separatedAudios];  // Use spread to ensure reactivity
                    console.log('Updated separatedAudios:', s2vForm.value.separatedAudios.length, 'speakers', s2vForm.value.separatedAudios);
                } else {
                    console.warn('No speakers found in separation response:', data);
                    s2vForm.value.separatedAudios = [];
                }
                audioSeparating.value = false;  // 音频分割完成,隐藏加载状态
            } catch (error) {
                console.error('Audio separation error:', error);
                audioSeparating.value = false;  // 发生错误时也要隐藏加载状态
                throw error;
            }
        };

        const handleAudioUpload = async (event) => {
LiangLiu's avatar
LiangLiu committed
1884
            const file = event.target.files[0];
LiangLiu's avatar
LiangLiu committed
1885

LiangLiu's avatar
LiangLiu committed
1886
1887
1888
1889
1890
            if (file && (file.type?.startsWith('audio/') || file.type?.startsWith('video/'))) {
                const allowedVideoTypes = ['video/mp4', 'video/x-m4v', 'video/mpeg'];
                if (file.type.startsWith('video/') && !allowedVideoTypes.includes(file.type)) {
                    showAlert(t('unsupportedVideoFormat'), 'warning');
                    setCurrentAudioPreview(null);
1891
                    s2vForm.value.separatedAudios = [];
LiangLiu's avatar
LiangLiu committed
1892
1893
1894
                    updateUploadedContentStatus();
                    return;
                }
LiangLiu's avatar
LiangLiu committed
1895
                s2vForm.value.audioFile = file;
1896
1897

                // Read file as data URL for preview
LiangLiu's avatar
LiangLiu committed
1898
                const reader = new FileReader();
1899
1900
1901
                reader.onload = async (e) => {
                    const audioDataUrl = e.target.result;
                    setCurrentAudioPreview(audioDataUrl);
LiangLiu's avatar
LiangLiu committed
1902
                    updateUploadedContentStatus();
1903
1904
                    // 音频分离由统一的 watch 监听器处理,不需要在这里手动调用
                    console.log('[handleAudioUpload] 音频上传完成,音频分离将由统一的监听器自动处理');
LiangLiu's avatar
LiangLiu committed
1905
1906
1907
1908
                };
                reader.readAsDataURL(file);
            } else {
                setCurrentAudioPreview(null);
1909
                s2vForm.value.separatedAudios = [];
LiangLiu's avatar
LiangLiu committed
1910
                updateUploadedContentStatus();
LiangLiu's avatar
LiangLiu committed
1911
1912
1913
                if (file) {
                    showAlert(t('unsupportedAudioOrVideo'), 'warning');
                }
LiangLiu's avatar
LiangLiu committed
1914
1915
            }
        };
LiangLiu's avatar
LiangLiu committed
1916

1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
        // 处理视频上传(用于 animate 任务类型)
        const handleVideoUpload = async (event) => {
            const file = event.target.files[0];

            if (file && file.type?.startsWith('video/')) {
                const allowedVideoTypes = ['video/mp4', 'video/x-m4v', 'video/mpeg', 'video/webm', 'video/quicktime'];
                if (!allowedVideoTypes.includes(file.type)) {
                    showAlert(t('unsupportedVideoFormat') || '不支持的视频格式', 'warning');
                    setCurrentVideoPreview(null);
                    animateForm.value.videoFile = null;
                    updateUploadedContentStatus();
                    return;
                }
                animateForm.value.videoFile = file;

                // Read file as data URL for preview
                const reader = new FileReader();
                reader.onload = async (e) => {
                    const videoDataUrl = e.target.result;
                    setCurrentVideoPreview(videoDataUrl);
                    updateUploadedContentStatus();
                };
                reader.readAsDataURL(file);
            } else {
                setCurrentVideoPreview(null);
                animateForm.value.videoFile = null;
                updateUploadedContentStatus();
                if (file) {
                    showAlert(t('unsupportedVideoFormat') || '不支持的视频格式', 'warning');
                }
            }
        };

LiangLiu's avatar
LiangLiu committed
1950
1951
1952
1953
        // 开始录音
        const startRecording = async () => {
            try {
                console.log('开始录音...');
LiangLiu's avatar
LiangLiu committed
1954

LiangLiu's avatar
LiangLiu committed
1955
1956
1957
                // 检查浏览器支持
                if (!navigator.mediaDevices) {
                    throw new Error('该浏览器不支持录音功能');
LiangLiu's avatar
LiangLiu committed
1958
1959
                }

LiangLiu's avatar
LiangLiu committed
1960
1961
                if (!navigator.mediaDevices.getUserMedia) {
                    throw new Error('浏览器不支持录音功能,请确保使用HTTPS协议访问');
LiangLiu's avatar
LiangLiu committed
1962
1963
                }

LiangLiu's avatar
LiangLiu committed
1964
1965
                if (!window.MediaRecorder) {
                    throw new Error('浏览器不支持MediaRecorder,请更新到最新版本浏览器');
LiangLiu's avatar
LiangLiu committed
1966
1967
                }

LiangLiu's avatar
LiangLiu committed
1968
1969
1970
1971
1972
                // 检查HTTPS协议
                console.log('当前协议:', location.protocol, '主机名:', location.hostname);
                if (location.protocol !== 'https:' && location.hostname !== 'localhost' && !location.hostname.includes('127.0.0.1')) {
                    throw new Error(`录音功能需要HTTPS协议,当前使用${location.protocol}协议。请使用HTTPS访问网站或通过localhost:端口号访问`);
                }
LiangLiu's avatar
LiangLiu committed
1973

LiangLiu's avatar
LiangLiu committed
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
                console.log('浏览器支持检查通过,请求麦克风权限...');

                // 记录浏览器支持状态用于调试
                const browserSupport = {
                    mediaDevices: !!navigator.mediaDevices,
                    getUserMedia: !!navigator.mediaDevices?.getUserMedia,
                    MediaRecorder: !!window.MediaRecorder,
                    protocol: location.protocol,
                    hostname: location.hostname,
                    userAgent: navigator.userAgent
                };
                console.log('浏览器支持状态:', browserSupport);

                // 请求麦克风权限
                console.log('正在请求麦克风权限...');
                const stream = await navigator.mediaDevices.getUserMedia({
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        sampleRate: 44100
LiangLiu's avatar
LiangLiu committed
1994
                    }
LiangLiu's avatar
LiangLiu committed
1995
1996
                });
                console.log('麦克风权限获取成功,音频流:', stream);
LiangLiu's avatar
LiangLiu committed
1997

LiangLiu's avatar
LiangLiu committed
1998
1999
2000
2001
                // 创建MediaRecorder
                mediaRecorder.value = new MediaRecorder(stream, {
                    mimeType: 'audio/webm;codecs=opus'
                });
LiangLiu's avatar
LiangLiu committed
2002

LiangLiu's avatar
LiangLiu committed
2003
                audioChunks.value = [];
LiangLiu's avatar
LiangLiu committed
2004

LiangLiu's avatar
LiangLiu committed
2005
2006
2007
2008
                // 监听数据可用事件
                mediaRecorder.value.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        audioChunks.value.push(event.data);
LiangLiu's avatar
LiangLiu committed
2009
                    }
LiangLiu's avatar
LiangLiu committed
2010
                };
LiangLiu's avatar
LiangLiu committed
2011

LiangLiu's avatar
LiangLiu committed
2012
2013
2014
2015
                // 监听录音停止事件
                mediaRecorder.value.onstop = () => {
                    const audioBlob = new Blob(audioChunks.value, { type: 'audio/webm' });
                    const audioFile = new File([audioBlob], 'recording.webm', { type: 'audio/webm' });
LiangLiu's avatar
LiangLiu committed
2016

LiangLiu's avatar
LiangLiu committed
2017
2018
                    // 设置到表单
                    s2vForm.value.audioFile = audioFile;
LiangLiu's avatar
LiangLiu committed
2019

LiangLiu's avatar
LiangLiu committed
2020
2021
2022
                    // 创建预览URL
                    const audioUrl = URL.createObjectURL(audioBlob);
                    setCurrentAudioPreview(audioUrl);
LiangLiu's avatar
LiangLiu committed
2023
2024
                    updateUploadedContentStatus();

LiangLiu's avatar
LiangLiu committed
2025
2026
                    // 停止所有音频轨道
                    stream.getTracks().forEach(track => track.stop());
LiangLiu's avatar
LiangLiu committed
2027

LiangLiu's avatar
LiangLiu committed
2028
2029
                    showAlert(t('recordingCompleted'), 'success');
                };
LiangLiu's avatar
LiangLiu committed
2030

LiangLiu's avatar
LiangLiu committed
2031
2032
2033
2034
                // 开始录音
                mediaRecorder.value.start(1000); // 每秒收集一次数据
                isRecording.value = true;
                recordingDuration.value = 0;
LiangLiu's avatar
LiangLiu committed
2035

LiangLiu's avatar
LiangLiu committed
2036
2037
2038
2039
                // 开始计时
                recordingTimer.value = setInterval(() => {
                    recordingDuration.value++;
                }, 1000);
LiangLiu's avatar
LiangLiu committed
2040

LiangLiu's avatar
LiangLiu committed
2041
2042
2043
2044
2045
2046
2047
                showAlert(t('recordingStarted'), 'info');

            } catch (error) {
                console.error('录音失败:', error);
                let errorMessage = t('recordingFailed');

                if (error.name === 'NotAllowedError') {
2048
                    errorMessage = t('microphonePermissionDenied');
LiangLiu's avatar
LiangLiu committed
2049
                } else if (error.name === 'NotFoundError') {
2050
                    errorMessage = t('microphoneNotFound');
LiangLiu's avatar
LiangLiu committed
2051
                } else if (error.name === 'NotSupportedError') {
2052
                    errorMessage = t('recordingNotSupportedOnMobile');
LiangLiu's avatar
LiangLiu committed
2053
                } else if (error.name === 'NotReadableError') {
2054
                    errorMessage = t('microphoneInUse');
LiangLiu's avatar
LiangLiu committed
2055
                } else if (error.name === 'OverconstrainedError') {
2056
                    errorMessage = t('microphoneNotCompatible');
LiangLiu's avatar
LiangLiu committed
2057
                } else if (error.name === 'SecurityError') {
2058
                    errorMessage = t('securityErrorUseHttps');
LiangLiu's avatar
LiangLiu committed
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
                } else if (error.message) {
                    errorMessage = error.message;
                }

                // 添加调试信息
                const debugInfo = {
                    userAgent: navigator.userAgent,
                    protocol: location.protocol,
                    hostname: location.hostname,
                    mediaDevices: !!navigator.mediaDevices,
                    getUserMedia: !!navigator.mediaDevices?.getUserMedia,
                    MediaRecorder: !!window.MediaRecorder,
                    isSecureContext: window.isSecureContext,
                    chromeVersion: navigator.userAgent.match(/Chrome\/(\d+)/)?.[1] || '未知'
                };
                console.log('浏览器调试信息:', debugInfo);
LiangLiu's avatar
LiangLiu committed
2075

LiangLiu's avatar
LiangLiu committed
2076
2077
2078
2079
2080
2081
2082
                // 如果是Chrome但仍有问题,提供特定建议
                if (navigator.userAgent.includes('Chrome')) {
                    console.log('检测到Chrome浏览器,可能的问题:');
                    console.log('1. 请确保使用HTTPS协议或localhost访问');
                    console.log('2. 检查Chrome地址栏是否有麦克风权限');
                    console.log('3. 尝试在Chrome设置中重置网站权限');
                    console.log('4. 确保没有其他应用占用麦克风');
LiangLiu's avatar
LiangLiu committed
2083
2084
                }

LiangLiu's avatar
LiangLiu committed
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
                showAlert(errorMessage, 'danger');
            }
        };

        // 停止录音
        const stopRecording = () => {
            if (mediaRecorder.value && isRecording.value) {
                mediaRecorder.value.stop();
                isRecording.value = false;

                if (recordingTimer.value) {
                    clearInterval(recordingTimer.value);
                    recordingTimer.value = null;
LiangLiu's avatar
LiangLiu committed
2098
2099
                }

LiangLiu's avatar
LiangLiu committed
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
                showAlert(t('recordingStopped'), 'info');
            }
        };

        // 格式化录音时长
        const formatRecordingDuration = (seconds) => {
            const mins = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        };

        const submitTask = async () => {
            try {
                // 检查是否正在加载模板
                if (templateLoading.value) {
2115
                    showAlert(t('templateLoadingPleaseWait'), 'warning');
LiangLiu's avatar
LiangLiu committed
2116
2117
                    return;
                }
LiangLiu's avatar
LiangLiu committed
2118

LiangLiu's avatar
LiangLiu committed
2119
                const currentForm = getCurrentForm();
LiangLiu's avatar
LiangLiu committed
2120

LiangLiu's avatar
LiangLiu committed
2121
2122
                // 表单验证
                if (!selectedTaskId.value) {
2123
                    showAlert(t('pleaseSelectTaskType'), 'warning');
LiangLiu's avatar
LiangLiu committed
2124
2125
                    return;
                }
LiangLiu's avatar
LiangLiu committed
2126

LiangLiu's avatar
LiangLiu committed
2127
                if (!currentForm.model_cls) {
2128
                    showAlert(t('pleaseSelectModel'), 'warning');
LiangLiu's avatar
LiangLiu committed
2129
                    return;
LiangLiu's avatar
LiangLiu committed
2130
                }
LiangLiu's avatar
LiangLiu committed
2131

2132
2133
2134
2135
2136
2137
2138
2139
2140
                // animate 任务类型不需要 prompt,其他任务类型需要
                if (selectedTaskId.value !== 'animate') {
                    if (!currentForm.prompt || currentForm.prompt.trim().length === 0) {
                        if (selectedTaskId.value === 's2v') {
                            currentForm.prompt = '让角色根据音频内容自然说话';
                        } else {
                            showAlert(t('pleaseEnterPrompt'), 'warning');
                            return;
                        }
LiangLiu's avatar
LiangLiu committed
2141
2142
                    }

2143
2144
2145
2146
                    if (currentForm.prompt.length > 1000) {
                        showAlert(t('promptTooLong'), 'warning');
                        return;
                    }
LiangLiu's avatar
LiangLiu committed
2147
2148
                }

LiangLiu's avatar
LiangLiu committed
2149
                if (selectedTaskId.value === 'i2v' && !currentForm.imageFile) {
2150
                    showAlert(t('i2vTaskRequiresImage'), 'warning');
LiangLiu's avatar
LiangLiu committed
2151
                    return;
LiangLiu's avatar
LiangLiu committed
2152
2153
                }

LiangLiu's avatar
LiangLiu committed
2154
                if (selectedTaskId.value === 's2v' && !currentForm.imageFile) {
2155
                    showAlert(t('s2vTaskRequiresImage'), 'warning');
LiangLiu's avatar
LiangLiu committed
2156
                    return;
LiangLiu's avatar
LiangLiu committed
2157
2158
                }

LiangLiu's avatar
LiangLiu committed
2159
                if (selectedTaskId.value === 's2v' && !currentForm.audioFile) {
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
                    showAlert(t('s2vTaskRequiresAudio'), 'warning');
                    return;
                }

                if (selectedTaskId.value === 'animate' && !currentForm.imageFile) {
                    showAlert(t('animateTaskRequiresImage'), 'warning');
                    return;
                }

                if (selectedTaskId.value === 'animate' && !currentForm.videoFile) {
                    showAlert(t('animateTaskRequiresVideo'), 'warning');
LiangLiu's avatar
LiangLiu committed
2171
2172
2173
                    return;
                }
                submitting.value = true;
LiangLiu's avatar
LiangLiu committed
2174

LiangLiu's avatar
LiangLiu committed
2175
2176
                // 确定实际提交的任务类型
                let actualTaskType = selectedTaskId.value;
LiangLiu's avatar
LiangLiu committed
2177

LiangLiu's avatar
LiangLiu committed
2178
2179
2180
2181
2182
2183
                var formData = {
                    task: actualTaskType,
                    model_cls: currentForm.model_cls,
                    stage: currentForm.stage,
                    seed: currentForm.seed || Math.floor(Math.random() * 1000000)
                };
LiangLiu's avatar
LiangLiu committed
2184

2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
                // animate 任务类型使用默认 prompt,其他任务类型需要用户输入
                if (selectedTaskId.value === 'animate') {
                    // animate 任务类型使用默认 prompt
                    formData.prompt = currentForm.prompt && currentForm.prompt.trim().length > 0
                        ? currentForm.prompt.trim()
                        : '视频中的人在做动作';
                } else {
                    formData.prompt = currentForm.prompt ? currentForm.prompt.trim() : '';
                }

LiangLiu's avatar
LiangLiu committed
2195
2196
2197
                if (currentForm.model_cls.startsWith('wan2.1')) {
                    formData.negative_prompt = "镜头晃动,色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
                }
LiangLiu's avatar
LiangLiu committed
2198

LiangLiu's avatar
LiangLiu committed
2199
2200
2201
2202
2203
2204
2205
                if (selectedTaskId.value === 'i2v' && currentForm.imageFile) {
                    const base64 = await fileToBase64(currentForm.imageFile);
                    formData.input_image = {
                        type: 'base64',
                        data: base64
                    };
                }
LiangLiu's avatar
LiangLiu committed
2206

2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
                if (selectedTaskId.value === 'animate' && currentForm.imageFile) {
                    const base64 = await fileToBase64(currentForm.imageFile);
                    formData.input_image = {
                        type: 'base64',
                        data: base64
                    };
                }

                if (selectedTaskId.value === 'animate' && currentForm.videoFile) {
                    const base64 = await fileToBase64(currentForm.videoFile);
                    formData.input_video = {
                        type: 'base64',
                        data: base64
                    };
                }

LiangLiu's avatar
LiangLiu committed
2223
2224
2225
2226
2227
2228
2229
2230
                if (selectedTaskId.value === 's2v') {
                    if (currentForm.imageFile) {
                        const base64 = await fileToBase64(currentForm.imageFile);
                        formData.input_image = {
                            type: 'base64',
                            data: base64
                        };
                    }
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260

                    // 检测是否为多人模式:有多个分离的音频和多个角色
                    const isMultiPersonMode = s2vForm.value.separatedAudios &&
                                            s2vForm.value.separatedAudios.length > 1 &&
                                            currentForm.detectedFaces &&
                                            currentForm.detectedFaces.length > 1;

                    if (isMultiPersonMode) {
                        // 多人模式:生成mask图、保存音频文件、生成config.json
                        try {
                            const multiPersonData = await prepareMultiPersonAudio(
                                currentForm.detectedFaces,
                                s2vForm.value.separatedAudios,
                                currentForm.imageFile,
                                currentForm.audioFile  // 传递原始音频文件
                            );

                            formData.input_audio = {
                                type: 'directory',
                                data: multiPersonData
                            };
                            formData.negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
                        } catch (error) {
                            console.error('Failed to prepare multi-person audio:', error);
                            showAlert(t('prepareMultiPersonAudioFailed') + ': ' + error.message, 'danger');
                            submitting.value = false;
                            return;
                        }
                    } else if (currentForm.audioFile) {
                        // 单人模式:使用原始音频文件
LiangLiu's avatar
LiangLiu committed
2261
2262
2263
2264
2265
2266
                        const base64 = await fileToBase64(currentForm.audioFile);
                        formData.input_audio = {
                            type: 'base64',
                            data: base64
                        };
                        formData.negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
LiangLiu's avatar
LiangLiu committed
2267
2268
2269
                    }
                }

LiangLiu's avatar
LiangLiu committed
2270
2271
2272
2273
                const response = await apiRequest('/api/v1/task/submit', {
                    method: 'POST',
                    body: JSON.stringify(formData)
                });
LiangLiu's avatar
LiangLiu committed
2274

LiangLiu's avatar
LiangLiu committed
2275
                if (response && response.ok) {
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
                    let result;
                    try {
                        result = await response.json();
                    } catch (error) {
                        console.error('Failed to parse response JSON:', error);
                        showAlert(t('taskSubmittedButParseFailed'), 'warning');
                        submitting.value = false;
                        return null;
                    }

LiangLiu's avatar
LiangLiu committed
2286
2287
                    showAlert(t('taskSubmitSuccessAlert'), 'success');

2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
                    // 开始轮询新提交的任务状态(不等待,异步执行)
                    try {
                        startPollingTask(result.task_id);
                    } catch (error) {
                        console.error('Failed to start polling task:', error);
                        // 不阻止流程继续
                    }

                    // 保存完整的任务历史(包括提示词、图片和音频)- 异步执行,不阻塞
                    // 注意:addTaskToHistory 是同步函数,但为了统一处理,使用 Promise.resolve 包装
                    Promise.resolve().then(() => {
                        try {
                            addTaskToHistory(selectedTaskId.value, currentForm);
                        } catch (error) {
                            console.error('Failed to add task to history:', error);
                        }
                    }).catch(error => {
                        console.error('Failed to add task to history:', error);
                    });

                    // 重置表单(异步执行,不阻塞)- 使用 Promise.race 添加超时保护
                    try {
                        await Promise.race([
                            Promise.resolve(resetForm(selectedTaskId.value)),
                            new Promise((_, reject) => setTimeout(() => reject(new Error('resetForm timeout')), 3000))
                        ]);
                    } catch (error) {
                        console.error('Failed to reset form:', error);
                        // 不阻止流程继续,只记录错误
                    }

LiangLiu's avatar
LiangLiu committed
2319
                    // 重置当前任务类型的表单(保留模型选择,清空图片、音频和提示词)
2320
2321
2322
2323
2324
2325
2326
                    try {
                        selectedTaskId.value = selectedTaskId.value;
                        selectModel(currentForm.model_cls);
                    } catch (error) {
                        console.error('Failed to select model:', error);
                        // 不阻止流程继续
                    }
LiangLiu's avatar
LiangLiu committed
2327
2328
2329
2330

                    // 返回新创建的任务ID
                    return result.task_id;
                } else {
2331
2332
2333
2334
2335
2336
2337
2338
                    let error;
                    try {
                        error = await response.json();
                        showAlert(`${t('taskSubmitFailedAlert')}: ${error.message || 'Unknown error'},${error.detail || ''}`, 'danger');
                    } catch (parseError) {
                        console.error('Failed to parse error response:', parseError);
                        showAlert(`${t('taskSubmitFailedAlert')}: ${response.statusText || 'Unknown error'}`, 'danger');
                    }
LiangLiu's avatar
LiangLiu committed
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
                    return null;
                }
            } catch (error) {
                showAlert(`${t('submitTaskFailedAlert')}: ${error.message}`, 'danger');
                return null;
            } finally {
                submitting.value = false;
            }
        };

        const fileToBase64 = (file) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => {
                    const base64 = reader.result.split(',')[1];
                    resolve(base64);
                };
                reader.onerror = error => reject(error);
            });
        };

2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
        // 准备多人模式的音频数据:生成mask图、保存音频文件、生成config.json
        const prepareMultiPersonAudio = async (detectedFaces, separatedAudios, imageFile, originalAudioFile) => {
            // 1. 读取原始图片,获取尺寸
            const imageBase64 = await fileToBase64(imageFile);
            const imageDataUrl = `data:image/png;base64,${imageBase64}`;

            // 创建图片对象以获取尺寸
            const img = new Image();
            await new Promise((resolve, reject) => {
                img.onload = resolve;
                img.onerror = reject;
                img.src = imageDataUrl;
            });
            const imageWidth = img.naturalWidth;
            const imageHeight = img.naturalHeight;

            // 2. 为每个角色生成mask图和音频文件
            const directoryFiles = {};
            const talkObjects = [];

            for (let i = 0; i < detectedFaces.length; i++) {
                const face = detectedFaces[i];
                const audioIndex = i < separatedAudios.length ? i : 0;
                const audio = separatedAudios[audioIndex];

                // 生成mask图(box部分为白色,其余部分为黑色)
                const maskBase64 = await generateMaskImage(
                    face.bbox,
                    imageWidth,
                    imageHeight
                );

                // 保存mask图
                const maskFilename = `p${i + 1}_mask.png`;
                directoryFiles[maskFilename] = maskBase64;

                // 保存音频文件
                // 注意:separatedAudios中的audio已经是base64编码的wav格式
                const audioFilename = `p${i + 1}.wav`;
                directoryFiles[audioFilename] = audio.audio; // audio.audio是base64编码的wav数据

                // 添加到talk_objects
                talkObjects.push({
                    audio: audioFilename,
                    mask: maskFilename
                });
            }

            // 3. 保存原始未分割的音频文件(用于后续复用)
            if (originalAudioFile) {
                try {
                    // 将原始音频文件转换为base64
                    const originalAudioBase64 = await fileToBase64(originalAudioFile);
                    // 根据原始文件名确定扩展名,如果没有扩展名则使用.wav
                    const originalFilename = originalAudioFile.name || 'original_audio.wav';
                    const fileExtension = originalFilename.toLowerCase().split('.').pop();
                    const validExtensions = ['wav', 'mp3', 'mp4', 'aac', 'ogg', 'm4a'];
                    const extension = validExtensions.includes(fileExtension) ? fileExtension : 'wav';
                    const originalAudioFilename = `original_audio.${extension}`;
                    directoryFiles[originalAudioFilename] = originalAudioBase64;
                    console.log('已保存原始音频文件:', originalAudioFilename);
                } catch (error) {
                    console.warn('保存原始音频文件失败:', error);
                    // 不阻止任务提交,只记录警告
                }
            }

            // 4. 生成config.json
            const configJson = {
                talk_objects: talkObjects
            };
            const configJsonString = JSON.stringify(configJson, null, 4);
            const configBase64 = btoa(unescape(encodeURIComponent(configJsonString)));
            directoryFiles['config.json'] = configBase64;

            return directoryFiles;
        };

        // 生成mask图:根据bbox坐标生成白色区域,其余为黑色
        const generateMaskImage = async (bbox, imageWidth, imageHeight) => {
            // bbox格式: [x1, y1, x2, y2]
            const [x1, y1, x2, y2] = bbox;

            // 创建canvas
            const canvas = document.createElement('canvas');
            canvas.width = imageWidth;
            canvas.height = imageHeight;
            const ctx = canvas.getContext('2d');

            // 填充黑色背景
            ctx.fillStyle = '#000000';
            ctx.fillRect(0, 0, imageWidth, imageHeight);

            // 在bbox区域填充白色
            ctx.fillStyle = '#FFFFFF';
            ctx.fillRect(Math.round(x1), Math.round(y1), Math.round(x2 - x1), Math.round(y2 - y1));

            // 转换为base64
            return canvas.toDataURL('image/png').split(',')[1];
        };

LiangLiu's avatar
LiangLiu committed
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
        const formatTime = (timestamp) => {
            if (!timestamp) return '';
            const date = new Date(timestamp * 1000);
            return date.toLocaleString('zh-CN');
        };

        // 通用缓存管理函数
        const loadFromCache = (cacheKey, expiryKey) => {
            try {
                const cached = localStorage.getItem(cacheKey);
                if (cached) {
                    const data = JSON.parse(cached);
                    if (Date.now() - data.timestamp < expiryKey) {
                        console.log(`成功从缓存加载数据${cacheKey}:`, data.data);
                        return data.data;
                    } else {
                        // 缓存过期,清除
                        localStorage.removeItem(cacheKey);
                        console.log(`缓存过期,清除 ${cacheKey}`);
                    }
                }
            } catch (error) {
                console.warn(`加载缓存失败 ${cacheKey}:`, error);
                localStorage.removeItem(cacheKey);
            }
            return null;
        };

        const saveToCache = (cacheKey, data) => {
            try {
                const cacheData = {
                    data: data,
                    timestamp: Date.now()
                };
                console.log(`成功保存缓存数据 ${cacheKey}:`, cacheData);
                localStorage.setItem(cacheKey, JSON.stringify(cacheData));
            } catch (error) {
                console.warn(`保存缓存失败 ${cacheKey}:`, error);
            }
        };

        // 清除所有应用缓存
        const clearAllCache = () => {
            try {
                const cacheKeys = [
                    TASK_FILE_CACHE_KEY,
                    TEMPLATE_FILE_CACHE_KEY,
                    MODELS_CACHE_KEY,
                    TEMPLATES_CACHE_KEY
                ];

                // 清除所有任务缓存(使用通配符匹配)
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    if (key && key.startsWith(TASKS_CACHE_KEY)) {
                        localStorage.removeItem(key);
                    }
LiangLiu's avatar
LiangLiu committed
2519
2520
                }

LiangLiu's avatar
LiangLiu committed
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
                // 清除所有模板缓存(使用通配符匹配)
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    if (key && key.startsWith(TEMPLATES_CACHE_KEY)) {
                        localStorage.removeItem(key);
                    }
                }
                // 清除其他缓存
                cacheKeys.forEach(key => {
                    localStorage.removeItem(key);
                });
LiangLiu's avatar
LiangLiu committed
2532

LiangLiu's avatar
LiangLiu committed
2533
2534
2535
                // 清除内存中的任务文件缓存
                taskFileCache.value.clear();
                taskFileCacheLoaded.value = false;
LiangLiu's avatar
LiangLiu committed
2536

LiangLiu's avatar
LiangLiu committed
2537
2538
2539
                // 清除内存中的模板文件缓存
                templateFileCache.value.clear();
                templateFileCacheLoaded.value = false;
LiangLiu's avatar
LiangLiu committed
2540

LiangLiu's avatar
LiangLiu committed
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
                console.log('所有缓存已清除');
            } catch (error) {
                console.warn('清除缓存失败:', error);
            }
        };

        // 模板文件缓存管理函数
        const loadTemplateFilesFromCache = () => {
            try {
                const cached = localStorage.getItem(TEMPLATE_FILE_CACHE_KEY);
                if (cached) {
                    const data = JSON.parse(cached);
                    if (data.files) {
                        for (const [cacheKey, fileData] of Object.entries(data.files)) {
                            templateFileCache.value.set(cacheKey, fileData);
LiangLiu's avatar
LiangLiu committed
2556
                        }
LiangLiu's avatar
LiangLiu committed
2557
2558
2559
2560
                        return true;
                    } else {
                        console.warn('模板文件缓存数据格式错误');
                        return false;
LiangLiu's avatar
LiangLiu committed
2561
2562
                    }
                }
LiangLiu's avatar
LiangLiu committed
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
            } catch (error) {
                console.warn('加载模板文件缓存失败:', error);
            }
            return false;
        };

        const saveTemplateFilesToCache = () => {
            try {
                const files = {};
                for (const [cacheKey, fileData] of templateFileCache.value.entries()) {
                    files[cacheKey] = fileData;
                }
                const data = {
                    files: files,
                    timestamp: Date.now()
                };
                localStorage.setItem(TEMPLATE_FILE_CACHE_KEY, JSON.stringify(data));
            } catch (error) {
                console.warn('保存模板文件缓存失败:', error);
            }
        };

        const getTemplateFileCacheKey = (templateId, fileKey) => {
            return `template_${templateId}_${fileKey}`;
        };

        const getTemplateFileFromCache = (cacheKey) => {
            return templateFileCache.value.get(cacheKey) || null;
        };

        const setTemplateFileToCache = (fileKey, fileData) => {
            templateFileCache.value.set(fileKey, fileData);
            // 异步保存到localStorage
            setTimeout(() => {
                saveTemplateFilesToCache();
            }, 100);
        };

        const getTemplateFileUrlFromApi = async (fileKey, fileType) => {
            const apiUrl = `/api/v1/template/asset_url/${fileType}/${fileKey}`;
            const response = await apiRequest(apiUrl);
            if (response && response.ok) {
                const data = await response.json();
                let assertUrl = data.url;
                if (assertUrl.startsWith('./assets/')) {
                    const token = localStorage.getItem('accessToken');
                    if (token) {
                        assertUrl = `${assertUrl}&token=${encodeURIComponent(token)}`;
LiangLiu's avatar
LiangLiu committed
2611
                    }
LiangLiu's avatar
LiangLiu committed
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
                }
                setTemplateFileToCache(fileKey, {
                    url: assertUrl,
                    timestamp: Date.now()
                });
                return assertUrl;
            }
            return null;
        };

        // 获取模板文件URL(优先从缓存,缓存没有则生成URL)- 同步版本
        const getTemplateFileUrl = (fileKey, fileType) => {
2624
            // 检查参数有效性(静默处理,不打印警告,因为模板可能确实没有某些输入)
LiangLiu's avatar
LiangLiu committed
2625
2626
2627
            if (!fileKey) {
                return null;
            }
LiangLiu's avatar
LiangLiu committed
2628

LiangLiu's avatar
LiangLiu committed
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
            // 先从缓存获取
            const cachedFile = getTemplateFileFromCache(fileKey);
            if (cachedFile) {
                /* console.log('从缓存获取模板文件url', { fileKey});*/
                return cachedFile.url;
            }
            // 如果缓存中没有,返回null,让调用方知道需要异步获取
            console.warn('模板文件URL不在缓存中,需要异步获取:', { fileKey, fileType });
            getTemplateFileUrlAsync(fileKey, fileType).then(url => {
                return url;
            });
            return null;
        };
LiangLiu's avatar
LiangLiu committed
2642

LiangLiu's avatar
LiangLiu committed
2643
2644
2645
        // 创建响应式的模板文件URL(用于首屏渲染)
        const createTemplateFileUrlRef = (fileKey, fileType) => {
            const urlRef = ref(null);
LiangLiu's avatar
LiangLiu committed
2646

2647
            // 检查参数有效性(静默处理,不打印警告)
LiangLiu's avatar
LiangLiu committed
2648
2649
2650
            if (!fileKey) {
                return urlRef;
            }
LiangLiu's avatar
LiangLiu committed
2651

LiangLiu's avatar
LiangLiu committed
2652
2653
2654
2655
2656
2657
            // 先从缓存获取
            const cachedFile = getTemplateFileFromCache(fileKey);
            if (cachedFile) {
                urlRef.value = cachedFile.url;
                return urlRef;
            }
LiangLiu's avatar
LiangLiu committed
2658

LiangLiu's avatar
LiangLiu committed
2659
2660
2661
2662
2663
2664
            // 检查是否正在获取中,避免重复请求
            const fetchKey = `${fileKey}_${fileType}`;
            if (templateUrlFetching.value.has(fetchKey)) {
                console.log('createTemplateFileUrlRef: 正在获取中,跳过重复请求', { fileKey, fileType });
                return urlRef;
            }
LiangLiu's avatar
LiangLiu committed
2665

LiangLiu's avatar
LiangLiu committed
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
            // 标记为正在获取
            templateUrlFetching.value.add(fetchKey);

            // 如果缓存中没有,异步获取
            getTemplateFileUrlFromApi(fileKey, fileType).then(url => {
                if (url) {
                    urlRef.value = url;
                    // 将获取到的URL存储到缓存中
                    setTemplateFileToCache(fileKey, { url, timestamp: Date.now() });
                }
            }).catch(error => {
                console.warn('获取模板文件URL失败:', error);
            }).finally(() => {
                // 移除获取状态
                templateUrlFetching.value.delete(fetchKey);
            });
LiangLiu's avatar
LiangLiu committed
2682

LiangLiu's avatar
LiangLiu committed
2683
2684
            return urlRef;
        };
LiangLiu's avatar
LiangLiu committed
2685

LiangLiu's avatar
LiangLiu committed
2686
2687
2688
        // 创建响应式的任务文件URL(用于首屏渲染)
        const createTaskFileUrlRef = (taskId, fileKey) => {
            const urlRef = ref(null);
LiangLiu's avatar
LiangLiu committed
2689

LiangLiu's avatar
LiangLiu committed
2690
2691
2692
2693
2694
            // 检查参数有效性
            if (!taskId || !fileKey) {
                console.warn('createTaskFileUrlRef: 参数为空', { taskId, fileKey });
                return urlRef;
            }
LiangLiu's avatar
LiangLiu committed
2695

LiangLiu's avatar
LiangLiu committed
2696
2697
2698
2699
2700
2701
            // 先从缓存获取
            const cachedFile = getTaskFileFromCache(taskId, fileKey);
            if (cachedFile) {
                urlRef.value = cachedFile.url;
                return urlRef;
            }
LiangLiu's avatar
LiangLiu committed
2702

LiangLiu's avatar
LiangLiu committed
2703
2704
2705
2706
2707
2708
            // 如果缓存中没有,异步获取
            getTaskFileUrl(taskId, fileKey).then(url => {
                if (url) {
                    urlRef.value = url;
                    // 将获取到的URL存储到缓存中
                    setTaskFileToCache(taskId, fileKey, { url, timestamp: Date.now() });
LiangLiu's avatar
LiangLiu committed
2709
                }
LiangLiu's avatar
LiangLiu committed
2710
2711
2712
            }).catch(error => {
                console.warn('获取任务文件URL失败:', error);
            });
LiangLiu's avatar
LiangLiu committed
2713

LiangLiu's avatar
LiangLiu committed
2714
2715
            return urlRef;
        };
LiangLiu's avatar
LiangLiu committed
2716

LiangLiu's avatar
LiangLiu committed
2717
2718
        // 获取模板文件URL(异步版本,用于预加载等场景)
        const getTemplateFileUrlAsync = async (fileKey, fileType) => {
2719
            // 检查参数有效性(静默处理,不打印警告,因为模板可能确实没有某些输入)
LiangLiu's avatar
LiangLiu committed
2720
2721
2722
            if (!fileKey) {
                return null;
            }
LiangLiu's avatar
LiangLiu committed
2723

LiangLiu's avatar
LiangLiu committed
2724
2725
2726
2727
2728
2729
            // 先从缓存获取
            const cachedFile = getTemplateFileFromCache(fileKey);
            if (cachedFile) {
                console.log('getTemplateFileUrlAsync: 从缓存获取', { fileKey, url: cachedFile.url });
                return cachedFile.url;
            }
LiangLiu's avatar
LiangLiu committed
2730

LiangLiu's avatar
LiangLiu committed
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
            // 检查是否正在获取中,避免重复请求
            const fetchKey = `${fileKey}_${fileType}`;
            if (templateUrlFetching.value.has(fetchKey)) {
                console.log('getTemplateFileUrlAsync: 正在获取中,等待完成', { fileKey, fileType });
                // 等待其他请求完成
                return new Promise((resolve) => {
                    const checkInterval = setInterval(() => {
                        const cachedFile = getTemplateFileFromCache(fileKey);
                        if (cachedFile) {
                            clearInterval(checkInterval);
                            resolve(cachedFile.url);
                        } else if (!templateUrlFetching.value.has(fetchKey)) {
                            clearInterval(checkInterval);
                            resolve(null);
                        }
                    }, 100);
                });
            }
LiangLiu's avatar
LiangLiu committed
2749

LiangLiu's avatar
LiangLiu committed
2750
2751
            // 标记为正在获取
            templateUrlFetching.value.add(fetchKey);
LiangLiu's avatar
LiangLiu committed
2752

LiangLiu's avatar
LiangLiu committed
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
            // 如果缓存中没有,异步获取
            try {
                const url = await getTemplateFileUrlFromApi(fileKey, fileType);
                if (url) {
                    // 将获取到的URL存储到缓存中
                    setTemplateFileToCache(fileKey, { url, timestamp: Date.now() });
                }
                return url;
            } catch (error) {
                console.warn('getTemplateFileUrlAsync: 获取URL失败', error);
                return null;
            } finally {
                // 移除获取状态
                templateUrlFetching.value.delete(fetchKey);
            }
        };

        // 任务文件缓存管理函数
        const loadTaskFilesFromCache = () => {
            try {
                const cached = localStorage.getItem(TASK_FILE_CACHE_KEY);
                if (cached) {
                    const data = JSON.parse(cached);
                    // 检查是否过期
                    if (Date.now() - data.timestamp < TASK_FILE_CACHE_EXPIRY) {
                        // 将缓存数据加载到内存缓存中
                        for (const [cacheKey, fileData] of Object.entries(data.files)) {
                            taskFileCache.value.set(cacheKey, fileData);
LiangLiu's avatar
LiangLiu committed
2781
                        }
LiangLiu's avatar
LiangLiu committed
2782
                        return true;
LiangLiu's avatar
LiangLiu committed
2783
                    } else {
LiangLiu's avatar
LiangLiu committed
2784
2785
                        // 缓存过期,清除
                        localStorage.removeItem(TASK_FILE_CACHE_KEY);
LiangLiu's avatar
LiangLiu committed
2786
2787
                    }
                }
LiangLiu's avatar
LiangLiu committed
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
            } catch (error) {
                console.warn('加载任务文件缓存失败:', error);
                localStorage.removeItem(TASK_FILE_CACHE_KEY);
            }
            return false;
        };

        const saveTaskFilesToCache = () => {
            try {
                const files = {};
                for (const [cacheKey, fileData] of taskFileCache.value.entries()) {
                    files[cacheKey] = fileData;
                }
                const data = {
                    files,
                    timestamp: Date.now()
                };
                localStorage.setItem(TASK_FILE_CACHE_KEY, JSON.stringify(data));
            } catch (error) {
                console.warn('保存任务文件缓存失败:', error);
            }
        };

        // 生成缓存键
        const getTaskFileCacheKey = (taskId, fileKey) => {
            return `${taskId}_${fileKey}`;
        };

        // 从缓存获取任务文件
        const getTaskFileFromCache = (taskId, fileKey) => {
            const cacheKey = getTaskFileCacheKey(taskId, fileKey);
            return taskFileCache.value.get(cacheKey) || null;
        };

        // 设置任务文件到缓存
        const setTaskFileToCache = (taskId, fileKey, fileData) => {
            const cacheKey = getTaskFileCacheKey(taskId, fileKey);
            taskFileCache.value.set(cacheKey, fileData);
            // 异步保存到localStorage
            setTimeout(() => {
                saveTaskFilesToCache();
            }, 100);
        };

2832
        const getTaskFileUrlFromApi = async (taskId, fileKey, filename = null) => {
LiangLiu's avatar
LiangLiu committed
2833
            let apiUrl = `/api/v1/task/input_url?task_id=${taskId}&name=${fileKey}`;
2834
2835
2836
            if (filename) {
                apiUrl += `&filename=${encodeURIComponent(filename)}`;
            }
LiangLiu's avatar
LiangLiu committed
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
            if (fileKey.includes('output')) {
                apiUrl = `/api/v1/task/result_url?task_id=${taskId}&name=${fileKey}`;
            }
            const response = await apiRequest(apiUrl);
            if (response && response.ok) {
                const data = await response.json();
                let assertUrl = data.url;
                if (assertUrl.startsWith('./assets/')) {
                    const token = localStorage.getItem('accessToken');
                    if (token) {
                        assertUrl = `${assertUrl}&token=${encodeURIComponent(token)}`;
                    }
LiangLiu's avatar
LiangLiu committed
2849
                }
2850
2851
                const cacheKey = filename ? `${fileKey}_${filename}` : fileKey;
                setTaskFileToCache(taskId, cacheKey, {
LiangLiu's avatar
LiangLiu committed
2852
2853
2854
2855
                    url: assertUrl,
                    timestamp: Date.now()
                });
                return assertUrl;
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
            } else if (response && response.status === 400) {
                // Handle directory input error (multi-person mode)
                try {
                    const errorData = await response.json();
                    if (errorData.error && errorData.error.includes('directory')) {
                        console.warn(`Input ${fileKey} is a directory (multi-person mode), cannot get single file URL`);
                        return null;
                    }
                } catch (e) {
                    // Ignore JSON parse errors
                }
            }
            return null;
        };

        // Podcast 音频 URL 缓存管理函数(模仿任务文件缓存)
        const loadPodcastAudioFromCache = () => {
            try {
                const cached = localStorage.getItem(PODCAST_AUDIO_CACHE_KEY);
                if (cached) {
                    const data = JSON.parse(cached);
                    // 检查是否过期
                    if (Date.now() - data.timestamp < PODCAST_AUDIO_CACHE_EXPIRY) {
                        // 将缓存数据加载到内存缓存中
                        for (const [cacheKey, audioData] of Object.entries(data.audio_urls)) {
                            podcastAudioCache.value.set(cacheKey, audioData);
                        }
                        podcastAudioCacheLoaded.value = true;
                        return true;
                    } else {
                        // 缓存过期,清除
                        localStorage.removeItem(PODCAST_AUDIO_CACHE_KEY);
                    }
                }
            } catch (error) {
                console.warn('加载播客音频缓存失败:', error);
                localStorage.removeItem(PODCAST_AUDIO_CACHE_KEY);
            }
            podcastAudioCacheLoaded.value = true;
            return false;
        };

        const savePodcastAudioToCache = () => {
            try {
                const audio_urls = {};
                for (const [cacheKey, audioData] of podcastAudioCache.value.entries()) {
                    audio_urls[cacheKey] = audioData;
                }
                const data = {
                    audio_urls,
                    timestamp: Date.now()
                };
                localStorage.setItem(PODCAST_AUDIO_CACHE_KEY, JSON.stringify(data));
            } catch (error) {
                console.warn('保存播客音频缓存失败:', error);
            }
        };

        // 生成播客音频缓存键
        const getPodcastAudioCacheKey = (sessionId) => {
            return sessionId;
        };

        // 从缓存获取播客音频 URL
        const getPodcastAudioFromCache = (sessionId) => {
            const cacheKey = getPodcastAudioCacheKey(sessionId);
            return podcastAudioCache.value.get(cacheKey) || null;
        };

        // 设置播客音频 URL 到缓存
        const setPodcastAudioToCache = (sessionId, audioData) => {
            const cacheKey = getPodcastAudioCacheKey(sessionId);
            podcastAudioCache.value.set(cacheKey, audioData);
            // 异步保存到localStorage
            setTimeout(() => {
                savePodcastAudioToCache();
            }, 100);
        };

        // 从 API 获取播客音频 URL(CDN URL)
        const getPodcastAudioUrlFromApi = async (sessionId) => {
            try {
                const response = await apiCall(`/api/v1/podcast/session/${sessionId}/audio_url`);
                if (response && response.ok) {
                    const data = await response.json();
                    const audioUrl = data.audio_url;
                    setPodcastAudioToCache(sessionId, {
                        url: audioUrl,
                        timestamp: Date.now()
                    });
                    return audioUrl;
                }
            } catch (error) {
                console.warn(`Failed to get audio URL for session ${sessionId}:`, error);
LiangLiu's avatar
LiangLiu committed
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
            }
            return null;
        };

        // 获取任务文件URL(优先从缓存,缓存没有则调用后端)
        const getTaskFileUrl = async (taskId, fileKey) => {
            // 先从缓存获取
            const cachedFile = getTaskFileFromCache(taskId, fileKey);
            if (cachedFile) {
                return cachedFile.url;
            }
            return await getTaskFileUrlFromApi(taskId, fileKey);
        };

        // 同步获取任务文件URL(仅从缓存获取,用于模板显示)
        const getTaskFileUrlSync = (taskId, fileKey) => {
            const cachedFile = getTaskFileFromCache(taskId, fileKey);
            if (cachedFile) {
                console.log('getTaskFileUrlSync: 从缓存获取', { taskId, fileKey, url: cachedFile.url, type: typeof cachedFile.url });
                return cachedFile.url;
            }
            console.log('getTaskFileUrlSync: 缓存中没有找到', { taskId, fileKey });
            return null;
        };
LiangLiu's avatar
LiangLiu committed
2974

LiangLiu's avatar
LiangLiu committed
2975
2976
2977
        // 预加载任务文件
        const preloadTaskFilesUrl = async (tasks) => {
            if (!tasks || tasks.length === 0) return;
LiangLiu's avatar
LiangLiu committed
2978

LiangLiu's avatar
LiangLiu committed
2979
2980
2981
2982
            // 先尝试从localStorage加载缓存
            if (taskFileCache.value.size === 0) {
                loadTaskFilesFromCache();
            }
LiangLiu's avatar
LiangLiu committed
2983

LiangLiu's avatar
LiangLiu committed
2984
            console.log(`开始获取 ${tasks.length} 个任务的文件url`);
LiangLiu's avatar
LiangLiu committed
2985

LiangLiu's avatar
LiangLiu committed
2986
2987
2988
2989
            // 分批预加载,避免过多并发请求
            const batchSize = 5;
            for (let i = 0; i < tasks.length; i += batchSize) {
                const batch = tasks.slice(i, i + batchSize);
LiangLiu's avatar
LiangLiu committed
2990

LiangLiu's avatar
LiangLiu committed
2991
2992
                const promises = batch.map(async (task) => {
                    if (!task.task_id) return;
LiangLiu's avatar
LiangLiu committed
2993

LiangLiu's avatar
LiangLiu committed
2994
2995
2996
                    // 预加载输入图片
                    if (task.inputs && task.inputs.input_image) {
                        await getTaskFileUrl(task.task_id, 'input_image');
LiangLiu's avatar
LiangLiu committed
2997
                    }
LiangLiu's avatar
LiangLiu committed
2998
2999
3000
                    // 预加载输入音频
                    if (task.inputs && task.inputs.input_audio) {
                        await getTaskFileUrl(task.task_id, 'input_audio');
LiangLiu's avatar
LiangLiu committed
3001
                    }
LiangLiu's avatar
LiangLiu committed
3002
3003
3004
                    // 预加载输出视频
                    if (task.outputs && task.outputs.output_video && task.status === 'SUCCEED') {
                        await getTaskFileUrl(task.task_id, 'output_video');
LiangLiu's avatar
LiangLiu committed
3005
                    }
LiangLiu's avatar
LiangLiu committed
3006
3007
3008
                });

                await Promise.all(promises);
LiangLiu's avatar
LiangLiu committed
3009

LiangLiu's avatar
LiangLiu committed
3010
3011
3012
                // 批次间添加延迟
                if (i + batchSize < tasks.length) {
                    await new Promise(resolve => setTimeout(resolve, 200));
LiangLiu's avatar
LiangLiu committed
3013
                }
LiangLiu's avatar
LiangLiu committed
3014
            }
LiangLiu's avatar
LiangLiu committed
3015

LiangLiu's avatar
LiangLiu committed
3016
3017
            console.log('任务文件url预加载完成');
        };
LiangLiu's avatar
LiangLiu committed
3018

LiangLiu's avatar
LiangLiu committed
3019
3020
3021
        // 预加载模板文件
        const preloadTemplateFilesUrl = async (templates) => {
            if (!templates || templates.length === 0) return;
LiangLiu's avatar
LiangLiu committed
3022

LiangLiu's avatar
LiangLiu committed
3023
3024
3025
3026
            // 先尝试从localStorage加载缓存
            if (templateFileCache.value.size === 0) {
                loadTemplateFilesFromCache();
            }
LiangLiu's avatar
LiangLiu committed
3027

LiangLiu's avatar
LiangLiu committed
3028
            console.log(`开始获取 ${templates.length} 个模板的文件url`);
LiangLiu's avatar
LiangLiu committed
3029

LiangLiu's avatar
LiangLiu committed
3030
3031
3032
3033
            // 分批预加载,避免过多并发请求
            const batchSize = 5;
            for (let i = 0; i < templates.length; i += batchSize) {
                const batch = templates.slice(i, i + batchSize);
LiangLiu's avatar
LiangLiu committed
3034

LiangLiu's avatar
LiangLiu committed
3035
3036
                const promises = batch.map(async (template) => {
                    if (!template.task_id) return;
LiangLiu's avatar
LiangLiu committed
3037

LiangLiu's avatar
LiangLiu committed
3038
3039
3040
                    // 预加载视频文件
                    if (template.outputs?.output_video) {
                        await getTemplateFileUrlAsync(template.outputs.output_video, 'videos');
LiangLiu's avatar
LiangLiu committed
3041
3042
                    }

LiangLiu's avatar
LiangLiu committed
3043
3044
3045
                    // 预加载图片文件
                    if (template.inputs?.input_image) {
                        await getTemplateFileUrlAsync(template.inputs.input_image, 'images');
LiangLiu's avatar
LiangLiu committed
3046
3047
                    }

LiangLiu's avatar
LiangLiu committed
3048
3049
3050
                    // 预加载音频文件
                    if (template.inputs?.input_audio) {
                        await getTemplateFileUrlAsync(template.inputs.input_audio, 'audios');
LiangLiu's avatar
LiangLiu committed
3051
                    }
LiangLiu's avatar
LiangLiu committed
3052
                });
LiangLiu's avatar
LiangLiu committed
3053

LiangLiu's avatar
LiangLiu committed
3054
                await Promise.all(promises);
LiangLiu's avatar
LiangLiu committed
3055

LiangLiu's avatar
LiangLiu committed
3056
3057
3058
                // 批次间添加延迟
                if (i + batchSize < templates.length) {
                    await new Promise(resolve => setTimeout(resolve, 200));
LiangLiu's avatar
LiangLiu committed
3059
                }
LiangLiu's avatar
LiangLiu committed
3060
            }
LiangLiu's avatar
LiangLiu committed
3061

LiangLiu's avatar
LiangLiu committed
3062
3063
            console.log('模板文件url预加载完成');
        };
LiangLiu's avatar
LiangLiu committed
3064

LiangLiu's avatar
LiangLiu committed
3065
3066
3067
        const refreshTasks = async (forceRefresh = false) => {
            try {
                console.log('开始刷新任务列表, forceRefresh:', forceRefresh, 'currentPage:', currentTaskPage.value);
LiangLiu's avatar
LiangLiu committed
3068

LiangLiu's avatar
LiangLiu committed
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
                // 构建缓存键,包含分页和过滤条件
                const cacheKey = `${TASKS_CACHE_KEY}_${currentTaskPage.value}_${taskPageSize.value}_${statusFilter.value}_${taskSearchQuery.value}`;

                // 如果不是强制刷新,先尝试从缓存加载
                if (!forceRefresh) {
                    const cachedTasks = loadFromCache(cacheKey, TASKS_CACHE_EXPIRY);
                    if (cachedTasks) {
                        console.log('从缓存加载任务列表');
                        tasks.value = cachedTasks.tasks || [];
                        pagination.value = cachedTasks.pagination || null;
                        // 强制触发响应式更新
                        await nextTick();
                        // 强制刷新分页组件
                        paginationKey.value++;
                        // 使用新的任务文件预加载逻辑
                        await preloadTaskFilesUrl(tasks.value);
                        return;
LiangLiu's avatar
LiangLiu committed
3086
3087
3088
                    }
                }

LiangLiu's avatar
LiangLiu committed
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
                const params = new URLSearchParams({
                    page: currentTaskPage.value.toString(),
                    page_size: taskPageSize.value.toString()
                });

                if (statusFilter.value !== 'ALL') {
                    params.append('status', statusFilter.value);
                }

                console.log('请求任务列表API:', `/api/v1/task/list?${params.toString()}`);
                const response = await apiRequest(`/api/v1/task/list?${params.toString()}`);
                if (response && response.ok) {
                    const data = await response.json();
                    console.log('任务列表API响应:', data);

                    // 强制清空并重新赋值,确保Vue检测到变化
                    tasks.value = [];
                    pagination.value = null;
                    await nextTick();

                    tasks.value = data.tasks || [];
                    pagination.value = data.pagination || null;

                    // 缓存任务数据
                    saveToCache(cacheKey, {
                        tasks: data.tasks || [],
                        pagination: data.pagination || null
LiangLiu's avatar
LiangLiu committed
3116
                    });
LiangLiu's avatar
LiangLiu committed
3117
                    console.log('缓存任务列表数据成功');
LiangLiu's avatar
LiangLiu committed
3118

LiangLiu's avatar
LiangLiu committed
3119
3120
                    // 强制触发响应式更新
                    await nextTick();
LiangLiu's avatar
LiangLiu committed
3121

LiangLiu's avatar
LiangLiu committed
3122
3123
                    // 强制刷新分页组件
                    paginationKey.value++;
LiangLiu's avatar
LiangLiu committed
3124

LiangLiu's avatar
LiangLiu committed
3125
3126
3127
                    // 使用新的任务文件预加载逻辑
                    await preloadTaskFilesUrl(tasks.value);
                } else if (response) {
3128
                    showAlert(t('refreshTaskListFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
                }
                // 如果response为null,说明是认证错误,apiRequest已经处理了
            } catch (error) {
                console.error('刷新任务列表失败:', error);
                // showAlert(`刷新任务列表失败: ${error.message}`, 'danger');
            }
        };

        // 分页相关函数
        const goToPage = async (page) => {
LiangLiu's avatar
LiangLiu committed
3139
            isPageLoading.value = true;
LiangLiu's avatar
LiangLiu committed
3140
            if (page < 1 || page > pagination.value?.total_pages || page === currentTaskPage.value) {
LiangLiu's avatar
LiangLiu committed
3141
                isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
3142
3143
3144
3145
3146
                return;
            }
            currentTaskPage.value = page;
            taskPageInput.value = page; // 同步更新输入框
            await refreshTasks();
LiangLiu's avatar
LiangLiu committed
3147
            isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
        };

        const jumpToPage = async () => {
            const page = parseInt(taskPageInput.value);
            if (page && page >= 1 && page <= pagination.value?.total_pages && page !== currentTaskPage.value) {
                await goToPage(page);
            } else {
                // 如果输入无效,恢复到当前页
                taskPageInput.value = currentTaskPage.value;
            }
        };

        // Template分页相关函数
        const goToTemplatePage = async (page) => {
LiangLiu's avatar
LiangLiu committed
3162
            isPageLoading.value=true;
LiangLiu's avatar
LiangLiu committed
3163
            if (page < 1 || page > templatePagination.value?.total_pages || page === templateCurrentPage.value) {
LiangLiu's avatar
LiangLiu committed
3164
                isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
3165
3166
3167
3168
3169
                return;
            }
            templateCurrentPage.value = page;
            templatePageInput.value = page; // 同步更新输入框
            await loadImageAudioTemplates();
LiangLiu's avatar
LiangLiu committed
3170
            isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
        };

        const jumpToTemplatePage = async () => {
            const page = parseInt(templatePageInput.value);
            if (page && page >= 1 && page <= templatePagination.value?.total_pages && page !== templateCurrentPage.value) {
                await goToTemplatePage(page);
            } else {
                // 如果输入无效,恢复到当前页
                templatePageInput.value = templateCurrentPage.value;
            }
        };
LiangLiu's avatar
LiangLiu committed
3182

LiangLiu's avatar
LiangLiu committed
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
        const getVisiblePages = () => {
            if (!pagination.value) return [];

            const totalPages = pagination.value.total_pages;
            const current = currentTaskPage.value;
            const pages = [];

            // 总是显示第一页
            pages.push(1);

            if (totalPages <= 5) {
                // 如果总页数少于等于7页,显示所有页码
                for (let i = 2; i <= totalPages - 1; i++) {
                    pages.push(i);
                }
            } else {
                // 如果总页数大于7页,使用省略号
                if (current <= 3) {
                    // 当前页在前4页
                    for (let i = 2; i <= 3; i++) {
                        pages.push(i);
LiangLiu's avatar
LiangLiu committed
3204
                    }
LiangLiu's avatar
LiangLiu committed
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
                    pages.push('...');
                } else if (current >= totalPages - 2) {
                    // 当前页在后4页
                    pages.push('...');
                    for (let i = totalPages - 2; i <= totalPages - 1; i++) {
                        pages.push(i);
                    }
                } else {
                    // 当前页在中间
                    pages.push('...');
                    for (let i = current - 1; i <= current + 1; i++) {
                        pages.push(i);
                    }
                    pages.push('...');
LiangLiu's avatar
LiangLiu committed
3219
                }
LiangLiu's avatar
LiangLiu committed
3220
            }
LiangLiu's avatar
LiangLiu committed
3221

LiangLiu's avatar
LiangLiu committed
3222
3223
3224
3225
            // 总是显示最后一页(如果不是第一页)
            if (totalPages > 1) {
                pages.push(totalPages);
            }
LiangLiu's avatar
LiangLiu committed
3226

LiangLiu's avatar
LiangLiu committed
3227
3228
            return pages;
        };
LiangLiu's avatar
LiangLiu committed
3229

LiangLiu's avatar
LiangLiu committed
3230
3231
        const getVisibleTemplatePages = () => {
            if (!templatePagination.value) return [];
LiangLiu's avatar
LiangLiu committed
3232

LiangLiu's avatar
LiangLiu committed
3233
3234
3235
            const totalPages = templatePagination.value.total_pages;
            const current = templateCurrentPage.value;
            const pages = [];
LiangLiu's avatar
LiangLiu committed
3236

LiangLiu's avatar
LiangLiu committed
3237
3238
            // 总是显示第一页
            pages.push(1);
LiangLiu's avatar
LiangLiu committed
3239

LiangLiu's avatar
LiangLiu committed
3240
3241
3242
3243
3244
3245
3246
3247
3248
            if (totalPages <= 5) {
                // 如果总页数少于等于7页,显示所有页码
                for (let i = 2; i <= totalPages - 1; i++) {
                    pages.push(i);
                }
            } else {
                // 显示当前页附近的页码
                const start = Math.max(2, current - 1);
                const end = Math.min(totalPages - 1, current + 1);
LiangLiu's avatar
LiangLiu committed
3249

LiangLiu's avatar
LiangLiu committed
3250
3251
3252
                if (start > 2) {
                    pages.push('...');
                }
LiangLiu's avatar
LiangLiu committed
3253

LiangLiu's avatar
LiangLiu committed
3254
3255
3256
3257
3258
                for (let i = start; i <= end; i++) {
                    if (i !== 1 && i !== totalPages) {
                        pages.push(i);
                    }
                }
LiangLiu's avatar
LiangLiu committed
3259

LiangLiu's avatar
LiangLiu committed
3260
3261
3262
3263
                if (end < totalPages - 1) {
                    pages.push('...');
                }
            }
LiangLiu's avatar
LiangLiu committed
3264

LiangLiu's avatar
LiangLiu committed
3265
3266
3267
3268
            // 总是显示最后一页
            if (totalPages > 1) {
                pages.push(totalPages);
            }
LiangLiu's avatar
LiangLiu committed
3269

LiangLiu's avatar
LiangLiu committed
3270
3271
            return pages;
        };
LiangLiu's avatar
LiangLiu committed
3272

LiangLiu's avatar
LiangLiu committed
3273
3274
        // 灵感广场分页相关函数
        const goToInspirationPage = async (page) => {
LiangLiu's avatar
LiangLiu committed
3275
            isPageLoading.value = true;
LiangLiu's avatar
LiangLiu committed
3276
            if (page < 1 || page > inspirationPagination.value?.total_pages || page === inspirationCurrentPage.value) {
LiangLiu's avatar
LiangLiu committed
3277
                isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
3278
3279
3280
3281
3282
                return;
            }
            inspirationCurrentPage.value = page;
            inspirationPageInput.value = page; // 同步更新输入框
            await loadInspirationData();
LiangLiu's avatar
LiangLiu committed
3283
            isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
        };

        const jumpToInspirationPage = async () => {
            const page = parseInt(inspirationPageInput.value);
            if (page && page >= 1 && page <= inspirationPagination.value?.total_pages && page !== inspirationCurrentPage.value) {
                await goToInspirationPage(page);
            } else {
                // 如果输入无效,恢复到当前页
                inspirationPageInput.value = inspirationCurrentPage.value;
            }
        };
LiangLiu's avatar
LiangLiu committed
3295

LiangLiu's avatar
LiangLiu committed
3296
3297
        const getVisibleInspirationPages = () => {
            if (!inspirationPagination.value) return [];
LiangLiu's avatar
LiangLiu committed
3298

LiangLiu's avatar
LiangLiu committed
3299
3300
3301
            const totalPages = inspirationPagination.value.total_pages;
            const current = inspirationCurrentPage.value;
            const pages = [];
LiangLiu's avatar
LiangLiu committed
3302

LiangLiu's avatar
LiangLiu committed
3303
3304
            // 总是显示第一页
            pages.push(1);
LiangLiu's avatar
LiangLiu committed
3305

LiangLiu's avatar
LiangLiu committed
3306
3307
3308
3309
3310
3311
3312
3313
3314
            if (totalPages <= 5) {
                // 如果总页数少于等于7页,显示所有页码
                for (let i = 2; i <= totalPages - 1; i++) {
                    pages.push(i);
                }
            } else {
                // 显示当前页附近的页码
                const start = Math.max(2, current - 1);
                const end = Math.min(totalPages - 1, current + 1);
LiangLiu's avatar
LiangLiu committed
3315

LiangLiu's avatar
LiangLiu committed
3316
3317
3318
                if (start > 2) {
                    pages.push('...');
                }
LiangLiu's avatar
LiangLiu committed
3319

LiangLiu's avatar
LiangLiu committed
3320
3321
3322
                for (let i = start; i <= end; i++) {
                    if (i !== 1 && i !== totalPages) {
                        pages.push(i);
LiangLiu's avatar
LiangLiu committed
3323
3324
3325
                    }
                }

LiangLiu's avatar
LiangLiu committed
3326
3327
3328
3329
                if (end < totalPages - 1) {
                    pages.push('...');
                }
            }
LiangLiu's avatar
LiangLiu committed
3330

LiangLiu's avatar
LiangLiu committed
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
            // 总是显示最后一页
            if (totalPages > 1) {
                pages.push(totalPages);
            }

            return pages;
        };

        const getStatusBadgeClass = (status) => {
            const statusMap = {
                'SUCCEED': 'bg-success',
                'FAILED': 'bg-danger',
                'RUNNING': 'bg-warning',
                'PENDING': 'bg-secondary',
                'CREATED': 'bg-secondary'
            };
            return statusMap[status] || 'bg-secondary';
        };

        const viewSingleResult = async (taskId, key) => {
            try {
                downloadLoading.value = true;
                const url = await getTaskFileUrl(taskId, key);
                if (url) {
                    const response = await fetch(url);
                    if (response.ok) {
                        const blob = await response.blob();
                        const videoBlob = new Blob([blob], { type: 'video/mp4' });
                        const url = window.URL.createObjectURL(videoBlob);
                        window.open(url, '_blank');
                    } else {
3362
                        showAlert(t('getResultFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
                    }
                } else {
                    showAlert(t('getTaskResultFailedAlert'), 'danger');
                }
            } catch (error) {
                showAlert(`${t('viewTaskResultFailedAlert')}: ${error.message}`, 'danger');
            } finally {
                downloadLoading.value = false;
            }
        };

        const cancelTask = async (taskId, fromDetailPage = false) => {
            try {
                // 显示确认对话框
                const confirmed = await showConfirmDialog({
                    title: t('cancelTaskConfirm'),
                    message: t('cancelTaskConfirmMessage'),
                    confirmText: t('confirmCancel'),
                });
LiangLiu's avatar
LiangLiu committed
3382

LiangLiu's avatar
LiangLiu committed
3383
3384
                if (!confirmed) {
                    return;
LiangLiu's avatar
LiangLiu committed
3385
                }
LiangLiu's avatar
LiangLiu committed
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406

                const response = await apiRequest(`/api/v1/task/cancel?task_id=${taskId}`);
                if (response && response.ok) {
                    showAlert(t('taskCancelSuccessAlert'), 'success');

                    // 如果当前在任务详情界面,刷新任务后关闭详情弹窗
                    if (fromDetailPage) {
                        refreshTasks(true); // 强制刷新
                        const updatedTask = tasks.value.find(t => t.task_id === taskId);
                        if (updatedTask) {
                            modalTask.value = updatedTask;
                        }
                        await nextTick();
                        closeTaskDetailModal();
                    } else {
                        refreshTasks(true); // 强制刷新
                    }

                } else if (response) {
                    const error = await response.json();
                    showAlert(`${t('cancelTaskFailedAlert')}: ${error.message}`, 'danger');
LiangLiu's avatar
LiangLiu committed
3407
                }
LiangLiu's avatar
LiangLiu committed
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
                // 如果response为null,说明是认证错误,apiRequest已经处理了
            } catch (error) {
                showAlert(`${t('cancelTaskFailedAlert')}: ${error.message}`, 'danger');
            }
        };

        const resumeTask = async (taskId, fromDetailPage = false) => {
            try {
                // 先获取任务信息,检查任务状态
                const taskResponse = await apiRequest(`/api/v1/task/query?task_id=${taskId}`);
                if (!taskResponse || !taskResponse.ok) {
                    showAlert(t('taskNotFoundAlert'), 'danger');
                    return;
LiangLiu's avatar
LiangLiu committed
3421
3422
                }

LiangLiu's avatar
LiangLiu committed
3423
3424
3425
3426
                const task = await taskResponse.json();

                // 如果任务已完成,则删除并重新生成
                if (task.status === 'SUCCEED') {
LiangLiu's avatar
LiangLiu committed
3427
3428
                    // 显示确认对话框
                    const confirmed = await showConfirmDialog({
LiangLiu's avatar
LiangLiu committed
3429
3430
3431
                        title: t('regenerateTaskConfirm'),
                        message: t('regenerateTaskConfirmMessage'),
                        confirmText: t('confirmRegenerate')
LiangLiu's avatar
LiangLiu committed
3432
3433
3434
3435
3436
3437
                    });

                    if (!confirmed) {
                        return;
                    }

LiangLiu's avatar
LiangLiu committed
3438
3439
                    // 显示重新生成中的提示
                    showAlert(t('regeneratingTaskAlert'), 'info');
LiangLiu's avatar
LiangLiu committed
3440

LiangLiu's avatar
LiangLiu committed
3441
                    const deleteResponse = await apiRequest(`/api/v1/task/delete?task_id=${taskId}`, {
LiangLiu's avatar
LiangLiu committed
3442
3443
                        method: 'DELETE'
                    });
LiangLiu's avatar
LiangLiu committed
3444
3445
3446
3447
3448
3449
3450
3451
                    if (!deleteResponse || !deleteResponse.ok) {
                        showAlert(t('deleteTaskFailedAlert'), 'danger');
                        return;
                    }
                    try {
                        // 设置任务类型
                        selectedTaskId.value = task.task_type;
                        console.log('selectedTaskId.value', selectedTaskId.value);
LiangLiu's avatar
LiangLiu committed
3452

LiangLiu's avatar
LiangLiu committed
3453
3454
                        // 获取当前表单
                        const currentForm = getCurrentForm();
LiangLiu's avatar
LiangLiu committed
3455

LiangLiu's avatar
LiangLiu committed
3456
3457
3458
                        // 设置模型
                        if (task.params && task.params.model_cls) {
                            currentForm.model_cls = task.params.model_cls;
LiangLiu's avatar
LiangLiu committed
3459
3460
                        }

LiangLiu's avatar
LiangLiu committed
3461
3462
3463
3464
                        // 设置prompt
                        if (task.params && task.params.prompt) {
                            currentForm.prompt = task.params.prompt;
                        }
LiangLiu's avatar
LiangLiu committed
3465

LiangLiu's avatar
LiangLiu committed
3466
                        // localStorage 不再保存文件内容,直接从后端获取任务文件
LiangLiu's avatar
LiangLiu committed
3467
                            try {
LiangLiu's avatar
LiangLiu committed
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
                                // 使用现有的函数获取图片和音频URL
                                const imageUrl = await getTaskInputImage(task);
                                const audioUrl = await getTaskInputAudio(task);

                                // 加载图片文件
                                if (imageUrl) {
                                    try {
                                        const imageResponse = await fetch(imageUrl);
                                        if (imageResponse && imageResponse.ok) {
                                            const blob = await imageResponse.blob();
                                            const filename = task.inputs[Object.keys(task.inputs).find(key =>
                                                key.includes('image') ||
                                                task.inputs[key].toString().toLowerCase().match(/\.(jpg|jpeg|png|gif|bmp|webp)$/)
                                            )] || 'image.jpg';
                                            const file = new File([blob], filename, { type: blob.type });
                                            currentForm.imageFile = file;
                                            setCurrentImagePreview(URL.createObjectURL(file));
LiangLiu's avatar
LiangLiu committed
3485
                                        }
LiangLiu's avatar
LiangLiu committed
3486
3487
                                    } catch (error) {
                                        console.warn('Failed to load image file:', error);
LiangLiu's avatar
LiangLiu committed
3488
3489
3490
                                    }
                                }

LiangLiu's avatar
LiangLiu committed
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
                                // 加载音频文件
                                if (audioUrl) {
                                    try {
                                        const audioResponse = await fetch(audioUrl);
                                        if (audioResponse && audioResponse.ok) {
                                            const blob = await audioResponse.blob();
                                            const filename = task.inputs[Object.keys(task.inputs).find(key =>
                                                key.includes('audio') ||
                                                task.inputs[key].toString().toLowerCase().match(/\.(mp3|wav|mp4|aac|ogg|m4a)$/)
                                            )] || 'audio.wav';

                                            // 根据文件扩展名确定正确的MIME类型
                                            let mimeType = blob.type;
                                            if (!mimeType || mimeType === 'application/octet-stream') {
                                                const ext = filename.toLowerCase().split('.').pop();
                                                const mimeTypes = {
                                                    'mp3': 'audio/mpeg',
                                                    'wav': 'audio/wav',
                                                    'mp4': 'audio/mp4',
                                                    'aac': 'audio/aac',
                                                    'ogg': 'audio/ogg',
                                                    'm4a': 'audio/mp4'
                                                };
                                                mimeType = mimeTypes[ext] || 'audio/mpeg';
                                            }

                                            const file = new File([blob], filename, { type: mimeType });
                                            currentForm.audioFile = file;
                                            console.log('复用任务 - 从后端加载音频文件:', {
                                                name: file.name,
                                                type: file.type,
                                                size: file.size,
                                                originalBlobType: blob.type
                                            });
                                            // 使用FileReader生成data URL,与正常上传保持一致
                                            const reader = new FileReader();
                                            reader.onload = (e) => {
                                                setCurrentAudioPreview(e.target.result);
                                                console.log('复用任务 - 音频预览已设置:', e.target.result.substring(0, 50) + '...');
                                            };
                                            reader.readAsDataURL(file);
LiangLiu's avatar
LiangLiu committed
3532
                                        }
LiangLiu's avatar
LiangLiu committed
3533
3534
3535
3536

                                    } catch (error) {
                                        console.warn('Failed to load audio file:', error);
                                    }
LiangLiu's avatar
LiangLiu committed
3537
3538
                                }
                            } catch (error) {
LiangLiu's avatar
LiangLiu committed
3539
                                console.warn('Failed to load task data from backend:', error);
LiangLiu's avatar
LiangLiu committed
3540
3541
                        }

LiangLiu's avatar
LiangLiu committed
3542
                        showAlert(t('taskMaterialReuseSuccessAlert'), 'success');
LiangLiu's avatar
LiangLiu committed
3543

LiangLiu's avatar
LiangLiu committed
3544
3545
3546
3547
                    } catch (error) {
                        console.error('Failed to resume task:', error);
                        showAlert(t('loadTaskDataFailedAlert'), 'danger');
                        return;
LiangLiu's avatar
LiangLiu committed
3548
                    }
LiangLiu's avatar
LiangLiu committed
3549
3550
3551
                    // 如果从详情页调用,关闭详情页
                    if (fromDetailPage) {
                        closeTaskDetailModal();
LiangLiu's avatar
LiangLiu committed
3552
3553
                    }

LiangLiu's avatar
LiangLiu committed
3554
                    submitTask();
LiangLiu's avatar
LiangLiu committed
3555
3556


LiangLiu's avatar
LiangLiu committed
3557
3558
3559
3560
3561
3562
                    return; // 不需要继续执行后续的API调用
                } else {
                    // 对于未完成的任务,使用原有的恢复逻辑
                    const response = await apiRequest(`/api/v1/task/resume?task_id=${taskId}`);
                    if (response && response.ok) {
                        showAlert(t('taskRetrySuccessAlert'), 'success');
LiangLiu's avatar
LiangLiu committed
3563

LiangLiu's avatar
LiangLiu committed
3564
3565
3566
3567
3568
3569
                        // 如果当前在任务详情界面,先刷新任务列表,然后重新获取任务信息
                        if (fromDetailPage) {
                            refreshTasks(true); // 强制刷新
                            const updatedTask = tasks.value.find(t => t.task_id === taskId);
                            if (updatedTask) {
                                selectedTask.value = updatedTask;
LiangLiu's avatar
LiangLiu committed
3570
                            }
LiangLiu's avatar
LiangLiu committed
3571
3572
3573
3574
                            startPollingTask(taskId);
                            await nextTick();
                        } else {
                            refreshTasks(true); // 强制刷新
LiangLiu's avatar
LiangLiu committed
3575

LiangLiu's avatar
LiangLiu committed
3576
3577
                            // 开始轮询新提交的任务状态
                            startPollingTask(taskId);
LiangLiu's avatar
LiangLiu committed
3578
                        }
LiangLiu's avatar
LiangLiu committed
3579
3580
3581
                    } else if (response) {
                        const error = await response.json();
                        showAlert(`${t('retryTaskFailedAlert')}: ${error.message}`, 'danger');
LiangLiu's avatar
LiangLiu committed
3582
                    }
LiangLiu's avatar
LiangLiu committed
3583
                }
LiangLiu's avatar
LiangLiu committed
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
            } catch (error) {
                console.error('resumeTask error:', error);
                showAlert(`${t('retryTaskFailedAlert')}: ${error.message}`, 'danger');
            }
        };

        // 切换任务菜单显示状态
        const toggleTaskMenu = (taskId) => {
            // 先关闭所有其他菜单
            closeAllTaskMenus();
            // 然后打开当前菜单
            taskMenuVisible.value[taskId] = true;
        };

        // 关闭所有任务菜单
        const closeAllTaskMenus = () => {
            taskMenuVisible.value = {};
        };

        // 点击外部关闭菜单
        const handleClickOutside = (event) => {
            if (!event.target.closest('.task-menu-container')) {
                closeAllTaskMenus();
            }
            if (!event.target.closest('.task-type-dropdown')) {
                showTaskTypeMenu.value = false;
            }
            if (!event.target.closest('.model-dropdown')) {
                showModelMenu.value = false;
            }
        };

        const deleteTask = async (taskId, fromDetailPage = false) => {
            try {
                // 显示确认对话框
                const confirmed = await showConfirmDialog({
                    title: t('deleteTaskConfirm'),
                    message: t('deleteTaskConfirmMessage'),
                    confirmText: t('confirmDelete')
                });
LiangLiu's avatar
LiangLiu committed
3624

LiangLiu's avatar
LiangLiu committed
3625
                if (!confirmed) {
LiangLiu's avatar
LiangLiu committed
3626
3627
                    return;
                }
LiangLiu's avatar
LiangLiu committed
3628
3629
3630
                const response = await apiRequest(`/api/v1/task/delete?task_id=${taskId}`, {
                    method: 'DELETE'
                });
LiangLiu's avatar
LiangLiu committed
3631

LiangLiu's avatar
LiangLiu committed
3632
3633
                if (response && response.ok) {
                    showAlert(t('taskDeletedSuccessAlert'), 'success');
LiangLiu's avatar
LiangLiu committed
3634
3635
3636
3637
3638
3639
3640
3641
                    const deletedTaskIndex = tasks.value.findIndex(task => task.task_id === taskId);
                    if (deletedTaskIndex !== -1) {
                        const wasCurrent = currentTask.value?.task_id === taskId;
                        tasks.value.splice(deletedTaskIndex, 1);
                        if (wasCurrent) {
                            currentTask.value = tasks.value[deletedTaskIndex] || tasks.value[deletedTaskIndex - 1] || null;
                        }
                    }
LiangLiu's avatar
LiangLiu committed
3642
                    refreshTasks(true); // 强制刷新
LiangLiu's avatar
LiangLiu committed
3643

LiangLiu's avatar
LiangLiu committed
3644
3645
3646
3647
3648
3649
                    // 如果是从任务详情页删除,删除成功后关闭详情弹窗
                    if (fromDetailPage) {
                        closeTaskDetailModal();
                        if (!selectedTaskId.value) {
                            if (availableTaskTypes.value.includes('s2v')) {
                                selectTask('s2v');
LiangLiu's avatar
LiangLiu committed
3650
3651
3652
                            }
                        }
                    }
LiangLiu's avatar
LiangLiu committed
3653
3654
3655
3656
3657
3658
3659
3660
3661
                } else if (response) {
                    const error = await response.json();
                    showAlert(`${t('deleteTaskFailedAlert')}: ${error.message}`, 'danger');
                }
                // 如果response为null,说明是认证错误,apiRequest已经处理了
            } catch (error) {
                showAlert(`${t('deleteTaskFailedAlert')}: ${error.message}`, 'danger');
            }
        };
LiangLiu's avatar
LiangLiu committed
3662

LiangLiu's avatar
LiangLiu committed
3663
3664
3665
        const loadTaskFiles = async (task) => {
            try {
                loadingTaskFiles.value = true;
LiangLiu's avatar
LiangLiu committed
3666

LiangLiu's avatar
LiangLiu committed
3667
                const files = { inputs: {}, outputs: {} };
LiangLiu's avatar
LiangLiu committed
3668

LiangLiu's avatar
LiangLiu committed
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
                // 获取输入文件(所有状态的任务都需要)
                if (task.inputs) {
                    for (const [key, inputPath] of Object.entries(task.inputs)) {
                        try {
                            const url = await getTaskFileUrl(taskId, key);
                            if (url) {
                                const response = await fetch(url);
                                if (response && response.ok) {
                                    const blob = await response.blob()
                                    files.inputs[key] = {
                                        name: inputPath, // 使用原始文件名而不是key
                                        path: inputPath,
                                        blob: blob,
                                        url: URL.createObjectURL(blob)
                                    }
LiangLiu's avatar
LiangLiu committed
3684
3685
                                }
                            }
LiangLiu's avatar
LiangLiu committed
3686
3687
3688
3689
3690
3691
3692
                        } catch (error) {
                            console.error(`Failed to load input ${key}:`, error);
                            files.inputs[key] = {
                                name: inputPath, // 使用原始文件名而不是key
                                path: inputPath,
                                error: true
                            };
LiangLiu's avatar
LiangLiu committed
3693
3694
                        }
                    }
LiangLiu's avatar
LiangLiu committed
3695
3696
                }

LiangLiu's avatar
LiangLiu committed
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
                // 只对成功完成的任务获取输出文件
                if (task.status === 'SUCCEED' && task.outputs) {
                    for (const [key, outputPath] of Object.entries(task.outputs)) {
                        try {
                            const url = await getTaskFileUrl(taskId, key);
                            if (url) {
                                const response = await fetch(url);
                                if (response && response.ok) {
                                    const blob = await response.blob()
                                    files.outputs[key] = {
                                        name: outputPath, // 使用原始文件名而不是key
                                        path: outputPath,
                                        blob: blob,
                                        url: URL.createObjectURL(blob)
                                    }
                                };
                            }
                        } catch (error) {
                            console.error(`Failed to load output ${key}:`, error);
                            files.outputs[key] = {
                                name: outputPath, // 使用原始文件名而不是key
                                path: outputPath,
                                error: true
                            };
                        }
LiangLiu's avatar
LiangLiu committed
3722
3723
3724
                    }
                }

LiangLiu's avatar
LiangLiu committed
3725
                selectedTaskFiles.value = files;
LiangLiu's avatar
LiangLiu committed
3726

LiangLiu's avatar
LiangLiu committed
3727
3728
3729
3730
3731
3732
3733
            } catch (error) {
                console.error('Failed to load task files: task_id=', taskId, error);
                showAlert(t('loadTaskFilesFailedAlert'), 'danger');
            } finally {
                loadingTaskFiles.value = false;
            }
        };
LiangLiu's avatar
LiangLiu committed
3734

LiangLiu's avatar
LiangLiu committed
3735
        const reuseTask = async (task) => {
LiangLiu's avatar
LiangLiu committed
3736
3737
3738
3739
3740
            if (!task) {
                showAlert(t('loadTaskDataFailedAlert'), 'danger');
                return;
            }

LiangLiu's avatar
LiangLiu committed
3741
            try {
LiangLiu's avatar
LiangLiu committed
3742
3743
                templateLoading.value = true;
                templateLoadingMessage.value = t('prefillLoadingTask');
LiangLiu's avatar
LiangLiu committed
3744
                // 跳转到任务创建界面
LiangLiu's avatar
LiangLiu committed
3745
                isCreationAreaExpanded.value = true;
LiangLiu's avatar
LiangLiu committed
3746
3747
3748
                if (showTaskDetailModal.value) {
                    closeTaskDetailModal();
                }
LiangLiu's avatar
LiangLiu committed
3749

LiangLiu's avatar
LiangLiu committed
3750
3751
3752
3753
3754
3755
                // 设置任务类型
                selectedTaskId.value = task.task_type;
                console.log('selectedTaskId.value', selectedTaskId.value);

                // 获取当前表单
                const currentForm = getCurrentForm();
LiangLiu's avatar
LiangLiu committed
3756

LiangLiu's avatar
LiangLiu committed
3757
3758
3759
                // 立即切换到创建视图,后续资产异步加载
                switchToCreateView();

LiangLiu's avatar
LiangLiu committed
3760
3761
3762
                // 设置模型
                if (task.params && task.params.model_cls) {
                    currentForm.model_cls = task.params.model_cls;
LiangLiu's avatar
LiangLiu committed
3763
3764
                }

LiangLiu's avatar
LiangLiu committed
3765
3766
3767
                // 设置prompt
                if (task.params && task.params.prompt) {
                    currentForm.prompt = task.params.prompt;
LiangLiu's avatar
LiangLiu committed
3768
3769
                }

LiangLiu's avatar
LiangLiu committed
3770
3771
3772
3773
3774
                // localStorage 不再保存文件内容,直接从后端获取任务文件
                    try {
                        // 使用现有的函数获取图片和音频URL
                        const imageUrl = await getTaskInputImage(task);
                        const audioUrl = await getTaskInputAudio(task);
LiangLiu's avatar
LiangLiu committed
3775

LiangLiu's avatar
LiangLiu committed
3776
3777
3778
3779
3780
3781

                        // 加载音频文件
                        if (audioUrl) {
                            try {
                                const audioResponse = await fetch(audioUrl);
                                if (audioResponse && audioResponse.ok) {
3782
3783
3784
3785
3786
3787
3788
                                    // Check if the response is an error (for directory inputs)
                                    const contentType = audioResponse.headers.get('content-type');
                                    if (contentType && contentType.includes('application/json')) {
                                        const errorData = await audioResponse.json();
                                            // Not a directory error, proceed with normal loading
                                            currentForm.audioUrl = audioUrl;
                                            setCurrentAudioPreview(audioUrl);
LiangLiu's avatar
LiangLiu committed
3789

3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
                                            const blob = await audioResponse.blob();
                                            const filename = task.inputs[Object.keys(task.inputs).find(key =>
                                                key.includes('audio') ||
                                                task.inputs[key].toString().toLowerCase().match(/\.(mp3|wav|mp4|aac|ogg|m4a)$/)
                                            )] || 'audio.wav';

                                            // 根据文件扩展名确定正确的MIME类型
                                            let mimeType = blob.type;
                                            if (!mimeType || mimeType === 'application/octet-stream') {
                                                const ext = filename.toLowerCase().split('.').pop();
                                                const mimeTypes = {
                                                    'mp3': 'audio/mpeg',
                                                    'wav': 'audio/wav',
                                                    'mp4': 'audio/mp4',
                                                    'aac': 'audio/aac',
                                                    'ogg': 'audio/ogg',
                                                    'm4a': 'audio/mp4'
                                                };
                                                mimeType = mimeTypes[ext] || 'audio/mpeg';
                                            }

                                            const file = new File([blob], filename, { type: mimeType });
                                            currentForm.audioFile = file;
                                            console.log('复用任务 - 从后端加载音频文件:', {
                                                name: file.name,
                                                type: file.type,
                                                size: file.size,
                                                originalBlobType: blob.type
                                            });
                                    } else {
                                        // Normal audio file response
                                        currentForm.audioUrl = audioUrl;
                                        setCurrentAudioPreview(audioUrl);

                                        const blob = await audioResponse.blob();
                                        const filename = task.inputs[Object.keys(task.inputs).find(key =>
                                            key.includes('audio') ||
                                            task.inputs[key].toString().toLowerCase().match(/\.(mp3|wav|mp4|aac|ogg|m4a)$/)
                                        )] || 'audio.wav';

                                        // 根据文件扩展名确定正确的MIME类型
                                        let mimeType = blob.type;
                                        if (!mimeType || mimeType === 'application/octet-stream') {
                                            const ext = filename.toLowerCase().split('.').pop();
                                            const mimeTypes = {
                                                'mp3': 'audio/mpeg',
                                                'wav': 'audio/wav',
                                                'mp4': 'audio/mp4',
                                                'aac': 'audio/aac',
                                                'ogg': 'audio/ogg',
                                                'm4a': 'audio/mp4'
                                            };
                                            mimeType = mimeTypes[ext] || 'audio/mpeg';
                                        }

                                        const file = new File([blob], filename, { type: mimeType });
                                        currentForm.audioFile = file;
                                        console.log('复用任务 - 从后端加载音频文件:', {
                                            name: file.name,
                                            type: file.type,
                                            size: file.size,
                                            originalBlobType: blob.type
                                        });
                                    }
LiangLiu's avatar
LiangLiu committed
3854
3855
3856
3857
3858
                                }
                            } catch (error) {
                                console.warn('Failed to load audio file:', error);
                            }
                        }
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887

                                                // 加载图片文件
                                                if (imageUrl) {
                                                    try {
                                                        const imageResponse = await fetch(imageUrl);
                                                        if (imageResponse && imageResponse.ok) {
                                                            const blob = await imageResponse.blob();
                                                            const filename = task.inputs[Object.keys(task.inputs).find(key =>
                                                                key.includes('image') ||
                                                                task.inputs[key].toString().toLowerCase().match(/\.(jpg|jpeg|png|gif|bmp|webp)$/)
                                                            )] || 'image.jpg';
                                                            const file = new File([blob], filename, { type: blob.type });
                                                            currentForm.imageFile = file;
                                                            const imagePreviewUrl = URL.createObjectURL(file);
                                                            setCurrentImagePreview(imageUrl);

                                                            // Reset detected faces
                                                            if (selectedTaskId.value === 'i2v') {
                                                                i2vForm.value.detectedFaces = [];
                                                            } else if (selectedTaskId.value === 's2v') {
                                                                s2vForm.value.detectedFaces = [];
                                                            }

                                                            // 不再自动检测人脸,等待用户手动打开多角色模式开关
                                                        }
                                                    } catch (error) {
                                                        console.warn('Failed to load image file:', error);
                                                    }
                                                }
LiangLiu's avatar
LiangLiu committed
3888
3889
                    } catch (error) {
                        console.warn('Failed to load task data from backend:', error);
LiangLiu's avatar
LiangLiu committed
3890
3891
                }

LiangLiu's avatar
LiangLiu committed
3892
                showAlert(t('taskMaterialReuseSuccessAlert'), 'success');
LiangLiu's avatar
LiangLiu committed
3893

LiangLiu's avatar
LiangLiu committed
3894
3895
3896
            } catch (error) {
                console.error('Failed to reuse task:', error);
                showAlert(t('loadTaskDataFailedAlert'), 'danger');
LiangLiu's avatar
LiangLiu committed
3897
3898
3899
            } finally {
                templateLoading.value = false;
                templateLoadingMessage.value = '';
LiangLiu's avatar
LiangLiu committed
3900
3901
            }
        };
LiangLiu's avatar
LiangLiu committed
3902

LiangLiu's avatar
LiangLiu committed
3903
        const downloadFile = async (fileInfo) => {
LiangLiu's avatar
LiangLiu committed
3904
3905
            if (!fileInfo || !fileInfo.blob) {
                showAlert(t('fileUnavailableAlert'), 'danger');
LiangLiu's avatar
LiangLiu committed
3906
3907
3908
3909
3910
3911
                return false;
            }

            const blob = fileInfo.blob;
            const fileName = fileInfo.name || 'download';
            const mimeType = blob.type || fileInfo.mimeType || 'application/octet-stream';
LiangLiu's avatar
LiangLiu committed
3912

LiangLiu's avatar
LiangLiu committed
3913
            try {
LiangLiu's avatar
LiangLiu committed
3914
                const objectUrl = URL.createObjectURL(blob);
LiangLiu's avatar
LiangLiu committed
3915
                const a = document.createElement('a');
LiangLiu's avatar
LiangLiu committed
3916
3917
                a.href = objectUrl;
                a.download = fileName;
LiangLiu's avatar
LiangLiu committed
3918
3919
3920
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
LiangLiu's avatar
LiangLiu committed
3921
                URL.revokeObjectURL(objectUrl);
LiangLiu's avatar
LiangLiu committed
3922
                showAlert(t('downloadSuccessAlert'), 'success');
LiangLiu's avatar
LiangLiu committed
3923
                return true;
LiangLiu's avatar
LiangLiu committed
3924
3925
3926
            } catch (error) {
                console.error('Download failed:', error);
                showAlert(t('downloadFailedAlert'), 'danger');
LiangLiu's avatar
LiangLiu committed
3927
                return false;
LiangLiu's avatar
LiangLiu committed
3928
3929
            }
        };
LiangLiu's avatar
LiangLiu committed
3930

LiangLiu's avatar
LiangLiu committed
3931
3932
        // 处理文件下载
        const handleDownloadFile = async (taskId, fileKey, fileName) => {
LiangLiu's avatar
LiangLiu committed
3933
3934
3935
3936
3937
3938
3939
3940
            if (downloadLoading.value) {
                showAlert(t('downloadInProgressNotice'), 'info');
                return;
            }

            downloadLoading.value = true;
            downloadLoadingMessage.value = t('downloadPreparing');

LiangLiu's avatar
LiangLiu committed
3941
            try {
LiangLiu's avatar
LiangLiu committed
3942
                console.log('开始下载文件:', { taskId, fileKey, fileName });
LiangLiu's avatar
LiangLiu committed
3943

LiangLiu's avatar
LiangLiu committed
3944
                // 处理文件名,确保有正确的后缀名
LiangLiu's avatar
LiangLiu committed
3945
                let finalFileName = fileName;
LiangLiu's avatar
LiangLiu committed
3946
                if (fileName && typeof fileName === 'string') {
LiangLiu's avatar
LiangLiu committed
3947
                    const hasExtension = /\.[a-zA-Z0-9]+$/.test(fileName);
LiangLiu's avatar
LiangLiu committed
3948
                    if (!hasExtension) {
LiangLiu's avatar
LiangLiu committed
3949
3950
3951
                        const extension = getFileExtension(fileKey);
                        finalFileName = `${fileName}.${extension}`;
                        console.log('添加后缀名:', finalFileName);
LiangLiu's avatar
LiangLiu committed
3952
3953
                    }
                } else {
LiangLiu's avatar
LiangLiu committed
3954
                    finalFileName = `${fileKey}.${getFileExtension(fileKey)}`;
LiangLiu's avatar
LiangLiu committed
3955
3956
                }

LiangLiu's avatar
LiangLiu committed
3957
                downloadLoadingMessage.value = t('downloadFetching');
LiangLiu's avatar
LiangLiu committed
3958

LiangLiu's avatar
LiangLiu committed
3959
                let downloadUrl = null;
LiangLiu's avatar
LiangLiu committed
3960

LiangLiu's avatar
LiangLiu committed
3961
3962
3963
                const cachedData = getTaskFileFromCache(taskId, fileKey);
                if (cachedData?.url) {
                    downloadUrl = cachedData.url;
LiangLiu's avatar
LiangLiu committed
3964
3965
                }

LiangLiu's avatar
LiangLiu committed
3966
3967
3968
                if (!downloadUrl) {
                    downloadUrl = await getTaskFileUrl(taskId, fileKey);
                }
LiangLiu's avatar
LiangLiu committed
3969

LiangLiu's avatar
LiangLiu committed
3970
3971
3972
                if (!downloadUrl) {
                    throw new Error('无法获取文件URL');
                }
LiangLiu's avatar
LiangLiu committed
3973

LiangLiu's avatar
LiangLiu committed
3974
3975
3976
3977
                const response = await fetch(downloadUrl);
                if (!response.ok) {
                    throw new Error(`文件响应失败: ${response.status}`);
                }
LiangLiu's avatar
LiangLiu committed
3978

LiangLiu's avatar
LiangLiu committed
3979
3980
3981
3982
3983
3984
3985
                const blob = await response.blob();
                downloadLoadingMessage.value = t('downloadSaving');
                await downloadFile({
                    blob,
                    name: finalFileName,
                    mimeType: blob.type
                });
LiangLiu's avatar
LiangLiu committed
3986
            } catch (error) {
LiangLiu's avatar
LiangLiu committed
3987
3988
3989
3990
3991
                console.error('下载失败:', error);
                showAlert(t('downloadFailedAlert'), 'danger');
            } finally {
                downloadLoading.value = false;
                downloadLoadingMessage.value = '';
LiangLiu's avatar
LiangLiu committed
3992
3993
            }
        }
LiangLiu's avatar
LiangLiu committed
3994

LiangLiu's avatar
LiangLiu committed
3995
3996
3997
3998
3999
        const viewFile = (fileInfo) => {
            if (!fileInfo || !fileInfo.url) {
                showAlert(t('fileUnavailableAlert'), 'danger');
                return;
            }
LiangLiu's avatar
LiangLiu committed
4000

LiangLiu's avatar
LiangLiu committed
4001
4002
4003
            // 在新窗口中打开文件
            window.open(fileInfo.url, '_blank');
        };
LiangLiu's avatar
LiangLiu committed
4004

LiangLiu's avatar
LiangLiu committed
4005
4006
4007
4008
4009
        const clearTaskFiles = () => {
            // 清理 URL 对象,释放内存
            Object.values(selectedTaskFiles.value.inputs).forEach(file => {
                if (file.url) {
                    URL.revokeObjectURL(file.url);
LiangLiu's avatar
LiangLiu committed
4010
4011
                }
            });
LiangLiu's avatar
LiangLiu committed
4012
4013
4014
            Object.values(selectedTaskFiles.value.outputs).forEach(file => {
                if (file.url) {
                    URL.revokeObjectURL(file.url);
LiangLiu's avatar
LiangLiu committed
4015
4016
                }
            });
LiangLiu's avatar
LiangLiu committed
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
            selectedTaskFiles.value = { inputs: {}, outputs: {} };
        };

        const showTaskCreator = () => {
            selectedTask.value = null;
            // clearTaskFiles(); // 清空文件缓存
            selectedTaskId.value = 's2v'; // 默认选择数字人任务

            // 停止所有任务状态轮询
            pollingTasks.value.clear();
            if (pollingInterval.value) {
                clearInterval(pollingInterval.value);
                pollingInterval.value = null;
            }
        };
LiangLiu's avatar
LiangLiu committed
4032

LiangLiu's avatar
LiangLiu committed
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
        const toggleSidebar = () => {
            sidebarCollapsed.value = !sidebarCollapsed.value;

            if (sidebarCollapsed.value) {
                // 收起时,将历史任务栏隐藏到屏幕左侧
                if (sidebar.value) {
                    sidebar.value.style.transform = 'translateX(-100%)';
                }
            } else {
                // 展开时,恢复历史任务栏位置
                if (sidebar.value) {
                    sidebar.value.style.transform = 'translateX(0)';
LiangLiu's avatar
LiangLiu committed
4045
                }
LiangLiu's avatar
LiangLiu committed
4046
            }
LiangLiu's avatar
LiangLiu committed
4047

LiangLiu's avatar
LiangLiu committed
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
            // 更新悬浮按钮位置
            updateFloatingButtonPosition(sidebarWidth.value);
        };

        const clearPrompt = () => {
            getCurrentForm().prompt = '';
            updateUploadedContentStatus();
        };

        const getTaskItemClass = (status) => {
            if (status === 'SUCCEED') return 'bg-laser-purple/15 border border-laser-purple/30';
            if (status === 'RUNNING') return 'bg-laser-purple/15 border border-laser-purple/30';
            if (status === 'FAILED') return 'bg-red-500/15 border border-red-500/30';
            return 'bg-dark-light border border-gray-700';
        };

        const getStatusIndicatorClass = (status) => {
        const base = 'inline-block w-2 aspect-square rounded-full shrink-0 align-middle';
            if (status === 'SUCCEED')
                return `${base} bg-gradient-to-r from-emerald-200 to-green-300 shadow-md shadow-emerald-300/30`;
            if (status === 'RUNNING')
                return `${base} bg-gradient-to-r from-amber-200 to-yellow-300 shadow-md shadow-amber-300/30 animate-pulse`;
            if (status === 'FAILED')
                return `${base} bg-gradient-to-r from-red-200 to-pink-300 shadow-md shadow-red-300/30`;
            return `${base} bg-gradient-to-r from-gray-200 to-gray-300 shadow-md shadow-gray-300/30`;
            };

        const getTaskTypeBtnClass = (taskType) => {
            if (selectedTaskId.value === taskType) {
                return 'text-gradient-icon border-b-2 border-laser-purple';
            }
            return 'text-gray-400 hover:text-gradient-icon';
        };
LiangLiu's avatar
LiangLiu committed
4081

LiangLiu's avatar
LiangLiu committed
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
        const getModelBtnClass = (model) => {
            if (getCurrentForm().model_cls === model) {
                return 'bg-laser-purple/20 border border-laser-purple/40 active shadow-laser';
            }
            return 'bg-dark-light border border-gray-700 hover:bg-laser-purple/15 hover:border-laser-purple/40 transition-all hover:shadow-laser';
        };

        const getTaskTypeIcon = (taskType) => {
            const iconMap = {
                't2v': 'fas fa-font',  // 文字A形图标
                'i2v': 'fas fa-image',     // 图像图标
4093
4094
                's2v': 'fas fa-user', // 人物图标
                'animate': 'fi fi-br-running text-lg' // 角色替换图标
LiangLiu's avatar
LiangLiu committed
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
            };
            return iconMap[taskType] || 'fas fa-video';
        };

        const getTaskTypeName = (task) => {
            // 如果传入的是字符串,直接返回映射
            if (!task) {
                return '未知';
            }
            if (typeof task === 'string') {
                return nameMap.value[task] || task;
            }
LiangLiu's avatar
LiangLiu committed
4107

LiangLiu's avatar
LiangLiu committed
4108
4109
4110
            // 如果传入的是任务对象,根据模型类型判断
            if (task && task.model_cls) {
                const modelCls = task.model_cls.toLowerCase();
LiangLiu's avatar
LiangLiu committed
4111

LiangLiu's avatar
LiangLiu committed
4112
4113
                return nameMap.value[task.task_type] || task.task_type;
            }
LiangLiu's avatar
LiangLiu committed
4114

LiangLiu's avatar
LiangLiu committed
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
            // 默认返回task_type
            return task.task_type || '未知';
        };

        const getPromptPlaceholder = () => {
            if (selectedTaskId.value === 't2v') {
                return t('pleaseEnterThePromptForVideoGeneration') + ''+ t('describeTheContentStyleSceneOfTheVideo');
            } else if (selectedTaskId.value === 'i2v') {
                return t('pleaseEnterThePromptForVideoGeneration') + ''+ t('describeTheContentActionRequirementsBasedOnTheImage');
            } else if (selectedTaskId.value === 's2v') {
                return t('optional') + ' '+ t('pleaseEnterThePromptForVideoGeneration') + ''+ t('describeTheDigitalHumanImageBackgroundStyleActionRequirements');
4126
4127
            } else if (selectedTaskId.value === 'animate') {
                return t('optional') + ' '+ t('pleaseEnterThePromptForVideoGeneration') + ''+ t('describeTheContentActionRequirementsBasedOnTheImage');
LiangLiu's avatar
LiangLiu committed
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
            }
            return t('pleaseEnterThePromptForVideoGeneration') + '...';
        };

        const getStatusTextClass = (status) => {
            if (status === 'SUCCEED') return 'text-emerald-400';
            if (status === 'CREATED') return 'text-blue-400';
            if (status === 'PENDING') return 'text-yellow-400';
            if (status === 'RUNNING') return 'text-amber-400';
            if (status === 'FAILED') return 'text-red-400';
            if (status === 'CANCEL') return 'text-gray-400';
            return 'text-gray-400';
        };

        const getImagePreview = (base64Data) => {
            if (!base64Data) return '';
            return `data:image/jpeg;base64,${base64Data}`;
        };

        const getTaskInputUrl = async (taskId, key) => {
            // 优先从缓存获取
            const cachedUrl = getTaskFileUrlSync(taskId, key);
            if (cachedUrl) {
                console.log('getTaskInputUrl: 从缓存获取', { taskId, key, url: cachedUrl });
                return cachedUrl;
            }
            return await getTaskFileUrlFromApi(taskId, key);
        };
LiangLiu's avatar
LiangLiu committed
4156

LiangLiu's avatar
LiangLiu committed
4157
        const getTaskInputImage = async (task) => {
LiangLiu's avatar
LiangLiu committed
4158

LiangLiu's avatar
LiangLiu committed
4159
4160
4161
4162
            if (!task || !task.inputs) {
                console.log('getTaskInputImage: 任务或输入为空', { task: task?.task_id, inputs: task?.inputs });
                return null;
            }
LiangLiu's avatar
LiangLiu committed
4163

LiangLiu's avatar
LiangLiu committed
4164
4165
4166
4167
            const imageInputs = Object.keys(task.inputs).filter(key =>
                key.includes('image') ||
                task.inputs[key].toString().toLowerCase().match(/\.(jpg|jpeg|png|gif|bmp|webp)$/)
            );
LiangLiu's avatar
LiangLiu committed
4168

LiangLiu's avatar
LiangLiu committed
4169
4170
4171
4172
4173
4174
4175
            if (imageInputs.length > 0) {
                const firstImageKey = imageInputs[0];
                // 优先从缓存获取
                const cachedUrl = getTaskFileUrlSync(task.task_id, firstImageKey);
                if (cachedUrl) {
                    console.log('getTaskInputImage: 从缓存获取', { taskId: task.task_id, key: firstImageKey, url: cachedUrl });
                    return cachedUrl;
LiangLiu's avatar
LiangLiu committed
4176
                }
LiangLiu's avatar
LiangLiu committed
4177
4178
4179
4180
4181
                // 缓存没有则生成URL
                const url = await getTaskInputUrl(task.task_id, firstImageKey);
                console.log('getTaskInputImage: 生成URL', { taskId: task.task_id, key: firstImageKey, url });
                return url;
            }
LiangLiu's avatar
LiangLiu committed
4182

LiangLiu's avatar
LiangLiu committed
4183
4184
4185
            console.log('getTaskInputImage: 没有找到图片输入');
            return null;
        };
LiangLiu's avatar
LiangLiu committed
4186

LiangLiu's avatar
LiangLiu committed
4187
4188
        const getTaskInputAudio = async (task) => {
            if (!task || !task.inputs) return null;
LiangLiu's avatar
LiangLiu committed
4189

4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
            // Directly use 'input_audio' key
            const audioKey = 'input_audio';
            if (!task.inputs[audioKey]) return null;

            // Always bypass cache and check API directly to detect directory type
            // This ensures we get the correct URL even if cache has invalid data
            let url = await getTaskFileUrlFromApi(task.task_id, audioKey);

            // If it's a directory (multi-person mode) or URL is null, try to get original_audio file
            if (!url) {
                console.log(`Audio input ${audioKey} is a directory (multi-person mode), trying to get original_audio file`);
                // Try to get original_audio file from directory
                // Try common extensions
                const extensions = ['wav', 'mp3', 'mp4', 'aac', 'ogg', 'm4a'];
                for (const ext of extensions) {
                    const originalAudioFilename = `original_audio.${ext}`;
                    url = await getTaskFileUrlFromApi(task.task_id, audioKey, originalAudioFilename);
                    if (url) {
                        console.log(`Found original audio file: ${originalAudioFilename}`);
                        break;
                    }
                }
LiangLiu's avatar
LiangLiu committed
4212
            }
LiangLiu's avatar
LiangLiu committed
4213

4214
            return url;
LiangLiu's avatar
LiangLiu committed
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
        };

        const handleThumbnailError = (event) => {
            // 当输入图片加载失败时,显示默认图标
            const img = event.target;
            const parent = img.parentElement;
            parent.innerHTML = '<div class="w-full h-44 bg-laser-purple/20 flex items-center justify-center"><i class="fas fa-video text-gradient-icon text-xl"></i></div>';
        };

        const handleImageError = (event) => {
            // 当图片加载失败时,隐藏图片,显示文件名
            const img = event.target;
            img.style.display = 'none';
            // 文件名已经显示,不需要额外处理
        };

        const handleImageLoad = (event) => {
            // 当图片加载成功时,显示图片和下载按钮,隐藏文件名
            const img = event.target;
            img.style.display = 'block';
            // 显示下载按钮
            const downloadBtn = img.parentElement.querySelector('button');
            if (downloadBtn) {
                downloadBtn.style.display = 'block';
            }
            // 隐藏文件名span
            const span = img.parentElement.parentElement.querySelector('span');
            if (span) {
                span.style.display = 'none';
            }
        };

        const handleAudioError = (event) => {
            // 当音频加载失败时,隐藏音频控件和下载按钮,显示文件名
            const audio = event.target;
            audio.style.display = 'none';
            // 隐藏下载按钮
            const downloadBtn = audio.parentElement.querySelector('button');
            if (downloadBtn) {
                downloadBtn.style.display = 'none';
            }
            // 文件名已经显示,不需要额外处理
        };

        const handleAudioLoad = (event) => {
            // 当音频加载成功时,显示音频控件和下载按钮,隐藏文件名
            const audio = event.target;
            audio.style.display = 'block';
            // 显示下载按钮
            const downloadBtn = audio.parentElement.querySelector('button');
            if (downloadBtn) {
                downloadBtn.style.display = 'block';
            }
            // 隐藏文件名span
            const span = audio.parentElement.parentElement.querySelector('span');
            if (span) {
                span.style.display = 'none';
            }
        };
LiangLiu's avatar
LiangLiu committed
4274

LiangLiu's avatar
LiangLiu committed
4275
4276
4277
4278
        // 监听currentPage变化,同步更新pageInput
        watch(currentTaskPage, (newPage) => {
            taskPageInput.value = newPage;
        });
LiangLiu's avatar
LiangLiu committed
4279

LiangLiu's avatar
LiangLiu committed
4280
4281
4282
4283
4284
4285
4286
        // 监听pagination变化,确保分页组件更新
        watch(pagination, (newPagination) => {
            console.log('pagination变化:', newPagination);
            if (newPagination && newPagination.total_pages) {
                // 确保当前页不超过总页数
                if (currentTaskPage.value > newPagination.total_pages) {
                    currentTaskPage.value = newPagination.total_pages;
LiangLiu's avatar
LiangLiu committed
4287
                }
LiangLiu's avatar
LiangLiu committed
4288
4289
            }
        }, { deep: true });
LiangLiu's avatar
LiangLiu committed
4290

LiangLiu's avatar
LiangLiu committed
4291
4292
4293
4294
        // 监听templateCurrentPage变化,同步更新templatePageInput
        watch(templateCurrentPage, (newPage) => {
            templatePageInput.value = newPage;
        });
LiangLiu's avatar
LiangLiu committed
4295

LiangLiu's avatar
LiangLiu committed
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
        // 监听templatePagination变化,确保分页组件更新
        watch(templatePagination, (newPagination) => {
            console.log('templatePagination变化:', newPagination);
            if (newPagination && newPagination.total_pages) {
                // 确保当前页不超过总页数
                if (templateCurrentPage.value > newPagination.total_pages) {
                    templateCurrentPage.value = newPagination.total_pages;
                }
            }
        }, { deep: true });
LiangLiu's avatar
LiangLiu committed
4306

LiangLiu's avatar
LiangLiu committed
4307
4308
4309
4310
        // 监听inspirationCurrentPage变化,同步更新inspirationPageInput
        watch(inspirationCurrentPage, (newPage) => {
            inspirationPageInput.value = newPage;
        });
LiangLiu's avatar
LiangLiu committed
4311

LiangLiu's avatar
LiangLiu committed
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
        // 监听inspirationPagination变化,确保分页组件更新
        watch(inspirationPagination, (newPagination) => {
            console.log('inspirationPagination变化:', newPagination);
            if (newPagination && newPagination.total_pages) {
                // 确保当前页不超过总页数
                if (inspirationCurrentPage.value > newPagination.total_pages) {
                    inspirationCurrentPage.value = newPagination.total_pages;
                }
            }
        }, { deep: true });
LiangLiu's avatar
LiangLiu committed
4322

LiangLiu's avatar
LiangLiu committed
4323
4324
4325
4326
4327
        // 统一的初始化函数
        const init = async () => {
            try {
                // 0. 初始化主题
                initTheme();
LiangLiu's avatar
LiangLiu committed
4328

LiangLiu's avatar
LiangLiu committed
4329
4330
                // 1. 加载模型和任务数据
                await loadModels();
LiangLiu's avatar
LiangLiu committed
4331

4332
4333
4334
4335
4336
                // 2. 从路由恢复或设置默认值
                const routeQuery = router.currentRoute.value?.query || {};
                const routeTaskType = routeQuery.taskType;
                const routeModel = routeQuery.model;
                const routeExpanded = routeQuery.expanded;
LiangLiu's avatar
LiangLiu committed
4337

4338
4339
4340
                if (routeTaskType && availableTaskTypes.value.includes(routeTaskType)) {
                    // 路由中有 taskType,恢复它
                    selectTask(routeTaskType);
LiangLiu's avatar
LiangLiu committed
4341

4342
4343
4344
4345
4346
4347
4348
4349
4350
                    if (routeModel && availableModelClasses.value.includes(routeModel)) {
                        // 路由中有 model,恢复它(会自动设置 stage)
                        selectModel(routeModel);
                    } else {
                        // 路由中没有 model 或 model 无效,选择第一个模型
                        const firstModel = availableModelClasses.value[0];
                        if (firstModel) {
                            selectModel(firstModel);
                        }
LiangLiu's avatar
LiangLiu committed
4351
                    }
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
                } else {
                    // 路由中没有 taskType,设置默认值:s2v
                    const defaultTaskType = availableTaskTypes.value.includes('s2v') ? 's2v' : availableTaskTypes.value[0];
                    if (defaultTaskType) {
                        selectTask(defaultTaskType);

                        // 选择该任务下的第一个模型
                        const firstModel = availableModelClasses.value[0];
                        if (firstModel) {
                            selectModel(firstModel);
                        }
                    }
                }

                // 3. 恢复 expanded 状态(如果路由中有)
                if (routeExpanded === 'true') {
                    expandCreationArea();
LiangLiu's avatar
LiangLiu committed
4369
                }
LiangLiu's avatar
LiangLiu committed
4370

4371
                // 4. 加载历史记录和素材库(异步,不阻塞首屏)
LiangLiu's avatar
LiangLiu committed
4372
4373
                refreshTasks(true);
                loadInspirationData(true);
LiangLiu's avatar
LiangLiu committed
4374

4375
                // 5. 加载历史记录和素材库文件(异步,不阻塞首屏)
LiangLiu's avatar
LiangLiu committed
4376
4377
4378
                getPromptHistory();
                loadTaskFilesFromCache();
                loadTemplateFilesFromCache();
LiangLiu's avatar
LiangLiu committed
4379

LiangLiu's avatar
LiangLiu committed
4380
4381
4382
4383
                // 异步加载模板数据,不阻塞首屏渲染
                setTimeout(() => {
                    loadImageAudioTemplates(true);
                }, 100);
LiangLiu's avatar
LiangLiu committed
4384
4385


LiangLiu's avatar
LiangLiu committed
4386
4387
4388
4389
4390
                console.log('初始化完成:', {
                    currentUser: currentUser.value,
                    availableModels: models.value,
                    tasks: tasks.value,
                    inspirationItems: inspirationItems.value,
4391
4392
4393
4394
4395
4396
                    selectedTaskId: selectedTaskId.value,
                    selectedModel: selectedModel.value,
                    currentForm: {
                        model_cls: getCurrentForm().model_cls,
                        stage: getCurrentForm().stage
                    }
LiangLiu's avatar
LiangLiu committed
4397
4398
                });

LiangLiu's avatar
LiangLiu committed
4399
4400
            } catch (error) {
                console.error('初始化失败:', error);
4401
                showAlert(t('initFailedPleaseRefresh'), 'danger');
LiangLiu's avatar
LiangLiu committed
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
            }
        };

        // 重置表单函数(保留模型选择,清空图片、音频和提示词)
        const resetForm = async (taskType) => {
            const currentForm = getCurrentForm();
            const currentModel = currentForm.model_cls;
            const currentStage = currentForm.stage;

            // 重置表单但保留模型和阶段
            switch (taskType) {
                case 't2v':
                    t2vForm.value = {
                        task: 't2v',
4416
4417
                        model_cls: currentModel,
                        stage: currentStage,
LiangLiu's avatar
LiangLiu committed
4418
4419
4420
4421
4422
4423
4424
                        prompt: '',
                        seed: Math.floor(Math.random() * 1000000)
                    };
                    break;
                case 'i2v':
                    i2vForm.value = {
                        task: 'i2v',
4425
4426
                        model_cls: currentModel,
                        stage: currentStage,
LiangLiu's avatar
LiangLiu committed
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
                        imageFile: null,
                        prompt: '',
                        seed: Math.floor(Math.random() * 1000000)
                    };
                    // 直接清空i2v图片预览
                    i2vImagePreview.value = null;
                    // 清理图片文件输入框
                    const imageInput = document.querySelector('input[type="file"][accept="image/*"]');
                    if (imageInput) {
                        imageInput.value = '';
                    }
                    break;
                case 's2v':
                    s2vForm.value = {
                        task: 's2v',
4442
4443
                        model_cls: currentModel,
                        stage: currentStage,
LiangLiu's avatar
LiangLiu committed
4444
4445
4446
4447
4448
4449
                        imageFile: null,
                        audioFile: null,
                        prompt: 'Make the character speak in a natural way according to the audio.',
                        seed: Math.floor(Math.random() * 1000000)
                    };
                    break;
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
                case 'animate':
                    animateForm.value = {
                        task: 'animate',
                        model_cls: currentModel,
                        stage: currentStage,
                        imageFile: null,
                        videoFile: null,
                        prompt: '视频中的人在做动作',
                        seed: Math.floor(Math.random() * 1000000),
                        detectedFaces: []
                    };
                    // 直接清空animate图片和视频预览
                    animateImagePreview.value = null;
                    animateVideoPreview.value = null;
                    // 清理图片和视频文件输入框
                    const animateImageInput = document.querySelector('input[type="file"][accept="image/*"]');
                    if (animateImageInput) {
                        animateImageInput.value = '';
                    }
                    const animateVideoInput = document.querySelector('input[type="file"][data-role="video-input"]');
                    if (animateVideoInput) {
                        animateVideoInput.value = '';
                    }
                    break;
LiangLiu's avatar
LiangLiu committed
4474
            }
LiangLiu's avatar
LiangLiu committed
4475

LiangLiu's avatar
LiangLiu committed
4476
4477
4478
4479
4480
            // 强制触发Vue响应式更新
            setCurrentImagePreview(null);
            setCurrentAudioPreview(null);
            await nextTick();
        };
LiangLiu's avatar
LiangLiu committed
4481

LiangLiu's avatar
LiangLiu committed
4482
4483
4484
4485
4486
        // 开始轮询任务状态
        const startPollingTask = (taskId) => {
            if (!pollingTasks.value.has(taskId)) {
                pollingTasks.value.add(taskId);
                console.log(`开始轮询任务状态: ${taskId}`);
LiangLiu's avatar
LiangLiu committed
4487

LiangLiu's avatar
LiangLiu committed
4488
4489
4490
4491
4492
                // 如果还没有轮询定时器,启动一个
                if (!pollingInterval.value) {
                    pollingInterval.value = setInterval(async () => {
                        await pollTaskStatuses();
                    }, 1000); // 每1秒轮询一次
LiangLiu's avatar
LiangLiu committed
4493
                }
LiangLiu's avatar
LiangLiu committed
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
            }
        };

        // 停止轮询任务状态
        const stopPollingTask = (taskId) => {
            pollingTasks.value.delete(taskId);
            console.log(`停止轮询任务状态: ${taskId}`);

            // 如果没有任务需要轮询了,清除定时器
            if (pollingTasks.value.size === 0 && pollingInterval.value) {
                clearInterval(pollingInterval.value);
                pollingInterval.value = null;
                console.log('停止所有任务状态轮询');
            }
        };
LiangLiu's avatar
LiangLiu committed
4509

LiangLiu's avatar
LiangLiu committed
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
        const refreshTaskFiles = (task) => {
            for (const [key, inputPath] of Object.entries(task.inputs)) {
                getTaskFileUrlFromApi(task.task_id, key).then(url => {
                    console.log('refreshTaskFiles: input', task.task_id, key, url);
                });
            }
            for (const [key, outputPath] of Object.entries(task.outputs)) {
                getTaskFileUrlFromApi(task.task_id, key).then(url => {
                    console.log('refreshTaskFiles: output', task.task_id, key, url);
                });
            }
        };
LiangLiu's avatar
LiangLiu committed
4522

LiangLiu's avatar
LiangLiu committed
4523
4524
4525
        // 轮询任务状态
        const pollTaskStatuses = async () => {
            if (pollingTasks.value.size === 0) return;
LiangLiu's avatar
LiangLiu committed
4526

LiangLiu's avatar
LiangLiu committed
4527
4528
4529
            try {
                const taskIds = Array.from(pollingTasks.value);
                const response = await apiRequest(`/api/v1/task/query?task_ids=${taskIds.join(',')}`);
LiangLiu's avatar
LiangLiu committed
4530

LiangLiu's avatar
LiangLiu committed
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
                if (response && response.ok) {
                    const tasksData = await response.json();
                    const updatedTasks = tasksData.tasks || [];

                    // 更新任务列表中的任务状态
                    let hasUpdates = false;
                    updatedTasks.forEach(updatedTask => {
                        const existingTaskIndex = tasks.value.findIndex(t => t.task_id === updatedTask.task_id);
                        if (existingTaskIndex !== -1) {
                            const oldTask = tasks.value[existingTaskIndex];
                            tasks.value[existingTaskIndex] = updatedTask;
                            console.log('updatedTask', updatedTask);
                            console.log('oldTask', oldTask);

                            // 如果状态发生变化,记录日志
                            if (oldTask !== updatedTask) {
                                hasUpdates = true; // 这里基本都会变,因为任务有进度条

                                // 如果当前在查看这个任务的详情,更新selectedTask
                                if (modalTask.value && modalTask.value.task_id === updatedTask.task_id) {
                                    modalTask.value = updatedTask;
                                    if (updatedTask.status === 'SUCCEED') {
                                        console.log('refresh viewing task: output files');
                                        loadTaskFiles(updatedTask);
                                    }
                                }
LiangLiu's avatar
LiangLiu committed
4557

LiangLiu's avatar
LiangLiu committed
4558
4559
4560
4561
4562
                                // 如果当前TaskCarousel显示的是这个任务,更新currentTask
                                if (currentTask.value && currentTask.value.task_id === updatedTask.task_id) {
                                    currentTask.value = updatedTask;
                                    console.log('TaskCarousel: 更新currentTask', updatedTask);
                                }
LiangLiu's avatar
LiangLiu committed
4563

LiangLiu's avatar
LiangLiu committed
4564
4565
4566
4567
                                // 如果当前在projects页面且变化的是状态,更新tasks
                                if (router.path === '/projects' && oldTask.status !== updatedTask.status) {
                                    refreshTasks(true);
                                }
LiangLiu's avatar
LiangLiu committed
4568

LiangLiu's avatar
LiangLiu committed
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
                                // 如果任务完成或失败,停止轮询并显示提示
                                if (['SUCCEED', 'FAILED', 'CANCEL'].includes(updatedTask.status)) {
                                    stopPollingTask(updatedTask.task_id);
                                    refreshTaskFiles(updatedTask);
                                    refreshTasks(true);

                                    // 显示任务完成提示
                                    if (updatedTask.status === 'SUCCEED') {
                                        showAlert(t('taskCompletedSuccessfully'), 'success', {
                                            label: t('view'),
                                            onClick: () => {
                                                openTaskDetailModal(updatedTask);
                                            }
                                        });
                                    } else if (updatedTask.status === 'FAILED') {
                                        showAlert(t('videoGeneratingFailed'), 'danger', {
                                            label: t('view'),
                                            onClick: () => {
                                                openTaskDetailModal(updatedTask);
                                            }
                                        });
                                    } else if (updatedTask.status === 'CANCEL') {
                                        showAlert(t('taskCancelled'), 'warning');
                                    }
                                }
                            }
                        }
                    });
LiangLiu's avatar
LiangLiu committed
4597

LiangLiu's avatar
LiangLiu committed
4598
4599
4600
                    // 如果有更新,触发界面刷新
                    if (hasUpdates) {
                        await nextTick();
LiangLiu's avatar
LiangLiu committed
4601
4602
                    }
                }
LiangLiu's avatar
LiangLiu committed
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
            } catch (error) {
                console.error('轮询任务状态失败:', error);
            }
        };

        // 任务状态管理
        const getTaskStatusDisplay = (status) => {
            const statusMap = {
                'CREATED': t('created'),
                'PENDING': t('pending'),
                'RUNNING': t('running'),
                'SUCCEED': t('succeed'),
                'FAILED': t('failed'),
                'CANCEL': t('cancelled')
            };
            return statusMap[status] || status;
        };

        const getTaskStatusColor = (status) => {
            const colorMap = {
                'CREATED': 'text-blue-400',
                'PENDING': 'text-yellow-400',
                'RUNNING': 'text-amber-400',
                'SUCCEED': 'text-emerald-400',
                'FAILED': 'text-red-400',
                'CANCEL': 'text-gray-400'
            };
            return colorMap[status] || 'text-gray-400';
        };

        const getTaskStatusIcon = (status) => {
            const iconMap = {
                'CREATED': 'fas fa-clock',
                'PENDING': 'fas fa-hourglass-half',
                'RUNNING': 'fas fa-spinner fa-spin',
                'SUCCEED': 'fas fa-check-circle',
                'FAILED': 'fas fa-exclamation-triangle',
                'CANCEL': 'fas fa-ban'
            };
            return iconMap[status] || 'fas fa-question-circle';
        };

        // 任务时间格式化
        const getTaskDuration = (startTime, endTime) => {
            if (!startTime || !endTime) return '未知';
            const start = new Date(startTime * 1000);
            const end = new Date(endTime * 1000);
            const diff = end - start;
            const minutes = Math.floor(diff / 60000);
            const seconds = Math.floor((diff % 60000) / 1000);
            return `${minutes}${seconds}秒`;
        };

        // 相对时间格式化
        const getRelativeTime = (timestamp) => {
            if (!timestamp) return '未知';
            const now = new Date();
            const time = new Date(timestamp * 1000);
            const diff = now - time;

            const minutes = Math.floor(diff / 60000);
            const hours = Math.floor(diff / 3600000);
            const days = Math.floor(diff / 86400000);
            const months = Math.floor(diff / 2592000000); // 30天
            const years = Math.floor(diff / 31536000000);

            if (years > 0) {
                return years === 1 ? t('oneYearAgo') : `${years}t('yearsAgo')`;
            } else if (months > 0) {
                return months === 1 ? t('oneMonthAgo') : `${months}${t('monthsAgo')}`;
            } else if (days > 0) {
                return days === 1 ? t('oneDayAgo') : `${days}${t('daysAgo')}`;
            } else if (hours > 0) {
                return hours === 1 ? t('oneHourAgo') : `${hours}${t('hoursAgo')}`;
            } else if (minutes > 0) {
                return minutes === 1 ? t('oneMinuteAgo') : `${minutes}${t('minutesAgo')}`;
            } else {
                return t('justNow');
            }
        };
LiangLiu's avatar
LiangLiu committed
4683

LiangLiu's avatar
LiangLiu committed
4684
4685
4686
4687
4688
4689
        // 任务历史记录管理
        const getTaskHistory = () => {
            return tasks.value.filter(task =>
                ['SUCCEED', 'FAILED', 'CANCEL'].includes(task.status)
            );
        };
LiangLiu's avatar
LiangLiu committed
4690

LiangLiu's avatar
LiangLiu committed
4691
4692
4693
        // 子任务进度相关函数
        const getOverallProgress = (subtasks) => {
            if (!subtasks || subtasks.length === 0) return 0;
LiangLiu's avatar
LiangLiu committed
4694

LiangLiu's avatar
LiangLiu committed
4695
4696
4697
4698
            let completedCount = 0;
            subtasks.forEach(subtask => {
                if (subtask.status === 'SUCCEED') {
                    completedCount++;
LiangLiu's avatar
LiangLiu committed
4699
                }
LiangLiu's avatar
LiangLiu committed
4700
            });
LiangLiu's avatar
LiangLiu committed
4701

LiangLiu's avatar
LiangLiu committed
4702
4703
            return Math.round((completedCount / subtasks.length) * 100);
        };
LiangLiu's avatar
LiangLiu committed
4704

LiangLiu's avatar
LiangLiu committed
4705
4706
4707
        // 获取进度条标题
        const getProgressTitle = (subtasks) => {
            if (!subtasks || subtasks.length === 0) return t('overallProgress');
LiangLiu's avatar
LiangLiu committed
4708

LiangLiu's avatar
LiangLiu committed
4709
4710
            const pendingSubtasks = subtasks.filter(subtask => subtask.status === 'PENDING');
            const runningSubtasks = subtasks.filter(subtask => subtask.status === 'RUNNING');
LiangLiu's avatar
LiangLiu committed
4711

LiangLiu's avatar
LiangLiu committed
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
            if (pendingSubtasks.length > 0) {
                return t('queueStatus');
            } else if (runningSubtasks.length > 0) {
                return t('running');
            } else {
                return t('overallProgress');
            }
        };

        // 获取进度信息
        const getProgressInfo = (subtasks) => {
            if (!subtasks || subtasks.length === 0) return '0%';

            const pendingSubtasks = subtasks.filter(subtask => subtask.status === 'PENDING');
            const runningSubtasks = subtasks.filter(subtask => subtask.status === 'RUNNING');

            if (pendingSubtasks.length > 0) {
                // 显示排队信息
                const firstPending = pendingSubtasks[0];
                const queuePosition = firstPending.estimated_pending_order;
                const estimatedTime = firstPending.estimated_pending_secs;

                let info = t('queueing');
                if (queuePosition !== null && queuePosition !== undefined) {
                    info += ` (${t('position')}: ${queuePosition})`;
                }
                if (estimatedTime !== null && estimatedTime !== undefined) {
                    info += ` - ${formatDuration(estimatedTime)}`;
                }
                return info;
            } else if (runningSubtasks.length > 0) {
                // 显示运行信息
                const firstRunning = runningSubtasks[0];
                const workerName = firstRunning.worker_name || t('unknown');
                const estimatedTime = firstRunning.estimated_running_secs;

                let info = `${t('subtask')} ${workerName}`;
                if (estimatedTime !== null && estimatedTime !== undefined) {
                    const elapses = firstRunning.elapses || {};
                    const runningTime = elapses['RUNNING-'] || 0;
                    const remaining = Math.max(0, estimatedTime - runningTime);
                    info += ` - ${t('remaining')} ${formatDuration(remaining)}`;
LiangLiu's avatar
LiangLiu committed
4754
                }
LiangLiu's avatar
LiangLiu committed
4755
4756
4757
4758
4759
4760
                return info;
            } else {
                // 显示总体进度
                return getOverallProgress(subtasks) + '%';
            }
        };
LiangLiu's avatar
LiangLiu committed
4761

LiangLiu's avatar
LiangLiu committed
4762
4763
4764
        const getSubtaskProgress = (subtask) => {
            if (subtask.status === 'SUCCEED') return 100;
            if (subtask.status === 'FAILED' || subtask.status === 'CANCEL') return 0;
LiangLiu's avatar
LiangLiu committed
4765

LiangLiu's avatar
LiangLiu committed
4766
4767
4768
4769
4770
            // 对于PENDING和RUNNING状态,基于时间估算进度
            if (subtask.status === 'PENDING') {
                // 排队中的任务,进度为0
                return 0;
            }
LiangLiu's avatar
LiangLiu committed
4771

LiangLiu's avatar
LiangLiu committed
4772
4773
4774
4775
4776
            if (subtask.status === 'RUNNING') {
                // 运行中的任务,基于已运行时间估算进度
                const elapses = subtask.elapses || {};
                const runningTime = elapses['RUNNING-'] || 0;
                const estimatedTotal = subtask.estimated_running_secs || 0;
LiangLiu's avatar
LiangLiu committed
4777

LiangLiu's avatar
LiangLiu committed
4778
4779
4780
4781
                if (estimatedTotal > 0) {
                    const progress = Math.min((runningTime / estimatedTotal) * 100, 95); // 最多95%,避免显示100%但未完成
                    return Math.round(progress);
                }
LiangLiu's avatar
LiangLiu committed
4782

LiangLiu's avatar
LiangLiu committed
4783
4784
4785
                // 如果没有时间估算,基于状态显示一个基础进度
                return 50; // 运行中但无法估算进度时显示50%
            }
LiangLiu's avatar
LiangLiu committed
4786

LiangLiu's avatar
LiangLiu committed
4787
4788
            return 0;
        };
LiangLiu's avatar
LiangLiu committed
4789
4790
4791



LiangLiu's avatar
LiangLiu committed
4792
4793
4794
4795
4796
4797
4798
        const getSubtaskStatusText = (status) => {
            const statusMap = {
                'PENDING': t('pending'),
                'RUNNING': t('running'),
                'SUCCEED': t('completed'),
                'FAILED': t('failed'),
                'CANCEL': t('cancelled')
LiangLiu's avatar
LiangLiu committed
4799
            };
LiangLiu's avatar
LiangLiu committed
4800
4801
            return statusMap[status] || status;
        };
LiangLiu's avatar
LiangLiu committed
4802
4803


LiangLiu's avatar
LiangLiu committed
4804
4805
4806
4807
4808
        const formatEstimatedTime = computed(() => {
            return (formattedEstimatedTime) => {
            if (subtask.status === 'PENDING') {
                const pendingSecs = subtask.estimated_pending_secs;
                const queuePosition = subtask.estimated_pending_order;
LiangLiu's avatar
LiangLiu committed
4809

LiangLiu's avatar
LiangLiu committed
4810
4811
4812
4813
                if (pendingSecs !== null && pendingSecs !== undefined) {
                    let info = formatDuration(pendingSecs);
                    if (queuePosition !== null && queuePosition !== undefined) {
                        info += ` (${t('position')}: ${queuePosition})`;
LiangLiu's avatar
LiangLiu committed
4814
                    }
LiangLiu's avatar
LiangLiu committed
4815
                    formattedEstimatedTime.value = info;
LiangLiu's avatar
LiangLiu committed
4816
                }
LiangLiu's avatar
LiangLiu committed
4817
4818
                formattedEstimatedTime.value=t('calculating');
            }
LiangLiu's avatar
LiangLiu committed
4819

LiangLiu's avatar
LiangLiu committed
4820
4821
4822
4823
4824
            if (subtask.status === 'RUNNING') {
                // 使用extra_info.elapses而不是subtask.elapses
                const elapses = subtask.extra_info?.elapses || {};
                const runningTime = elapses['RUNNING-'] || 0;
                const estimatedTotal = subtask.estimated_running_secs || 0;
LiangLiu's avatar
LiangLiu committed
4825

LiangLiu's avatar
LiangLiu committed
4826
4827
4828
4829
4830
                if (estimatedTotal > 0) {
                    const remaining = Math.max(0, estimatedTotal - runningTime);
                    estimatedTime.value = remaining;
                    formattedEstimatedTime.value = `${t('remaining')} ${formatDuration(remaining)}`;
                }
LiangLiu's avatar
LiangLiu committed
4831

LiangLiu's avatar
LiangLiu committed
4832
4833
4834
4835
4836
                // 如果没有estimated_running_secs,尝试使用elapses计算
                if (Object.keys(elapses).length > 0) {
                    const totalElapsed = Object.values(elapses).reduce((sum, time) => sum + (time || 0), 0);
                    if (totalElapsed > 0) {
                        formattedEstimatedTime.value = `${t('running')} ${formatDuration(totalElapsed)}`;
LiangLiu's avatar
LiangLiu committed
4837
4838
                    }
                }
LiangLiu's avatar
LiangLiu committed
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879

                return t('calculating');
            }

            return t('completed');
        };
});

        const formatDuration = (seconds) => {
            if (seconds < 60) {
                return `${Math.round(seconds)}${t('seconds')}`;
            } else if (seconds < 3600) {
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = Math.round(seconds % 60);
                return `${minutes}${t('minutes')}${remainingSeconds}${t('seconds')}`;
            } else {
                const hours = Math.floor(seconds / 3600);
                const minutes = Math.floor((seconds % 3600) / 60);
                const remainingSeconds = Math.round(seconds % 60);
                return `${hours}${t('hours')}${minutes}${t('minutes')}${remainingSeconds}${t('seconds')}`;
            }
        };

        const getActiveTasks = () => {
            return tasks.value.filter(task =>
                ['CREATED', 'PENDING', 'RUNNING'].includes(task.status)
            );
        };

        // 任务搜索和过滤增强
        const searchTasks = (query) => {
            if (!query) return tasks.value;
            return tasks.value.filter(task => {
                const searchText = [
                    task.task_id,
                    task.task_type,
                    task.model_cls,
                    task.params?.prompt || '',
                    getTaskStatusDisplay(task.status)
                ].join(' ').toLowerCase();
                return searchText.includes(query.toLowerCase());
LiangLiu's avatar
LiangLiu committed
4880
            });
LiangLiu's avatar
LiangLiu committed
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
        };

        const filterTasksByStatus = (status) => {
            if (status === 'ALL') return tasks.value;
            return tasks.value.filter(task => task.status === status);
        };

        const filterTasksByType = (type) => {
            if (!type) return tasks.value;
            return tasks.value.filter(task => task.task_type === type);
        };

        // 提示消息样式管理
        const getAlertClass = (type) => {
            const classMap = {
                'success': 'animate-slide-down',
                'warning': 'animate-slide-down',
                'danger': 'animate-slide-down',
                'info': 'animate-slide-down'
            };
            return classMap[type] || 'animate-slide-down';
        };

        const getAlertBorderClass = (type) => {
            const borderMap = {
                'success': 'border-green-500',
                'warning': 'border-yellow-500',
                'danger': 'border-red-500',
                'info': 'border-blue-500'
            };
            return borderMap[type] || 'border-gray-500';
        };

        const getAlertTextClass = (type) => {
            // 统一使用白色文字
            return 'text-white';
        };

        const getAlertIcon = (type) => {
            const iconMap = {
                'success': 'fas fa-check text-white',
                'warning': 'fas fa-exclamation text-white',
                'danger': 'fas fa-times text-white',
                'info': 'fas fa-info text-white'
            };
            return iconMap[type] || 'fas fa-info text-white';
        };

        const getAlertIconBgClass = (type) => {
            const bgMap = {
                'success': 'bg-green-500/30',
                'warning': 'bg-yellow-500/30',
                'danger': 'bg-red-500/30',
                'info': 'bg-laser-purple/30'
            };
            return bgMap[type] || 'bg-laser-purple/30';
        };

        // 监听器 - 监听任务类型变化
        watch(() => selectedTaskId.value, () => {
            const currentForm = getCurrentForm();

            // 只有当当前表单没有选择模型时,才自动选择第一个可用的模型
            if (!currentForm.model_cls) {
                let availableModels;

                availableModels = models.value.filter(m => m.task === selectedTaskId.value);
LiangLiu's avatar
LiangLiu committed
4948

LiangLiu's avatar
LiangLiu committed
4949
4950
4951
4952
4953
4954
                if (availableModels.length > 0) {
                    const firstModel = availableModels[0];
                    currentForm.model_cls = firstModel.model_cls;
                    currentForm.stage = firstModel.stage;
                }
            }
LiangLiu's avatar
LiangLiu committed
4955

LiangLiu's avatar
LiangLiu committed
4956
4957
4958
            // 注意:这里不需要重置预览,因为我们要保持每个任务的独立性
            // 预览会在 selectTask 函数中根据文件状态恢复
        });
LiangLiu's avatar
LiangLiu committed
4959

LiangLiu's avatar
LiangLiu committed
4960
4961
        watch(() => getCurrentForm().model_cls, () => {
            const currentForm = getCurrentForm();
LiangLiu's avatar
LiangLiu committed
4962

LiangLiu's avatar
LiangLiu committed
4963
4964
4965
            // 只有当当前表单没有选择阶段时,才自动选择第一个可用的阶段
            if (!currentForm.stage) {
                let availableStages;
LiangLiu's avatar
LiangLiu committed
4966

LiangLiu's avatar
LiangLiu committed
4967
4968
4969
                availableStages = models.value
                        .filter(m => m.task === selectedTaskId.value && m.model_cls === currentForm.model_cls)
                        .map(m => m.stage);
LiangLiu's avatar
LiangLiu committed
4970

LiangLiu's avatar
LiangLiu committed
4971
4972
                if (availableStages.length > 0) {
                    currentForm.stage = availableStages[0];
LiangLiu's avatar
LiangLiu committed
4973
                }
LiangLiu's avatar
LiangLiu committed
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
            }
        });

        // 提示词模板管理
        const promptTemplates = {
            's2v': [
                {
                    id: 's2v_1',
                    title: '情绪表达',
                    prompt: '根据音频,人物进行情绪化表达,表情丰富,能体现音频中的情绪,手势根据情绪适当调整。'
                },
                {
                    id: 's2v_2',
                    title: '故事讲述',
                    prompt: '根据音频,人物进行故事讲述,表情丰富,能体现音频中的情绪,手势根据故事情节适当调整。'
                },
                {
                    id: 's2v_3',
                    title: '知识讲解',
                    prompt: '根据音频,人物进行知识讲解,表情严肃,整体风格专业得体,手势根据知识内容适当调整。'
                },
                {
                    id: 's2v_4',
                    title: '浮夸表演',
                    prompt: '根据音频,人物进行浮夸表演,表情夸张,动作浮夸,整体风格夸张搞笑。'
                },
                {
                    id: 's2v_5',
                    title: '商务演讲',
                    prompt: '根据音频,人物进行商务演讲,表情严肃,手势得体,整体风格专业商务。'
                },
                {
                    id: 's2v_6',
                    title: '产品介绍',
                    prompt: '数字人介绍产品特点,语气亲切热情,表情丰富,动作自然,能体现产品特点。'
                }
            ],
            't2v': [
                {
                    id: 't2v_1',
                    title: '自然风景',
                    prompt: '一个宁静的山谷,阳光透过云层洒在绿色的草地上,远处有雪山,近处有清澈的溪流,画面温暖自然,充满生机。'
                },
                {
                    id: 't2v_2',
                    title: '城市夜景',
                    prompt: '繁华的城市夜景,霓虹灯闪烁,高楼大厦林立,车流如织,天空中有星星点缀,营造出都市的繁华氛围。'
                },
                {
                    id: 't2v_3',
                    title: '科技未来',
                    prompt: '未来科技城市,飞行汽车穿梭,全息投影随处可见,建筑具有流线型设计,充满科技感和未来感。'
                }
            ],
            'i2v': [
                {
                    id: 'i2v_1',
                    title: '人物动作',
                    prompt: '基于参考图片,让角色做出自然的行走动作,保持原有的服装和风格,背景可以适当变化。'
                },
                {
                    id: 'i2v_2',
                    title: '场景转换',
                    prompt: '保持参考图片中的人物形象,将背景转换为不同的季节或环境,如从室内到户外,从白天到夜晚。'
                }
            ]
        };

        const getPromptTemplates = (taskType) => {
            return promptTemplates[taskType] || [];
        };

        const selectPromptTemplate = (template) => {
            getCurrentForm().prompt = template.prompt;
            showPromptModal.value = false;
            showAlert(`${t('templateApplied')} ${template.title}`, 'success');
        };

        // 提示词历史记录管理 - 现在直接从taskHistory中获取
        const promptHistory = ref([]);

        const getPromptHistory = async () => {
            try {
                // 从taskHistory中获取prompt历史,去重并按时间排序
                const taskHistory = await getLocalTaskHistory();
                const uniquePrompts = [];
                const seenPrompts = new Set();

                // 遍历taskHistory,提取唯一的prompt
                for (const task of taskHistory) {
                    if (task.prompt && task.prompt.trim() && !seenPrompts.has(task.prompt.trim())) {
                        uniquePrompts.push(task.prompt.trim());
                        seenPrompts.add(task.prompt.trim());
                    }
                }

                const result = uniquePrompts.slice(0, 10); // 只显示最近10条
                promptHistory.value = result; // 更新响应式数据
                return result;
            } catch (error) {
                console.error(t('getPromptHistoryFailed'), error);
                promptHistory.value = []; // 更新响应式数据
                return [];
            }
        };

        // addPromptToHistory函数已删除,现在prompt历史直接从taskHistory中获取

        // 保存完整的任务历史(只保存元数据,不保存文件内容)
        const addTaskToHistory = (taskType, formData) => {
            console.log('开始保存任务历史:', { taskType, formData });

            const historyItem = {
                id: Date.now(),
                timestamp: new Date().toISOString(),
                taskType: taskType,
                prompt: formData.prompt || '',
                // 只保存文件元数据,不保存文件内容
                imageFile: formData.imageFile ? {
                        name: formData.imageFile.name,
                        type: formData.imageFile.type,
                    size: formData.imageFile.size
                    // 不再保存 data 字段,避免占用大量存储空间
                } : null,
                audioFile: formData.audioFile ? {
                        name: formData.audioFile.name,
                        type: formData.audioFile.type,
                    size: formData.audioFile.size
                    // 不再保存 data 字段,避免占用大量存储空间
                } : null
                    };
LiangLiu's avatar
LiangLiu committed
5105

LiangLiu's avatar
LiangLiu committed
5106
5107
5108
            console.log('保存任务历史(仅元数据):', historyItem);
                saveTaskHistoryItem(historyItem);
        };
LiangLiu's avatar
LiangLiu committed
5109

LiangLiu's avatar
LiangLiu committed
5110
5111
5112
5113
        // 保存任务历史项到localStorage
        const saveTaskHistoryItem = (historyItem) => {
            try {
                const existingHistory = JSON.parse(localStorage.getItem('taskHistory') || '[]');
LiangLiu's avatar
LiangLiu committed
5114

LiangLiu's avatar
LiangLiu committed
5115
5116
5117
5118
5119
5120
                // 避免重复添加(基于提示词、任务类型、图片和音频)
                const isDuplicate = existingHistory.some(item => {
                    const samePrompt = item.prompt === historyItem.prompt;
                    const sameTaskType = item.taskType === historyItem.taskType;
                    const sameImage = (item.imageFile?.name || '') === (historyItem.imageFile?.name || '');
                    const sameAudio = (item.audioFile?.name || '') === (historyItem.audioFile?.name || '');
LiangLiu's avatar
LiangLiu committed
5121

LiangLiu's avatar
LiangLiu committed
5122
5123
                    return samePrompt && sameTaskType && sameImage && sameAudio;
                });
LiangLiu's avatar
LiangLiu committed
5124

LiangLiu's avatar
LiangLiu committed
5125
5126
5127
5128
                if (!isDuplicate) {
                    // 按时间戳排序,确保最新的记录在最后
                    existingHistory.push(historyItem);
                    existingHistory.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
LiangLiu's avatar
LiangLiu committed
5129

LiangLiu's avatar
LiangLiu committed
5130
5131
5132
5133
                    // 限制历史记录数量为10条(不再保存文件内容,所以可以适当减少)
                    if (existingHistory.length > 10) {
                        existingHistory.splice(0, existingHistory.length - 10);
                    }
LiangLiu's avatar
LiangLiu committed
5134

LiangLiu's avatar
LiangLiu committed
5135
5136
5137
5138
5139
5140
5141
                    // 保存到localStorage
                    try {
                        localStorage.setItem('taskHistory', JSON.stringify(existingHistory));
                        console.log('任务历史已保存(仅元数据):', historyItem);
                    } catch (storageError) {
                        if (storageError.name === 'QuotaExceededError') {
                            console.warn('localStorage空间不足,尝试清理旧数据...');
LiangLiu's avatar
LiangLiu committed
5142

LiangLiu's avatar
LiangLiu committed
5143
5144
                            // 清理策略1:只保留最新的5条记录
                            const cleanedHistory = existingHistory.slice(-5);
LiangLiu's avatar
LiangLiu committed
5145

LiangLiu's avatar
LiangLiu committed
5146
5147
5148
5149
5150
                            try {
                                localStorage.setItem('taskHistory', JSON.stringify(cleanedHistory));
                                console.log('任务历史已保存(清理后):', historyItem);
                            } catch (secondError) {
                                console.error('清理后仍无法保存,尝试清理所有缓存...');
LiangLiu's avatar
LiangLiu committed
5151

LiangLiu's avatar
LiangLiu committed
5152
                                // 清理策略2:清理所有任务历史,只保存当前这一条
LiangLiu's avatar
LiangLiu committed
5153
                                try {
LiangLiu's avatar
LiangLiu committed
5154
5155
                                    localStorage.setItem('taskHistory', JSON.stringify([historyItem]));
                                    console.log('任务历史已保存(完全清理后)');
5156
                                    showAlert(t('historyCleared'), 'info');
LiangLiu's avatar
LiangLiu committed
5157
5158
5159
5160
                                } catch (thirdError) {
                                    console.error('即使完全清理后仍无法保存:', thirdError);
                                    // 不再显示警告,因为历史记录不是必需的功能
                                    console.warn('历史记录功能暂时不可用,将从任务列表恢复数据');
LiangLiu's avatar
LiangLiu committed
5161
5162
                                }
                            }
LiangLiu's avatar
LiangLiu committed
5163
5164
                        } else {
                            throw storageError;
LiangLiu's avatar
LiangLiu committed
5165
5166
                        }
                    }
LiangLiu's avatar
LiangLiu committed
5167
5168
                } else {
                    console.log('任务历史重复,跳过保存:', historyItem);
LiangLiu's avatar
LiangLiu committed
5169
                }
LiangLiu's avatar
LiangLiu committed
5170
5171
5172
5173
5174
5175
            } catch (error) {
                console.error('保存任务历史失败:', error);
                // 不再显示警告给用户,因为可以从任务列表恢复数据
                console.warn('历史记录保存失败,将依赖任务列表数据');
            }
        };
LiangLiu's avatar
LiangLiu committed
5176

LiangLiu's avatar
LiangLiu committed
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
        // 获取本地存储的任务历史
        const getLocalTaskHistory = async () => {
            try {
                // 使用Promise模拟异步操作,避免阻塞UI
                return await new Promise((resolve) => {
                    setTimeout(() => {
                        try {
                            const history = JSON.parse(localStorage.getItem('taskHistory') || '[]');
                            // 按时间戳排序,最新的记录在前
                            const sortedHistory = history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
                            resolve(sortedHistory);
                        } catch (error) {
                            console.error(t('parseTaskHistoryFailed'), error);
                            resolve([]);
                        }
                    }, 0);
                });
            } catch (error) {
                console.error(t('getTaskHistoryFailed'), error);
                return [];
            }
        };

        const selectPromptHistory = (prompt) => {
            getCurrentForm().prompt = prompt;
            showPromptModal.value = false;
            showAlert(t('promptHistoryApplied'), 'success');
        };

        const clearPromptHistory = () => {
            // 清空taskHistory中的prompt相关数据
            localStorage.removeItem('taskHistory');
            showAlert(t('promptHistoryCleared'), 'info');
        };

        // 图片历史记录管理 - 从任务列表获取
        const getImageHistory = async () => {
            try {
                // 确保任务列表已加载
                if (tasks.value.length === 0) {
                    await refreshTasks();
                }

                const uniqueImages = [];
                const seenImages = new Set();

                // 遍历任务列表,提取唯一的图片
                for (const task of tasks.value) {
                    if (task.inputs && task.inputs.input_image && !seenImages.has(task.inputs.input_image)) {
                        // 获取图片URL
                        const imageUrl = await getTaskFileUrl(task.task_id, 'input_image');
                        if (imageUrl) {
                            uniqueImages.push({
                                filename: task.inputs.input_image,
                                url: imageUrl,
                                thumbnail: imageUrl, // 使用URL作为缩略图
                                taskId: task.task_id,
                                timestamp: task.create_t,
                                taskType: task.task_type
                            });
                            seenImages.add(task.inputs.input_image);
LiangLiu's avatar
LiangLiu committed
5238
5239
5240
5241
                        }
                    }
                }

LiangLiu's avatar
LiangLiu committed
5242
5243
                // 按时间戳排序,最新的在前
                uniqueImages.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
LiangLiu's avatar
LiangLiu committed
5244

5245
5246
5247
                imageHistory.value = uniqueImages;
                console.log('从任务列表获取图片历史:', uniqueImages.length, '');
                return uniqueImages;
LiangLiu's avatar
LiangLiu committed
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
            } catch (error) {
                console.error('获取图片历史失败:', error);
                imageHistory.value = [];
                return [];
            }
        };

        // 音频历史记录管理 - 从任务列表获取
        const getAudioHistory = async () => {
            try {
                // 确保任务列表已加载
                if (tasks.value.length === 0) {
                    await refreshTasks();
                }

                const uniqueAudios = [];
                const seenAudios = new Set();

                // 遍历任务列表,提取唯一的音频
                for (const task of tasks.value) {
                    if (task.inputs && task.inputs.input_audio && !seenAudios.has(task.inputs.input_audio)) {
                        // 获取音频URL
5270
5271
5272
5273
5274
5275
5276
                        let audioUrl = await getTaskFileUrl(task.task_id, 'input_audio');

                        // 如果返回null,可能是目录类型(多人模式),尝试获取original_audio.wav
                        if (!audioUrl) {
                            audioUrl = await getTaskFileUrlFromApi(task.task_id, 'input_audio', 'original_audio.wav');
                        }

5277
                        const imageUrl = task.inputs.input_image ? await getTaskFileUrl(task.task_id, 'input_image') : null;
LiangLiu's avatar
LiangLiu committed
5278
5279
5280
5281
5282
5283
                        if (audioUrl) {
                            uniqueAudios.push({
                                filename: task.inputs.input_audio,
                                url: audioUrl,
                                taskId: task.task_id,
                                timestamp: task.create_t,
5284
5285
                                taskType: task.task_type,
                                imageUrl
LiangLiu's avatar
LiangLiu committed
5286
5287
                            });
                            seenAudios.add(task.inputs.input_audio);
LiangLiu's avatar
LiangLiu committed
5288
5289
                        }
                    }
LiangLiu's avatar
LiangLiu committed
5290
                }
LiangLiu's avatar
LiangLiu committed
5291

LiangLiu's avatar
LiangLiu committed
5292
5293
                // 按时间戳排序,最新的在前
                uniqueAudios.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
LiangLiu's avatar
LiangLiu committed
5294

5295
5296
5297
                audioHistory.value = uniqueAudios;
                console.log('从任务列表获取音频历史:', uniqueAudios.length, '');
                return uniqueAudios;
LiangLiu's avatar
LiangLiu committed
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
            } catch (error) {
                console.error('获取音频历史失败:', error);
                audioHistory.value = [];
                return [];
            }
        };

        // 选择图片历史记录 - 从URL获取
        const selectImageHistory = async (history) => {
            try {
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
                // 确保 URL 有效,如果无效则重新获取
                let imageUrl = history.url;
                if (!imageUrl || imageUrl.trim() === '') {
                    // 如果 URL 为空,尝试重新获取
                    if (history.taskId) {
                        imageUrl = await getTaskFileUrl(history.taskId, 'input_image');
                    }
                    if (!imageUrl || imageUrl.trim() === '') {
                        throw new Error('图片 URL 无效');
                    }
                }

LiangLiu's avatar
LiangLiu committed
5320
                // 从URL获取图片文件
5321
                const response = await fetch(imageUrl);
LiangLiu's avatar
LiangLiu committed
5322
5323
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
LiangLiu's avatar
LiangLiu committed
5324
5325
                }

LiangLiu's avatar
LiangLiu committed
5326
5327
                const blob = await response.blob();
                const file = new File([blob], history.filename, { type: blob.type });
LiangLiu's avatar
LiangLiu committed
5328

LiangLiu's avatar
LiangLiu committed
5329
                // 设置图片预览
5330
                setCurrentImagePreview(imageUrl);
LiangLiu's avatar
LiangLiu committed
5331
                updateUploadedContentStatus();
LiangLiu's avatar
LiangLiu committed
5332

LiangLiu's avatar
LiangLiu committed
5333
5334
5335
                // 更新表单
                const currentForm = getCurrentForm();
                currentForm.imageFile = file;
LiangLiu's avatar
LiangLiu committed
5336

5337
5338
5339
5340
5341
5342
5343
                // Reset detected faces
                if (selectedTaskId.value === 'i2v') {
                    i2vForm.value.detectedFaces = [];
                } else if (selectedTaskId.value === 's2v') {
                    s2vForm.value.detectedFaces = [];
                }

LiangLiu's avatar
LiangLiu committed
5344
                showImageTemplates.value = false;
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
                showAlert(t('historyImageApplied'), 'success');

                // Auto detect faces after image is loaded
                // 不再自动检测人脸,等待用户手动打开多角色模式开关
                try {
                    // 如果 URL 是 http/https,直接使用;否则转换为 data URL
                    if (!imageUrl.startsWith('http://') && !imageUrl.startsWith('https://')) {
                        // 如果不是 http/https URL,转换为 data URL
                        const reader = new FileReader();
                        reader.onload = async (e) => {
                            // 不再自动检测人脸
                        };
                        reader.readAsDataURL(file);
                    }
                } catch (error) {
                    console.error('Face detection failed:', error);
                    // Don't show error alert, just log it
                }

LiangLiu's avatar
LiangLiu committed
5364
5365
            } catch (error) {
                console.error('应用历史图片失败:', error);
5366
                showAlert(t('applyHistoryImageFailed') + ': ' + error.message, 'danger');
LiangLiu's avatar
LiangLiu committed
5367
5368
            }
        };
LiangLiu's avatar
LiangLiu committed
5369

LiangLiu's avatar
LiangLiu committed
5370
5371
5372
5373
5374
5375
5376
        // 选择音频历史记录 - 从URL获取
        const selectAudioHistory = async (history) => {
            try {
                // 从URL获取音频文件
                const response = await fetch(history.url);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
LiangLiu's avatar
LiangLiu committed
5377
5378
                }

LiangLiu's avatar
LiangLiu committed
5379
5380
                const blob = await response.blob();
                const file = new File([blob], history.filename, { type: blob.type });
LiangLiu's avatar
LiangLiu committed
5381

LiangLiu's avatar
LiangLiu committed
5382
5383
5384
                // 设置音频预览
                setCurrentAudioPreview(history.url);
                updateUploadedContentStatus();
LiangLiu's avatar
LiangLiu committed
5385

LiangLiu's avatar
LiangLiu committed
5386
5387
5388
                // 更新表单
                const currentForm = getCurrentForm();
                currentForm.audioFile = file;
LiangLiu's avatar
LiangLiu committed
5389

LiangLiu's avatar
LiangLiu committed
5390
                showAudioTemplates.value = false;
5391
                showAlert(t('historyAudioApplied'), 'success');
LiangLiu's avatar
LiangLiu committed
5392
5393
            } catch (error) {
                console.error('应用历史音频失败:', error);
5394
                showAlert(t('applyHistoryAudioFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
5395
5396
            }
        };
LiangLiu's avatar
LiangLiu committed
5397

LiangLiu's avatar
LiangLiu committed
5398
5399
5400
        // 全局音频播放状态管理
        let currentPlayingAudio = null;
        let audioStopCallback = null;
LiangLiu's avatar
LiangLiu committed
5401

LiangLiu's avatar
LiangLiu committed
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
        // 停止音频播放
        const stopAudioPlayback = () => {
            if (currentPlayingAudio) {
                currentPlayingAudio.pause();
                currentPlayingAudio.currentTime = 0;
                currentPlayingAudio = null;

                // 调用停止回调
                if (audioStopCallback) {
                    audioStopCallback();
                    audioStopCallback = null;
LiangLiu's avatar
LiangLiu committed
5413
                }
LiangLiu's avatar
LiangLiu committed
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
            }
        };

        // 设置音频停止回调
        const setAudioStopCallback = (callback) => {
            audioStopCallback = callback;
        };

        // 预览音频历史记录 - 使用URL
        const previewAudioHistory = (history) => {
            console.log('预览音频历史:', history);
            const audioUrl = history.url;
            console.log('音频历史URL:', audioUrl);
            if (!audioUrl) {
5428
                showAlert(t('audioHistoryUrlFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
5429
5430
                return;
            }
LiangLiu's avatar
LiangLiu committed
5431

LiangLiu's avatar
LiangLiu committed
5432
5433
5434
5435
5436
5437
            // 停止当前播放的音频
            if (currentPlayingAudio) {
                currentPlayingAudio.pause();
                currentPlayingAudio.currentTime = 0;
                currentPlayingAudio = null;
            }
LiangLiu's avatar
LiangLiu committed
5438

LiangLiu's avatar
LiangLiu committed
5439
5440
            const audio = new Audio(audioUrl);
            currentPlayingAudio = audio;
LiangLiu's avatar
LiangLiu committed
5441

LiangLiu's avatar
LiangLiu committed
5442
5443
5444
5445
5446
5447
5448
            // 监听音频播放结束事件
            audio.addEventListener('ended', () => {
                currentPlayingAudio = null;
                // 调用停止回调
                if (audioStopCallback) {
                    audioStopCallback();
                    audioStopCallback = null;
LiangLiu's avatar
LiangLiu committed
5449
                }
LiangLiu's avatar
LiangLiu committed
5450
            });
LiangLiu's avatar
LiangLiu committed
5451

LiangLiu's avatar
LiangLiu committed
5452
5453
            audio.addEventListener('error', () => {
                console.error('音频播放失败:', audio.error);
5454
                showAlert(t('audioPlaybackFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
5455
5456
5457
5458
5459
5460
5461
                currentPlayingAudio = null;
                // 调用停止回调
                if (audioStopCallback) {
                    audioStopCallback();
                    audioStopCallback = null;
                }
            });
LiangLiu's avatar
LiangLiu committed
5462

LiangLiu's avatar
LiangLiu committed
5463
5464
            audio.play().catch(error => {
                console.error('音频播放失败:', error);
5465
                showAlert(t('audioPlaybackFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
5466
5467
5468
5469
5470
5471
5472
                currentPlayingAudio = null;
            });
        };

        // 清空图片历史记录
        const clearImageHistory = () => {
            imageHistory.value = [];
5473
            showAlert(t('imageHistoryCleared'), 'info');
LiangLiu's avatar
LiangLiu committed
5474
5475
5476
5477
5478
        };

        // 清空音频历史记录
        const clearAudioHistory = () => {
            audioHistory.value = [];
5479
            showAlert(t('audioHistoryCleared'), 'info');
LiangLiu's avatar
LiangLiu committed
5480
5481
5482
5483
5484
5485
5486
        };

        // 清理localStorage存储空间
        const clearLocalStorage = () => {
            try {
                // 清理任务历史
                localStorage.removeItem('taskHistory');
5487
                localStorage.removeItem('refreshToken');
LiangLiu's avatar
LiangLiu committed
5488

LiangLiu's avatar
LiangLiu committed
5489
5490
5491
5492
5493
5494
                // 清理其他可能的缓存数据
                const keysToRemove = [];
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    if (key && (key.includes('template') || key.includes('task') || key.includes('history'))) {
                        keysToRemove.push(key);
LiangLiu's avatar
LiangLiu committed
5495
                    }
LiangLiu's avatar
LiangLiu committed
5496
                }
LiangLiu's avatar
LiangLiu committed
5497

LiangLiu's avatar
LiangLiu committed
5498
5499
                keysToRemove.forEach(key => {
                    localStorage.removeItem(key);
LiangLiu's avatar
LiangLiu committed
5500
5501
                });

LiangLiu's avatar
LiangLiu committed
5502
                // 重置相关状态
LiangLiu's avatar
LiangLiu committed
5503
5504
                imageHistory.value = [];
                audioHistory.value = [];
LiangLiu's avatar
LiangLiu committed
5505
5506
                promptHistory.value = [];

5507
                showAlert(t('storageCleared'), 'success');
LiangLiu's avatar
LiangLiu committed
5508
5509
5510
                console.log('localStorage已清理,释放了存储空间');
            } catch (error) {
                console.error('清理localStorage失败:', error);
5511
                showAlert(t('clearStorageFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
5512
5513
5514
5515
5516
5517
            }
        };

        const getAuthHeaders = () => {
            const headers = {
                'Content-Type': 'application/json'
LiangLiu's avatar
LiangLiu committed
5518
5519
            };

LiangLiu's avatar
LiangLiu committed
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
            const token = localStorage.getItem('accessToken');
            if (token) {
                headers['Authorization'] = `Bearer ${token}`;
                console.log('使用Token进行认证:', token.substring(0, 20) + '...');
            } else {
                console.warn('没有找到accessToken');
            }
            return headers;
        };

        // 验证token是否有效
        const validateToken = async (token) => {
            try {
                const response = await fetch('/api/v1/model/list', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
LiangLiu's avatar
LiangLiu committed
5538
                    }
LiangLiu's avatar
LiangLiu committed
5539
5540
5541
5542
5543
5544
5545
5546
                });
                await new Promise(resolve => setTimeout(resolve, 100));
                return response.ok;
            } catch (error) {
                console.error('Token validation failed:', error);
                return false;
            }
        };
LiangLiu's avatar
LiangLiu committed
5547

5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
        const refreshAccessToken = async () => {
            if (refreshPromise) {
                return refreshPromise;
            }
            const refreshToken = localStorage.getItem('refreshToken');
            if (!refreshToken) {
                return false;
            }

            refreshPromise = (async () => {
                try {
                    const response = await fetch('/auth/refresh', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ refresh_token: refreshToken })
                    });
                    await new Promise(resolve => setTimeout(resolve, 100));
                    if (!response.ok) {
                        throw new Error(`Refresh failed with status ${response.status}`);
                    }

                    const data = await response.json();
                    if (data.access_token) {
                        localStorage.setItem('accessToken', data.access_token);
                    }
                    if (data.refresh_token) {
                        localStorage.setItem('refreshToken', data.refresh_token);
                    }
                    if (data.user_info) {
                        currentUser.value = data.user_info;
                        localStorage.setItem('currentUser', JSON.stringify(data.user_info));
                    }
                    return true;
                } catch (error) {
                    console.error('Refresh token failed:', error);
                    logout(false);
5586
                    showAlert(t('loginExpiredPleaseRelogin'), 'warning', {
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
                        label: t('login'),
                        onClick: login
                    });
                    return false;
                } finally {
                    refreshPromise = null;
                }
            })();

            return refreshPromise;
        };

LiangLiu's avatar
LiangLiu committed
5599
        // 增强的API请求函数,自动处理认证错误
5600
        const apiRequest = async (url, options = {}, allowRetry = true) => {
LiangLiu's avatar
LiangLiu committed
5601
            const headers = getAuthHeaders();
LiangLiu's avatar
LiangLiu committed
5602

LiangLiu's avatar
LiangLiu committed
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
            try {
                const response = await fetch(url, {
                    ...options,
                    headers: {
                        ...headers,
                        ...options.headers
                    }
                });
                await new Promise(resolve => setTimeout(resolve, 100));
                // 检查是否是认证错误
5613
5614
5615
5616
5617
                if ((response.status === 401 || response.status === 403) && allowRetry) {
                    const refreshed = await refreshAccessToken();
                    if (refreshed) {
                        return await apiRequest(url, options, false);
                    }
LiangLiu's avatar
LiangLiu committed
5618
                    return null;
LiangLiu's avatar
LiangLiu committed
5619
                }
5620

LiangLiu's avatar
LiangLiu committed
5621
5622
5623
                return response;
            } catch (error) {
                console.error('API request failed:', error);
5624
                showAlert(t('networkRequestFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
                return null;
            }
        };

        // 侧边栏拖拽调整功能
        const sidebar = ref(null);
        const sidebarWidth = ref(256); // 默认宽度 256px (w-64)
        let isResizing = false;
        let startX = 0;
        let startWidth = 0;

        // 更新悬浮按钮位置
        const updateFloatingButtonPosition = (width) => {
            const floatingBtn = document.querySelector('.floating-toggle-btn');
            if (floatingBtn) {
                if (sidebarCollapsed.value) {
                    // 收起状态时,按钮位于屏幕左侧
                    floatingBtn.style.left = '0px';
                    floatingBtn.style.right = 'auto';
LiangLiu's avatar
LiangLiu committed
5644
                } else {
LiangLiu's avatar
LiangLiu committed
5645
5646
5647
                    // 展开状态时,按钮位于历史任务栏右侧
                    floatingBtn.style.left = width + 'px';
                    floatingBtn.style.right = 'auto';
LiangLiu's avatar
LiangLiu committed
5648
                }
LiangLiu's avatar
LiangLiu committed
5649
5650
            }
        };
LiangLiu's avatar
LiangLiu committed
5651

LiangLiu's avatar
LiangLiu committed
5652
5653
5654
        const startResize = (e) => {
            e.preventDefault();
            console.log('startResize called');
LiangLiu's avatar
LiangLiu committed
5655

LiangLiu's avatar
LiangLiu committed
5656
5657
5658
5659
            isResizing = true;
            startX = e.clientX;
            startWidth = sidebar.value.offsetWidth;
            console.log('Resize started, width:', startWidth);
LiangLiu's avatar
LiangLiu committed
5660

LiangLiu's avatar
LiangLiu committed
5661
5662
5663
5664
            document.body.classList.add('resizing');
            document.addEventListener('mousemove', handleResize);
            document.addEventListener('mouseup', stopResize);
        };
LiangLiu's avatar
LiangLiu committed
5665

LiangLiu's avatar
LiangLiu committed
5666
5667
        const handleResize = (e) => {
            if (!isResizing) return;
LiangLiu's avatar
LiangLiu committed
5668

LiangLiu's avatar
LiangLiu committed
5669
5670
5671
5672
5673
5674
5675
            const deltaX = e.clientX - startX;
            const newWidth = startWidth + deltaX;
            const minWidth = 200;
            const maxWidth = 500;

            if (newWidth >= minWidth && newWidth <= maxWidth) {
                // 立即更新悬浮按钮位置,不等待其他更新
LiangLiu's avatar
LiangLiu committed
5676
                const floatingBtn = document.querySelector('.floating-toggle-btn');
LiangLiu's avatar
LiangLiu committed
5677
5678
                if (floatingBtn && !sidebarCollapsed.value) {
                    floatingBtn.style.left = newWidth + 'px';
LiangLiu's avatar
LiangLiu committed
5679
5680
                }

LiangLiu's avatar
LiangLiu committed
5681
5682
                sidebarWidth.value = newWidth; // 更新响应式变量
                sidebar.value.style.setProperty('width', newWidth + 'px', 'important');
LiangLiu's avatar
LiangLiu committed
5683

LiangLiu's avatar
LiangLiu committed
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
                // 同时调整主内容区域宽度
                const mainContent = document.querySelector('.main-container main');
                if (mainContent) {
                    mainContent.style.setProperty('width', `calc(100% - ${newWidth}px)`, 'important');
                } else {
                    const altMain = document.querySelector('main');
                    if (altMain) {
                        altMain.style.setProperty('width', `calc(100% - ${newWidth}px)`, 'important');
                    }
                }
            } else {
                console.log('Width out of range:', newWidth);
            }
        };
LiangLiu's avatar
LiangLiu committed
5698

LiangLiu's avatar
LiangLiu committed
5699
5700
5701
5702
5703
        const stopResize = () => {
            isResizing = false;
            document.body.classList.remove('resizing');
            document.removeEventListener('mousemove', handleResize);
            document.removeEventListener('mouseup', stopResize);
LiangLiu's avatar
LiangLiu committed
5704

LiangLiu's avatar
LiangLiu committed
5705
5706
5707
5708
5709
            // 保存当前宽度到localStorage
            if (sidebar.value) {
                localStorage.setItem('sidebarWidth', sidebar.value.offsetWidth);
            }
        };
LiangLiu's avatar
LiangLiu committed
5710

LiangLiu's avatar
LiangLiu committed
5711
5712
5713
        // 应用响应式侧边栏宽度
        const applyResponsiveWidth = () => {
            if (!sidebar.value) return;
LiangLiu's avatar
LiangLiu committed
5714

LiangLiu's avatar
LiangLiu committed
5715
5716
            const windowWidth = window.innerWidth;
            let sidebarWidthPx;
LiangLiu's avatar
LiangLiu committed
5717

LiangLiu's avatar
LiangLiu committed
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
            if (windowWidth <= 768) {
                sidebarWidthPx = 200;
            } else if (windowWidth <= 1200) {
                sidebarWidthPx = 250;
            } else {
                // 大屏幕时使用保存的宽度或默认宽度
                const savedWidth = localStorage.getItem('sidebarWidth');
                if (savedWidth) {
                    const width = parseInt(savedWidth);
                    if (width >= 200 && width <= 500) {
                        sidebarWidthPx = width;
LiangLiu's avatar
LiangLiu committed
5729
                    } else {
LiangLiu's avatar
LiangLiu committed
5730
                        sidebarWidthPx = 256; // 默认 w-64
LiangLiu's avatar
LiangLiu committed
5731
5732
                    }
                } else {
LiangLiu's avatar
LiangLiu committed
5733
                    sidebarWidthPx = 256; // 默认 w-64
LiangLiu's avatar
LiangLiu committed
5734
                }
LiangLiu's avatar
LiangLiu committed
5735
            }
LiangLiu's avatar
LiangLiu committed
5736

LiangLiu's avatar
LiangLiu committed
5737
5738
            sidebarWidth.value = sidebarWidthPx; // 更新响应式变量
            sidebar.value.style.width = sidebarWidthPx + 'px';
LiangLiu's avatar
LiangLiu committed
5739

LiangLiu's avatar
LiangLiu committed
5740
5741
            // 更新悬浮按钮位置
            updateFloatingButtonPosition(sidebarWidthPx);
LiangLiu's avatar
LiangLiu committed
5742

LiangLiu's avatar
LiangLiu committed
5743
5744
5745
5746
5747
            const mainContent = document.querySelector('main');
            if (mainContent) {
                mainContent.style.width = `calc(100% - ${sidebarWidthPx}px)`;
            }
        };
LiangLiu's avatar
LiangLiu committed
5748

LiangLiu's avatar
LiangLiu committed
5749
5750
5751
5752
        // 新增:视图切换方法
        const switchToCreateView = () => {
            // 生成页面的查询参数
            const generateQuery = {};
LiangLiu's avatar
LiangLiu committed
5753

LiangLiu's avatar
LiangLiu committed
5754
5755
5756
5757
5758
5759
5760
5761
5762
            // 保留任务类型选择
            if (selectedTaskId.value) {
                generateQuery.taskType = selectedTaskId.value;
            }

            // 保留模型选择
            if (selectedModel.value) {
                generateQuery.model = selectedModel.value;
            }
LiangLiu's avatar
LiangLiu committed
5763

LiangLiu's avatar
LiangLiu committed
5764
5765
5766
5767
            // 保留创作区域展开状态
            if (isCreationAreaExpanded.value) {
                generateQuery.expanded = 'true';
            }
LiangLiu's avatar
LiangLiu committed
5768

LiangLiu's avatar
LiangLiu committed
5769
            router.push({ path: '/generate', query: generateQuery });
LiangLiu's avatar
LiangLiu committed
5770

LiangLiu's avatar
LiangLiu committed
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
            // 如果之前有展开过创作区域,保持展开状态
            if (isCreationAreaExpanded.value) {
                // 延迟一点时间确保DOM更新完成
                setTimeout(() => {
                    const creationArea = document.querySelector('.creation-area');
                    if (creationArea) {
                        creationArea.classList.add('show');
                    }
                }, 50);
            }
        };
LiangLiu's avatar
LiangLiu committed
5782

LiangLiu's avatar
LiangLiu committed
5783
5784
5785
        const switchToProjectsView = (forceRefresh = false) => {
            // 项目页面的查询参数
            const projectsQuery = {};
LiangLiu's avatar
LiangLiu committed
5786

LiangLiu's avatar
LiangLiu committed
5787
5788
5789
5790
            // 保留搜索查询
            if (taskSearchQuery.value) {
                projectsQuery.search = taskSearchQuery.value;
            }
LiangLiu's avatar
LiangLiu committed
5791

LiangLiu's avatar
LiangLiu committed
5792
5793
5794
5795
            // 保留状态筛选
            if (statusFilter.value) {
                projectsQuery.status = statusFilter.value;
            }
LiangLiu's avatar
LiangLiu committed
5796

LiangLiu's avatar
LiangLiu committed
5797
5798
5799
5800
            // 保留当前页码
            if (currentTaskPage.value > 1) {
                projectsQuery.page = currentTaskPage.value.toString();
            }
LiangLiu's avatar
LiangLiu committed
5801

LiangLiu's avatar
LiangLiu committed
5802
5803
5804
5805
            router.push({ path: '/projects', query: projectsQuery });
            // 刷新任务列表
            refreshTasks(forceRefresh);
        };
LiangLiu's avatar
LiangLiu committed
5806

LiangLiu's avatar
LiangLiu committed
5807
5808
5809
        const switchToInspirationView = () => {
            // 灵感页面的查询参数
            const inspirationQuery = {};
LiangLiu's avatar
LiangLiu committed
5810

LiangLiu's avatar
LiangLiu committed
5811
5812
5813
5814
            // 保留搜索查询
            if (inspirationSearchQuery.value) {
                inspirationQuery.search = inspirationSearchQuery.value;
            }
LiangLiu's avatar
LiangLiu committed
5815

LiangLiu's avatar
LiangLiu committed
5816
5817
5818
5819
            // 保留分类筛选
            if (selectedInspirationCategory.value) {
                inspirationQuery.category = selectedInspirationCategory.value;
            }
LiangLiu's avatar
LiangLiu committed
5820

LiangLiu's avatar
LiangLiu committed
5821
5822
5823
5824
            // 保留当前页码
            if (inspirationCurrentPage.value > 1) {
                inspirationQuery.page = inspirationCurrentPage.value.toString();
            }
LiangLiu's avatar
LiangLiu committed
5825

LiangLiu's avatar
LiangLiu committed
5826
5827
5828
5829
            router.push({ path: '/inspirations', query: inspirationQuery });
            // 加载灵感数据
            loadInspirationData();
        };
LiangLiu's avatar
LiangLiu committed
5830

LiangLiu's avatar
LiangLiu committed
5831
5832
        const switchToLoginView = () => {
            router.push('/login');
LiangLiu's avatar
LiangLiu committed
5833

LiangLiu's avatar
LiangLiu committed
5834
        };
LiangLiu's avatar
LiangLiu committed
5835

LiangLiu's avatar
LiangLiu committed
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
        // 日期格式化函数
        const formatDate = (date) => {
            if (!date) return '';
            const d = new Date(date);
            return d.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
        };

        // 灵感广场相关方法
        const loadInspirationData = async (forceRefresh = false) => {
            try {
                // 如果不是强制刷新,先尝试从缓存加载
                // 构建缓存键,包含分页和过滤条件
                const cacheKey = `${TEMPLATES_CACHE_KEY}_${inspirationCurrentPage.value}_${inspirationPageSize.value}_${selectedInspirationCategory.value}_${inspirationSearchQuery.value}`;

                if (!forceRefresh) {
                const cachedData = loadFromCache(cacheKey, TEMPLATES_CACHE_EXPIRY);
                if (cachedData && cachedData.templates) {
                    console.log(`成功从缓存加载灵感模板数据${cacheKey}:`, cachedData.templates);
                    inspirationItems.value = cachedData.templates;
                    InspirationCategories.value = cachedData.all_categories;
                        // 如果有分页信息也加载
                        if (cachedData.pagination) {
                            inspirationPagination.value = cachedData.pagination;
                        }
                    preloadTemplateFilesUrl(inspirationItems.value);
                    return;
                    }
LiangLiu's avatar
LiangLiu committed
5867
5868
                }

LiangLiu's avatar
LiangLiu committed
5869
5870
                // 缓存中没有或强制刷新,从API加载
                const params = new URLSearchParams();
LiangLiu's avatar
LiangLiu committed
5871
                if (selectedInspirationCategory.value) {
LiangLiu's avatar
LiangLiu committed
5872
                    params.append('category', selectedInspirationCategory.value);
LiangLiu's avatar
LiangLiu committed
5873
                }
LiangLiu's avatar
LiangLiu committed
5874
5875
5876
5877
5878
5879
5880
5881
                if (inspirationSearchQuery.value) {
                    params.append('search', inspirationSearchQuery.value);
                }
                if (inspirationCurrentPage.value) {
                    params.append('page', inspirationCurrentPage.value.toString());
                }
                if (inspirationPageSize.value) {
                    params.append('page_size', inspirationPageSize.value.toString());
LiangLiu's avatar
LiangLiu committed
5882
5883
                }

LiangLiu's avatar
LiangLiu committed
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
                const apiUrl = `/api/v1/template/tasks${params.toString() ? '?' + params.toString() : ''}`;
                const response = await publicApiCall(apiUrl);
                if (response.ok) {
                    const data = await response.json();
                    inspirationItems.value = data.templates || [];
                    InspirationCategories.value = data.categories || [];
                    inspirationPagination.value = data.pagination || null;

                    // 缓存模板数据
                    saveToCache(cacheKey, {
                        templates: inspirationItems.value,
                        pagination: inspirationPagination.value,
                        all_categories: InspirationCategories.value,
                        category: selectedInspirationCategory.value,
                        search: inspirationSearchQuery.value,
                        page: inspirationCurrentPage.value,
                        page_size: inspirationPageSize.value,
                    });
LiangLiu's avatar
LiangLiu committed
5902

LiangLiu's avatar
LiangLiu committed
5903
5904
5905
                    console.log('缓存灵感模板数据成功:', inspirationItems.value.length, '个模板');
                    // 强制触发响应式更新
                    await nextTick();
LiangLiu's avatar
LiangLiu committed
5906

LiangLiu's avatar
LiangLiu committed
5907
5908
                    // 强制刷新分页组件
                    inspirationPaginationKey.value++;
LiangLiu's avatar
LiangLiu committed
5909

LiangLiu's avatar
LiangLiu committed
5910
5911
5912
5913
5914
5915
5916
5917
5918
                    // 使用新的模板文件预加载逻辑
                    preloadTemplateFilesUrl(inspirationItems.value);
                } else {
                    console.warn('加载模板数据失败');
                }
            } catch (error) {
                console.warn('加载模板数据失败:', error);
            }
        };
LiangLiu's avatar
LiangLiu committed
5919
5920


LiangLiu's avatar
LiangLiu committed
5921
5922
        // 选择分类
        const selectInspirationCategory = async (category) => {
LiangLiu's avatar
LiangLiu committed
5923
            isPageLoading.value = true;
LiangLiu's avatar
LiangLiu committed
5924
5925
            // 如果点击的是当前分类,不重复请求
            if (selectedInspirationCategory.value === category) {
LiangLiu's avatar
LiangLiu committed
5926
                isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
5927
5928
                return;
            }
LiangLiu's avatar
LiangLiu committed
5929

LiangLiu's avatar
LiangLiu committed
5930
5931
            // 更新分类
            selectedInspirationCategory.value = category;
LiangLiu's avatar
LiangLiu committed
5932

LiangLiu's avatar
LiangLiu committed
5933
5934
5935
            // 重置页码为1
            inspirationCurrentPage.value = 1;
            inspirationPageInput.value = 1;
LiangLiu's avatar
LiangLiu committed
5936

LiangLiu's avatar
LiangLiu committed
5937
5938
5939
            // 清空当前数据,显示加载状态
            inspirationItems.value = [];
            inspirationPagination.value = null;
LiangLiu's avatar
LiangLiu committed
5940

LiangLiu's avatar
LiangLiu committed
5941
5942
            // 重新加载数据
            await loadInspirationData(); // 强制刷新,不使用缓存
LiangLiu's avatar
LiangLiu committed
5943
            isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
5944
        };
LiangLiu's avatar
LiangLiu committed
5945

LiangLiu's avatar
LiangLiu committed
5946
5947
        // 搜索防抖定时器
        let searchTimeout = null;
LiangLiu's avatar
LiangLiu committed
5948

LiangLiu's avatar
LiangLiu committed
5949
5950
5951
5952
5953
5954
5955
        // 处理搜索
        const handleInspirationSearch = async () => {
            isLoading.value = true;
            // 清除之前的定时器
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }
LiangLiu's avatar
LiangLiu committed
5956

LiangLiu's avatar
LiangLiu committed
5957
5958
            // 设置防抖延迟
            searchTimeout = setTimeout(async () => {
LiangLiu's avatar
LiangLiu committed
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
                // 重置页码为1
                inspirationCurrentPage.value = 1;
                inspirationPageInput.value = 1;

                // 清空当前数据,显示加载状态
                inspirationItems.value = [];
                inspirationPagination.value = null;

                // 重新加载数据
                await loadInspirationData(); // 强制刷新,不使用缓存
LiangLiu's avatar
LiangLiu committed
5969
                isPageLoading.value = false;
LiangLiu's avatar
LiangLiu committed
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
            }, 500); // 500ms 防抖延迟
        };

        // 全局视频播放管理
        let currentPlayingVideo = null;
        let currentLoadingVideo = null; // 跟踪正在等待加载的视频

        // 更新视频播放按钮图标
        const updateVideoIcon = (video, isPlaying) => {
            // 查找视频容器中的播放按钮
            const container = video.closest('.relative');
            if (!container) return;

            // 查找移动端播放按钮
            const playButton = container.querySelector('button[class*="absolute"][class*="bottom-3"]');
            if (playButton) {
                const icon = playButton.querySelector('i');
                if (icon) {
                    icon.className = isPlaying ? 'fas fa-pause text-sm' : 'fas fa-play text-sm';
                }
            }
        };
LiangLiu's avatar
LiangLiu committed
5992

LiangLiu's avatar
LiangLiu committed
5993
5994
5995
5996
        // 处理视频播放结束
        const onVideoEnded = (event) => {
            const video = event.target;
            console.log('视频播放完毕:', video.src);
LiangLiu's avatar
LiangLiu committed
5997

LiangLiu's avatar
LiangLiu committed
5998
5999
            // 重置视频到开始位置
            video.currentTime = 0;
LiangLiu's avatar
LiangLiu committed
6000

LiangLiu's avatar
LiangLiu committed
6001
6002
            // 更新播放按钮图标为播放状态
            updateVideoIcon(video, false);
LiangLiu's avatar
LiangLiu committed
6003

LiangLiu's avatar
LiangLiu committed
6004
6005
6006
6007
6008
6009
            // 如果播放完毕的是当前播放的视频,清除引用
            if (currentPlayingVideo === video) {
                currentPlayingVideo = null;
                console.log('当前播放视频播放完毕');
            }
        };
LiangLiu's avatar
LiangLiu committed
6010

LiangLiu's avatar
LiangLiu committed
6011
6012
6013
        // 视频播放控制
        const playVideo = (event) => {
            const video = event.target;
LiangLiu's avatar
LiangLiu committed
6014

LiangLiu's avatar
LiangLiu committed
6015
6016
6017
6018
6019
            // 检查视频是否已加载完成
            if (video.readyState < 2) { // HAVE_CURRENT_DATA
                console.log('视频还没加载完成,忽略鼠标悬停播放');
                return;
            }
LiangLiu's avatar
LiangLiu committed
6020

LiangLiu's avatar
LiangLiu committed
6021
6022
6023
6024
6025
6026
6027
6028
            // 如果当前有视频在播放,先暂停它
            if (currentPlayingVideo && currentPlayingVideo !== video) {
                currentPlayingVideo.pause();
                currentPlayingVideo.currentTime = 0;
                // 更新上一个视频的图标
                updateVideoIcon(currentPlayingVideo, false);
                console.log('暂停上一个视频');
            }
LiangLiu's avatar
LiangLiu committed
6029

LiangLiu's avatar
LiangLiu committed
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
            // 视频已加载完成,可以播放
            video.currentTime = 0; // 从头开始播放
            video.play().then(() => {
                // 播放成功,更新当前播放视频
                currentPlayingVideo = video;
                console.log('开始播放新视频');
            }).catch(e => {
                console.log('视频播放失败:', e);
                currentPlayingVideo = null;
                video.pause();
LiangLiu's avatar
LiangLiu committed
6040
                video.currentTime = 0;
LiangLiu's avatar
LiangLiu committed
6041
6042
            });
        };
LiangLiu's avatar
LiangLiu committed
6043

LiangLiu's avatar
LiangLiu committed
6044
6045
        const pauseVideo = (event) => {
            const video = event.target;
LiangLiu's avatar
LiangLiu committed
6046

LiangLiu's avatar
LiangLiu committed
6047
6048
6049
6050
6051
            // 检查视频是否已加载完成
            if (video.readyState < 2) { // HAVE_CURRENT_DATA
                console.log('视频还没加载完成,忽略鼠标离开暂停');
                return;
            }
LiangLiu's avatar
LiangLiu committed
6052

LiangLiu's avatar
LiangLiu committed
6053
6054
            video.pause();
            video.currentTime = 0;
LiangLiu's avatar
LiangLiu committed
6055

LiangLiu's avatar
LiangLiu committed
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
            // 更新视频图标
            updateVideoIcon(video, false);

            // 如果暂停的是当前播放的视频,清除引用
            if (currentPlayingVideo === video) {
                currentPlayingVideo = null;
                console.log('暂停当前播放视频');
            }
        };

        // 移动端视频播放切换
        const toggleVideoPlay = (event) => {
            const button = event.target.closest('button');
            if (!button) {
                console.error('toggleVideoPlay: 未找到按钮元素');
                return;
            }

            const video = button.parentElement.querySelector('video');
            if (!video) {
                console.error('toggleVideoPlay: 未找到视频元素');
                return;
            }

            const icon = button.querySelector('i');
LiangLiu's avatar
LiangLiu committed
6081

LiangLiu's avatar
LiangLiu committed
6082
            if (video.paused) {
LiangLiu's avatar
LiangLiu committed
6083
6084
6085
6086
6087
6088
                // 如果当前有视频在播放,先暂停它
                if (currentPlayingVideo && currentPlayingVideo !== video) {
                    currentPlayingVideo.pause();
                    currentPlayingVideo.currentTime = 0;
                    // 更新上一个视频的图标
                    updateVideoIcon(currentPlayingVideo, false);
LiangLiu's avatar
LiangLiu committed
6089
                    console.log('暂停上一个视频(移动端)');
LiangLiu's avatar
LiangLiu committed
6090
6091
                }

LiangLiu's avatar
LiangLiu committed
6092
6093
6094
6095
6096
6097
6098
6099
6100
                // 如果当前有视频在等待加载,取消它的等待状态
                if (currentLoadingVideo && currentLoadingVideo !== video) {
                    currentLoadingVideo = null;
                    console.log('取消上一个视频的加载等待(移动端)');
                }

                // 检查视频是否已加载完成
                if (video.readyState >= 2) { // HAVE_CURRENT_DATA
                    // 视频已加载完成,直接播放
LiangLiu's avatar
LiangLiu committed
6101
                    video.currentTime = 0;
LiangLiu's avatar
LiangLiu committed
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
                    video.play().then(() => {
                        icon.className = 'fas fa-pause text-sm';
                        currentPlayingVideo = video;
                        console.log('开始播放新视频(移动端)');
                    }).catch(e => {
                        console.log('视频播放失败:', e);
                        icon.className = 'fas fa-play text-sm';
                        currentPlayingVideo = null;
                    });
                } else {
                    // 视频未加载完成,显示loading并等待
                    console.log('视频还没加载完成,等待加载(移动端), readyState:', video.readyState);
                    icon.className = 'fas fa-spinner fa-spin text-sm';
                    currentLoadingVideo = video;

                    // 主动触发视频加载
                    video.load();

                    // 设置超时保护(10秒后如果还未加载完成,重置状态)
                    const loadingTimeout = setTimeout(() => {
                        if (currentLoadingVideo === video) {
                            console.warn('视频加载超时(移动端)');
                            icon.className = 'fas fa-play text-sm';
                            currentLoadingVideo = null;
6126
                            showAlert(t('videoLoadTimeout'), 'warning');
LiangLiu's avatar
LiangLiu committed
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
                        }
                    }, 10000);

                    // 等待视频可以播放
                    const playHandler = () => {
                        clearTimeout(loadingTimeout);

                        // 检查这个视频是否仍然是当前等待加载的视频
                        if (currentLoadingVideo === video) {
                            currentLoadingVideo = null;
                            video.currentTime = 0;
                            video.play().then(() => {
                                icon.className = 'fas fa-pause text-sm';
                                currentPlayingVideo = video;
                                console.log('开始播放新视频(移动端-延迟加载)');
                            }).catch(e => {
                                console.log('视频播放失败:', e);
                                icon.className = 'fas fa-play text-sm';
                                currentPlayingVideo = null;
                            });
                        } else {
                            // 这个视频的加载等待已被取消,重置图标
                            icon.className = 'fas fa-play text-sm';
                            console.log('视频加载完成但等待已被取消(移动端)');
                        }
LiangLiu's avatar
LiangLiu committed
6152

LiangLiu's avatar
LiangLiu committed
6153
6154
6155
6156
                        // 移除事件监听器
                        video.removeEventListener('canplay', playHandler);
                        video.removeEventListener('error', errorHandler);
                    };
LiangLiu's avatar
LiangLiu committed
6157

LiangLiu's avatar
LiangLiu committed
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
                    const errorHandler = () => {
                        clearTimeout(loadingTimeout);
                        console.error('视频加载失败(移动端)');
                        icon.className = 'fas fa-play text-sm';
                        currentLoadingVideo = null;

                        // 移除事件监听器
                        video.removeEventListener('canplay', playHandler);
                        video.removeEventListener('error', errorHandler);
                    };
LiangLiu's avatar
LiangLiu committed
6168

LiangLiu's avatar
LiangLiu committed
6169
6170
6171
6172
6173
                    // 使用 canplay 事件,比 loadeddata 更适合移动端
                    video.addEventListener('canplay', playHandler, { once: true });
                    video.addEventListener('error', errorHandler, { once: true });
                }
            } else {
LiangLiu's avatar
LiangLiu committed
6174
6175
                video.pause();
                video.currentTime = 0;
LiangLiu's avatar
LiangLiu committed
6176
                icon.className = 'fas fa-play text-sm';
LiangLiu's avatar
LiangLiu committed
6177
6178
6179
6180

                // 如果暂停的是当前播放的视频,清除引用
                if (currentPlayingVideo === video) {
                    currentPlayingVideo = null;
LiangLiu's avatar
LiangLiu committed
6181
                    console.log('暂停当前播放视频(移动端)');
LiangLiu's avatar
LiangLiu committed
6182
6183
                }

LiangLiu's avatar
LiangLiu committed
6184
6185
6186
6187
6188
6189
6190
                // 如果暂停的是当前等待加载的视频,清除引用
                if (currentLoadingVideo === video) {
                    currentLoadingVideo = null;
                    console.log('取消当前等待加载的视频(移动端)');
                }
            }
        };
LiangLiu's avatar
LiangLiu committed
6191

LiangLiu's avatar
LiangLiu committed
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
        // 暂停所有视频
        const pauseAllVideos = () => {
            if (currentPlayingVideo) {
                currentPlayingVideo.pause();
                currentPlayingVideo.currentTime = 0;
                // 更新视频图标
                updateVideoIcon(currentPlayingVideo, false);
                currentPlayingVideo = null;
                console.log('暂停所有视频');
            }
LiangLiu's avatar
LiangLiu committed
6202

LiangLiu's avatar
LiangLiu committed
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
            // 清理等待加载的视频状态
            if (currentLoadingVideo) {
                // 重置等待加载的视频图标
                const loadingContainer = currentLoadingVideo.closest('.relative');
                if (loadingContainer) {
                    const loadingButton = loadingContainer.querySelector('button[class*="absolute"][class*="bottom-3"]');
                    if (loadingButton) {
                        const loadingIcon = loadingButton.querySelector('i');
                        if (loadingIcon) {
                            loadingIcon.className = 'fas fa-play text-sm';
                        }
LiangLiu's avatar
LiangLiu committed
6214
                    }
LiangLiu's avatar
LiangLiu committed
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
                }
                currentLoadingVideo = null;
                console.log('取消所有等待加载的视频');
            }
        };

        const onVideoLoaded = (event) => {
            const video = event.target;
            // 视频加载完成,准备播放
            console.log('视频加载完成:', video.src);

            // 更新视频加载状态(使用视频的实际src)
            setVideoLoaded(video.src, true);

            // 触发Vue的响应式更新
            videoLoadedStates.value = new Map(videoLoadedStates.value);
        };

        const onVideoError = (event) => {
            const video = event.target;
            console.error('视频加载失败:', video.src, event);
            const img = event.target;
            const parent = img.parentElement;
            parent.innerHTML = '<div class="w-full h-44 bg-laser-purple/20 flex items-center justify-center"><i class="fas fa-video text-gradient-icon text-xl"></i></div>';
            // 回退到图片
        };

        // 预览模板详情
        const previewTemplateDetail = (item, updateRoute = true) => {
            selectedTemplate.value = item;
            showTemplateDetailModal.value = true;

            // 只在需要时更新路由到模板详情页面
            if (updateRoute && item?.task_id) {
                router.push(`/template/${item.task_id}`);
            }
        };

        // 关闭模板详情弹窗
        const closeTemplateDetailModal = () => {
            showTemplateDetailModal.value = false;
            selectedTemplate.value = null;
            // 移除自动路由跳转,让调用方决定路由行为
        };

        // 显示图片放大
        const showImageZoom = (imageUrl) => {
            zoomedImageUrl.value = imageUrl;
            showImageZoomModal.value = true;
        };

        // 关闭图片放大弹窗
        const closeImageZoomModal = () => {
            showImageZoomModal.value = false;
            zoomedImageUrl.value = '';
        };

        // 通过后端API代理获取文件(避免CORS问题)
        const fetchFileThroughProxy = async (fileKey, fileType) => {
            try {
                // 尝试通过后端API代理获取文件
                const proxyUrl = `/api/v1/template/asset/${fileType}/${fileKey}`;
                const response = await apiRequest(proxyUrl);
LiangLiu's avatar
LiangLiu committed
6278

LiangLiu's avatar
LiangLiu committed
6279
6280
                if (response && response.ok) {
                    return await response.blob();
LiangLiu's avatar
LiangLiu committed
6281
6282
                }

LiangLiu's avatar
LiangLiu committed
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
                // 如果代理API不存在,尝试直接获取URL然后fetch
                const fileUrl = await getTemplateFileUrlAsync(fileKey, fileType);
                if (!fileUrl) {
                    return null;
                }

                // 检查是否是同源URL
                const urlObj = new URL(fileUrl, window.location.origin);
                const isSameOrigin = urlObj.origin === window.location.origin;

                if (isSameOrigin) {
                    // 同源,直接fetch
                    const directResponse = await fetch(fileUrl);
                    if (directResponse.ok) {
                        return await directResponse.blob();
                    }
                } else {
                    // 跨域,尝试使用no-cors模式(但这样无法读取响应)
                    // 或者使用img/audio元素加载(不适用于需要File对象的情况)
                    // 这里我们尝试直接fetch,如果失败会抛出错误
                    try {
                        const directResponse = await fetch(fileUrl, { mode: 'cors' });
                        if (directResponse.ok) {
                            return await directResponse.blob();
LiangLiu's avatar
LiangLiu committed
6307
                        }
LiangLiu's avatar
LiangLiu committed
6308
6309
6310
6311
                    } catch (corsError) {
                        console.warn('CORS错误,尝试使用代理:', corsError);
                        // 如果后端有代理API,应该使用上面的代理方式
                        // 如果没有,这里会返回null,然后调用方会显示错误
LiangLiu's avatar
LiangLiu committed
6312
6313
6314
                    }
                }

LiangLiu's avatar
LiangLiu committed
6315
6316
6317
6318
6319
6320
                return null;
            } catch (error) {
                console.error('获取文件失败:', error);
                return null;
            }
        };
LiangLiu's avatar
LiangLiu committed
6321

LiangLiu's avatar
LiangLiu committed
6322
6323
6324
6325
6326
6327
        // 应用模板图片
        const applyTemplateImage = async (template) => {
            if (!template?.inputs?.input_image) {
                showAlert(t('applyImageFailed'), 'danger');
                return;
            }
LiangLiu's avatar
LiangLiu committed
6328

LiangLiu's avatar
LiangLiu committed
6329
6330
6331
6332
6333
            try {
                // 先设置任务类型(如果模板有任务类型)
                if (template.task_type && (template.task_type === 'i2v' || template.task_type === 's2v')) {
                    selectedTaskId.value = template.task_type;
                }
LiangLiu's avatar
LiangLiu committed
6334

LiangLiu's avatar
LiangLiu committed
6335
6336
6337
6338
6339
                // 检查当前任务类型是否支持图片
                if (selectedTaskId.value !== 'i2v' && selectedTaskId.value !== 's2v') {
                    showAlert(t('applyImageFailed'), 'danger');
                    return;
                }
LiangLiu's avatar
LiangLiu committed
6340

LiangLiu's avatar
LiangLiu committed
6341
6342
6343
6344
6345
6346
6347
                // 获取图片URL(用于预览)
                const imageUrl = await getTemplateFileUrlAsync(template.inputs.input_image, 'images');
                if (!imageUrl) {
                    console.error('无法获取模板图片URL:', template.inputs.input_image);
                    showAlert(t('applyImageFailed'), 'danger');
                    return;
                }
LiangLiu's avatar
LiangLiu committed
6348

LiangLiu's avatar
LiangLiu committed
6349
6350
6351
6352
                // 根据任务类型设置图片
                const currentForm = getCurrentForm();
                if (currentForm) {
                    currentForm.imageUrl = imageUrl;
6353
6354
6355
6356
6357
6358
                    // Reset detected faces
                    if (selectedTaskId.value === 'i2v') {
                        i2vForm.value.detectedFaces = [];
                    } else if (selectedTaskId.value === 's2v') {
                        s2vForm.value.detectedFaces = [];
                    }
LiangLiu's avatar
LiangLiu committed
6359
6360
                }

LiangLiu's avatar
LiangLiu committed
6361
6362
                // 设置预览
                setCurrentImagePreview(imageUrl);
LiangLiu's avatar
LiangLiu committed
6363

LiangLiu's avatar
LiangLiu committed
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
                // 加载图片文件(与useTemplate相同的逻辑)
                try {
                    // 直接使用获取到的URL fetch(与useTemplate相同)
                    const imageResponse = await fetch(imageUrl);
                    if (imageResponse.ok) {
                        const blob = await imageResponse.blob();
                        // 验证返回的是图片而不是HTML
                        if (blob.type && blob.type.startsWith('text/html')) {
                            console.error('返回的是HTML而不是图片:', blob.type);
                            showAlert(t('applyImageFailed'), 'danger');
                            return;
                        }
                        const filename = template.inputs.input_image || 'template_image.jpg';
                        const file = new File([blob], filename, { type: blob.type || 'image/jpeg' });
                        if (currentForm) {
                            currentForm.imageFile = file;
                        }
                        console.log('模板图片文件已加载');
6382
6383

                        // 不再自动检测人脸,等待用户手动打开多角色模式开关
LiangLiu's avatar
LiangLiu committed
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
                    } else {
                        console.warn('Failed to fetch image from URL:', imageUrl);
                        showAlert(t('applyImageFailed'), 'danger');
                        return;
                    }
                } catch (error) {
                    console.error('Failed to load template image file:', error);
                    showAlert(t('applyImageFailed'), 'danger');
                    return;
                }
                updateUploadedContentStatus();
LiangLiu's avatar
LiangLiu committed
6395

LiangLiu's avatar
LiangLiu committed
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
                // 关闭所有弹窗的辅助函数
                const closeAllModals = () => {
                    closeTaskDetailModal(); // 使用函数确保状态完全重置
                    showVoiceTTSModal.value = false;
                    closeTemplateDetailModal(); // 使用函数确保状态完全重置
                    showImageTemplates.value = false;
                    showAudioTemplates.value = false;
                    showPromptModal.value = false;
                    closeImageZoomModal(); // 使用函数确保状态完全重置
                };
LiangLiu's avatar
LiangLiu committed
6406

LiangLiu's avatar
LiangLiu committed
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
                // 跳转到创作区域的函数
                const scrollToCreationArea = () => {
                    // 先关闭所有弹窗
                    closeAllModals();

                    // 如果不在生成页面,先切换视图
                    if (router.currentRoute.value.path !== '/generate') {
                        switchToCreateView();
                        // 等待路由切换完成后再展开和滚动
                        setTimeout(() => {
                            expandCreationArea();
                            setTimeout(() => {
                                // 滚动到顶部(TopBar 之后的位置,约60px)
                                const mainScrollable = document.querySelector('.main-scrollbar');
                                if (mainScrollable) {
                                    mainScrollable.scrollTo({
                                        top: 0,
                                        behavior: 'smooth'
                                    });
LiangLiu's avatar
LiangLiu committed
6426
                                }
LiangLiu's avatar
LiangLiu committed
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
                            }, 100);
                        }, 100);
                    } else {
                        // 已经在生成页面,直接展开和滚动
                        expandCreationArea();
                        setTimeout(() => {
                            // 滚动到顶部(TopBar 之后的位置,约60px)
                            const mainScrollable = document.querySelector('.main-scrollbar');
                            if (mainScrollable) {
                                mainScrollable.scrollTo({
                                    top: 0,
                                    behavior: 'smooth'
                                });
                            }
                        }, 100);
LiangLiu's avatar
LiangLiu committed
6442
                    }
LiangLiu's avatar
LiangLiu committed
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
                };

                showAlert(t('imageApplied'), 'success', {
                    label: t('view'),
                    onClick: scrollToCreationArea
                });
            } catch (error) {
                console.error('应用图片失败:', error);
                showAlert(t('applyImageFailed'), 'danger');
            }
        };

        // 应用模板音频
        const applyTemplateAudio = async (template) => {
            if (!template?.inputs?.input_audio) {
                showAlert(t('applyAudioFailed'), 'danger');
                return;
            }

            try {
                // 先设置任务类型(如果模板有任务类型)
                if (template.task_type && template.task_type === 's2v') {
                    selectedTaskId.value = template.task_type;
LiangLiu's avatar
LiangLiu committed
6466
6467
                }

LiangLiu's avatar
LiangLiu committed
6468
6469
6470
6471
                // 检查当前任务类型是否支持音频
                if (selectedTaskId.value !== 's2v') {
                    showAlert(t('applyAudioFailed'), 'danger');
                    return;
LiangLiu's avatar
LiangLiu committed
6472
6473
                }

LiangLiu's avatar
LiangLiu committed
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
                // 获取音频URL(用于预览)
                const audioUrl = await getTemplateFileUrlAsync(template.inputs.input_audio, 'audios');
                if (!audioUrl) {
                    console.error('无法获取模板音频URL:', template.inputs.input_audio);
                    showAlert(t('applyAudioFailed'), 'danger');
                    return;
                }

                // 设置音频文件
                const currentForm = getCurrentForm();
                if (currentForm) {
                    currentForm.audioUrl = audioUrl;
LiangLiu's avatar
LiangLiu committed
6486
6487
                }

LiangLiu's avatar
LiangLiu committed
6488
6489
                // 设置预览
                setCurrentAudioPreview(audioUrl);
LiangLiu's avatar
LiangLiu committed
6490

LiangLiu's avatar
LiangLiu committed
6491
                // 加载音频文件(与useTemplate相同的逻辑)
LiangLiu's avatar
LiangLiu committed
6492
                try {
LiangLiu's avatar
LiangLiu committed
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
                    // 直接使用获取到的URL fetch(与useTemplate相同)
                    const audioResponse = await fetch(audioUrl);
                    if (audioResponse.ok) {
                        const blob = await audioResponse.blob();
                        // 验证返回的是音频而不是HTML
                        if (blob.type && blob.type.startsWith('text/html')) {
                            console.error('返回的是HTML而不是音频:', blob.type);
                            showAlert(t('applyAudioFailed'), 'danger');
                            return;
                        }
                        const filename = template.inputs.input_audio || 'template_audio.mp3';

                        // 根据文件扩展名确定正确的MIME类型
                        let mimeType = blob.type;
                        if (!mimeType || mimeType === 'application/octet-stream') {
                            const ext = filename.toLowerCase().split('.').pop();
                            const mimeTypes = {
                                'mp3': 'audio/mpeg',
                                'wav': 'audio/wav',
                                'mp4': 'audio/mp4',
                                'aac': 'audio/aac',
                                'ogg': 'audio/ogg',
                                'm4a': 'audio/mp4'
                            };
                            mimeType = mimeTypes[ext] || 'audio/mpeg';
                        }
LiangLiu's avatar
LiangLiu committed
6519

LiangLiu's avatar
LiangLiu committed
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
                        const file = new File([blob], filename, { type: mimeType });
                        if (currentForm) {
                            currentForm.audioFile = file;
                        }
                        console.log('模板音频文件已加载');
                    } else {
                        console.warn('Failed to fetch audio from URL:', audioUrl);
                        showAlert(t('applyAudioFailed'), 'danger');
                        return;
                    }
                } catch (error) {
                    console.error('Failed to load template audio file:', error);
                    showAlert(t('applyAudioFailed'), 'danger');
LiangLiu's avatar
LiangLiu committed
6533
6534
                    return;
                }
LiangLiu's avatar
LiangLiu committed
6535
                        updateUploadedContentStatus();
LiangLiu's avatar
LiangLiu committed
6536

LiangLiu's avatar
LiangLiu committed
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
                // 关闭所有弹窗的辅助函数
                const closeAllModals = () => {
                    closeTaskDetailModal(); // 使用函数确保状态完全重置
                    showVoiceTTSModal.value = false;
                    closeTemplateDetailModal(); // 使用函数确保状态完全重置
                    showImageTemplates.value = false;
                    showAudioTemplates.value = false;
                    showPromptModal.value = false;
                    closeImageZoomModal(); // 使用函数确保状态完全重置
                };
LiangLiu's avatar
LiangLiu committed
6547

LiangLiu's avatar
LiangLiu committed
6548
6549
6550
6551
                // 跳转到创作区域的函数
                const scrollToCreationArea = () => {
                    // 先关闭所有弹窗
                    closeAllModals();
LiangLiu's avatar
LiangLiu committed
6552

LiangLiu's avatar
LiangLiu committed
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
                    // 如果不在生成页面,先切换视图
                    if (router.currentRoute.value.path !== '/generate') {
                        switchToCreateView();
                        // 等待路由切换完成后再展开和滚动
                        setTimeout(() => {
                            expandCreationArea();
                            setTimeout(() => {
                                // 滚动到顶部(TopBar 之后的位置,约60px)
                                const mainScrollable = document.querySelector('.main-scrollbar');
                                if (mainScrollable) {
                                    mainScrollable.scrollTo({
                                        top: 0,
                                        behavior: 'smooth'
                                    });
                                }
                            }, 100);
                        }, 100);
                    } else {
                        // 已经在生成页面,直接展开和滚动
                        expandCreationArea();
                        setTimeout(() => {
                            // 滚动到顶部(TopBar 之后的位置,约60px)
                            const mainScrollable = document.querySelector('.main-scrollbar');
                            if (mainScrollable) {
                                mainScrollable.scrollTo({
                                    top: 0,
                                    behavior: 'smooth'
                                });
                            }
                        }, 100);
                    }
                };
LiangLiu's avatar
LiangLiu committed
6585

LiangLiu's avatar
LiangLiu committed
6586
6587
6588
6589
6590
6591
6592
6593
6594
                showAlert(t('audioApplied'), 'success', {
                    label: t('view'),
                    onClick: scrollToCreationArea
                });
            } catch (error) {
                        console.error('应用音频失败:', error);
                        showAlert(t('applyAudioFailed'), 'danger');
            }
        };
LiangLiu's avatar
LiangLiu committed
6595

LiangLiu's avatar
LiangLiu committed
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
        // 应用模板Prompt
        const applyTemplatePrompt = (template) => {
            if (template?.params?.prompt) {
                const currentForm = getCurrentForm();
                if (currentForm) {
                    currentForm.prompt = template.params.prompt;
                    updateUploadedContentStatus();
                    showAlert(t('promptApplied'), 'success');
                }
            }
        };
LiangLiu's avatar
LiangLiu committed
6607

LiangLiu's avatar
LiangLiu committed
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
        // 复制文本到剪贴板的辅助函数(支持移动端降级)
        const copyToClipboard = async (text) => {
            // 检查是否支持现代 Clipboard API
            if (navigator.clipboard && navigator.clipboard.writeText) {
                try {
                    await navigator.clipboard.writeText(text);
                    return true;
            } catch (error) {
                    console.warn('Clipboard API 失败,尝试降级方案:', error);
                    // 降级到传统方法
                }
            }
LiangLiu's avatar
LiangLiu committed
6620

LiangLiu's avatar
LiangLiu committed
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
            // 降级方案:使用传统方法(适用于移动端和不支持Clipboard API的浏览器)
            try {
                const textArea = document.createElement('textarea');
                textArea.value = text;

                // 移动端需要元素可见且可聚焦,所以先设置可见样式
                textArea.style.position = 'fixed';
                textArea.style.left = '0';
                textArea.style.top = '0';
                textArea.style.width = '2em';
                textArea.style.height = '2em';
                textArea.style.padding = '0';
                textArea.style.border = 'none';
                textArea.style.outline = 'none';
                textArea.style.boxShadow = 'none';
                textArea.style.background = 'transparent';
                textArea.style.opacity = '0';
                textArea.style.zIndex = '-1';
                textArea.setAttribute('readonly', '');
                textArea.setAttribute('aria-hidden', 'true');
                textArea.setAttribute('tabindex', '-1');

                document.body.appendChild(textArea);

                // 聚焦元素(移动端需要)
                textArea.focus();
                textArea.select();

                // 移动端需要 setSelectionRange
                if (textArea.setSelectionRange) {
                    textArea.setSelectionRange(0, text.length);
                }

                // 尝试复制
                let successful = false;
                try {
                    successful = document.execCommand('copy');
                } catch (e) {
                    console.warn('execCommand 执行失败:', e);
                }
LiangLiu's avatar
LiangLiu committed
6661

LiangLiu's avatar
LiangLiu committed
6662
6663
                // 立即移除元素
                document.body.removeChild(textArea);
LiangLiu's avatar
LiangLiu committed
6664

LiangLiu's avatar
LiangLiu committed
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
                if (successful) {
                    return true;
                } else {
                    // 如果仍然失败,尝试另一种方法:在视口中心创建可见的输入框
                    return await fallbackCopyToClipboard(text);
                }
            } catch (error) {
                console.error('复制失败,尝试备用方案:', error);
                // 尝试备用方案
                return await fallbackCopyToClipboard(text);
            }
        };

        // 备用复制方案:显示一个可选择的文本区域(Apple风格)
        const fallbackCopyToClipboard = async (text) => {
            return new Promise((resolve) => {
                // 创建遮罩层
                const overlay = document.createElement('div');
                overlay.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(0, 0, 0, 0.5);
                    backdrop-filter: blur(8px);
                    -webkit-backdrop-filter: blur(8px);
                    z-index: 10000;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                `;

                // 创建弹窗容器(Apple风格)
                const container = document.createElement('div');
                container.style.cssText = `
                    background: rgba(255, 255, 255, 0.95);
                    backdrop-filter: blur(20px) saturate(180%);
                    -webkit-backdrop-filter: blur(20px) saturate(180%);
                    border-radius: 20px;
                    padding: 24px;
                    max-width: 90%;
                    width: 100%;
                    max-width: 500px;
                    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
                `;

                // 深色模式支持
                if (document.documentElement.classList.contains('dark')) {
                    container.style.background = 'rgba(30, 30, 30, 0.95)';
                }

                const title = document.createElement('div');
                title.textContent = t('copyLink') || '复制链接';
                title.style.cssText = `
                    font-size: 18px;
                    font-weight: 600;
                    color: #1d1d1f;
                    margin-bottom: 12px;
                    text-align: center;
                `;
                if (document.documentElement.classList.contains('dark')) {
                    title.style.color = '#f5f5f7';
                }

                const message = document.createElement('div');
                message.textContent = t('pleaseCopyManually') || '请手动选择并复制下面的文本';
                message.style.cssText = `
                    color: #86868b;
                    font-size: 14px;
                    margin-bottom: 16px;
                    text-align: center;
                `;
                if (document.documentElement.classList.contains('dark')) {
                    message.style.color = '#98989d';
                }

                const input = document.createElement('input');
                input.type = 'text';
                input.value = text;
                input.readOnly = true;
                input.style.cssText = `
                    width: 100%;
                    padding: 12px 16px;
                    font-size: 14px;
                    border: 1px solid rgba(0, 0, 0, 0.1);
                    border-radius: 12px;
                    background: rgba(255, 255, 255, 0.8);
                    color: #1d1d1f;
                    margin-bottom: 16px;
                    box-sizing: border-box;
                    -webkit-appearance: none;
                    appearance: none;
                `;
                if (document.documentElement.classList.contains('dark')) {
                    input.style.border = '1px solid rgba(255, 255, 255, 0.1)';
                    input.style.background = 'rgba(44, 44, 46, 0.8)';
                    input.style.color = '#f5f5f7';
                }

                const button = document.createElement('button');
                button.textContent = t('close') || '关闭';
                button.style.cssText = `
                    width: 100%;
                    padding: 12px 24px;
                    background: var(--brand-primary, #007AFF);
                    color: white;
                    border: none;
                    border-radius: 12px;
                    cursor: pointer;
                    font-size: 15px;
                    font-weight: 600;
                    transition: all 0.2s;
                `;
                button.onmouseover = () => {
                    button.style.opacity = '0.9';
                    button.style.transform = 'scale(1.02)';
                };
                button.onmouseout = () => {
                    button.style.opacity = '1';
                    button.style.transform = 'scale(1)';
                };
LiangLiu's avatar
LiangLiu committed
6788

LiangLiu's avatar
LiangLiu committed
6789
6790
6791
6792
6793
                container.appendChild(title);
                container.appendChild(message);
                container.appendChild(input);
                container.appendChild(button);
                overlay.appendChild(container);
LiangLiu's avatar
LiangLiu committed
6794

LiangLiu's avatar
LiangLiu committed
6795
6796
6797
6798
                const close = () => {
                    document.body.removeChild(overlay);
                    resolve(false); // 返回false表示需要用户手动复制
                };
LiangLiu's avatar
LiangLiu committed
6799

LiangLiu's avatar
LiangLiu committed
6800
6801
6802
6803
                button.onclick = close;
                overlay.onclick = (e) => {
                    if (e.target === overlay) close();
                };
LiangLiu's avatar
LiangLiu committed
6804

LiangLiu's avatar
LiangLiu committed
6805
                document.body.appendChild(overlay);
LiangLiu's avatar
LiangLiu committed
6806

LiangLiu's avatar
LiangLiu committed
6807
6808
6809
6810
6811
6812
                // 选中文本(延迟以确保DOM已渲染)
                setTimeout(() => {
                    input.focus();
                    input.select();
                    if (input.setSelectionRange) {
                        input.setSelectionRange(0, text.length);
LiangLiu's avatar
LiangLiu committed
6813
                    }
LiangLiu's avatar
LiangLiu committed
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
                }, 150);
            });
        };

        // 复制Prompt到剪贴板
        const copyPrompt = async (promptText) => {
            if (!promptText) return;

            try {
                // 使用辅助函数复制,支持移动端
                const success = await copyToClipboard(promptText);
                if (success) {
                showAlert(t('promptCopied'), 'success');
                }
                // 如果返回false,说明已经显示了手动复制的弹窗,不需要额外提示
            } catch (error) {
                console.error('复制Prompt失败:', error);
                showAlert(t('copyFailed'), 'error');
            }
        };
LiangLiu's avatar
LiangLiu committed
6834

LiangLiu's avatar
LiangLiu committed
6835
6836
6837
        // 使用模板
        const useTemplate = async (item) => {
            if (!item) {
6838
                showAlert(t('templateDataIncomplete'), 'danger');
LiangLiu's avatar
LiangLiu committed
6839
6840
6841
                return;
            }
            console.log('使用模板:', item);
LiangLiu's avatar
LiangLiu committed
6842

LiangLiu's avatar
LiangLiu committed
6843
6844
6845
            try {
                // 开始模板加载
                templateLoading.value = true;
LiangLiu's avatar
LiangLiu committed
6846
                templateLoadingMessage.value = t('prefillLoadingTemplate');
LiangLiu's avatar
LiangLiu committed
6847

LiangLiu's avatar
LiangLiu committed
6848
6849
                // 先设置任务类型
                selectedTaskId.value = item.task_type;
LiangLiu's avatar
LiangLiu committed
6850

LiangLiu's avatar
LiangLiu committed
6851
6852
                // 获取当前表单
                const currentForm = getCurrentForm();
LiangLiu's avatar
LiangLiu committed
6853

LiangLiu's avatar
LiangLiu committed
6854
6855
6856
6857
6858
                // 设置表单数据
                currentForm.prompt = item.params?.prompt || '';
                currentForm.negative_prompt = item.params?.negative_prompt || '';
                currentForm.seed = item.params?.seed || 42;
                currentForm.model_cls = item.model_cls || '';
6859
                currentForm.stage = item.stage || '';
LiangLiu's avatar
LiangLiu committed
6860

LiangLiu's avatar
LiangLiu committed
6861
6862
6863
6864
6865
6866
                // 立即关闭模板详情并切换到创建视图,后续资源异步加载
                showTemplateDetailModal.value = false;
                selectedTemplate.value = null;
                isCreationAreaExpanded.value = true;
                switchToCreateView();

LiangLiu's avatar
LiangLiu committed
6867
6868
                // 创建加载Promise数组
                const loadingPromises = [];
LiangLiu's avatar
LiangLiu committed
6869

LiangLiu's avatar
LiangLiu committed
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
                // 如果有输入图片,先获取正确的URL,然后加载文件
                if (item.inputs && item.inputs.input_image) {
                    // 异步获取图片URL
                    const imageLoadPromise = new Promise(async (resolve) => {
                        try {
                            // 先获取正确的URL
                            const imageUrl = await getTemplateFileUrlAsync(item.inputs.input_image, 'images');
                            if (!imageUrl) {
                                console.warn('无法获取模板图片URL:', item.inputs.input_image);
                                resolve();
                                return;
                            }
LiangLiu's avatar
LiangLiu committed
6882

LiangLiu's avatar
LiangLiu committed
6883
6884
6885
                            currentForm.imageUrl = imageUrl;
                            setCurrentImagePreview(imageUrl); // 设置正确的URL作为预览
                            console.log('模板输入图片URL:', imageUrl);
LiangLiu's avatar
LiangLiu committed
6886

6887
6888
6889
6890
6891
6892
6893
                            // Reset detected faces
                            if (selectedTaskId.value === 'i2v') {
                                i2vForm.value.detectedFaces = [];
                            } else if (selectedTaskId.value === 's2v') {
                                s2vForm.value.detectedFaces = [];
                            }

LiangLiu's avatar
LiangLiu committed
6894
6895
6896
6897
6898
6899
6900
6901
                            // 加载图片文件
                            const imageResponse = await fetch(imageUrl);
                            if (imageResponse.ok) {
                                const blob = await imageResponse.blob();
                                const filename = item.inputs.input_image;
                                const file = new File([blob], filename, { type: blob.type });
                                currentForm.imageFile = file;
                                console.log('模板图片文件已加载');
6902
6903

                                // 不再自动检测人脸,等待用户手动打开多角色模式开关
LiangLiu's avatar
LiangLiu committed
6904
6905
6906
6907
6908
6909
6910
                            } else {
                                console.warn('Failed to fetch image from URL:', imageUrl);
                            }
                        } catch (error) {
                            console.warn('Failed to load template image file:', error);
                        }
                        resolve();
LiangLiu's avatar
LiangLiu committed
6911
                    });
LiangLiu's avatar
LiangLiu committed
6912
6913
                    loadingPromises.push(imageLoadPromise);
                }
LiangLiu's avatar
LiangLiu committed
6914

LiangLiu's avatar
LiangLiu committed
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
                // 如果有输入音频,先获取正确的URL,然后加载文件
                if (item.inputs && item.inputs.input_audio) {
                    // 异步获取音频URL
                    const audioLoadPromise = new Promise(async (resolve) => {
                        try {
                            // 先获取正确的URL
                            const audioUrl = await getTemplateFileUrlAsync(item.inputs.input_audio, 'audios');
                            if (!audioUrl) {
                                console.warn('无法获取模板音频URL:', item.inputs.input_audio);
                                resolve();
                                return;
                            }
LiangLiu's avatar
LiangLiu committed
6927

LiangLiu's avatar
LiangLiu committed
6928
6929
6930
                            currentForm.audioUrl = audioUrl;
                            setCurrentAudioPreview(audioUrl); // 设置正确的URL作为预览
                            console.log('模板输入音频URL:', audioUrl);
LiangLiu's avatar
LiangLiu committed
6931

LiangLiu's avatar
LiangLiu committed
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
                            // 加载音频文件
                            const audioResponse = await fetch(audioUrl);
                            if (audioResponse.ok) {
                                const blob = await audioResponse.blob();
                                const filename = item.inputs.input_audio;

                                // 根据文件扩展名确定正确的MIME类型
                                let mimeType = blob.type;
                                if (!mimeType || mimeType === 'application/octet-stream') {
                                    const ext = filename.toLowerCase().split('.').pop();
                                    const mimeTypes = {
                                        'mp3': 'audio/mpeg',
                                        'wav': 'audio/wav',
                                        'mp4': 'audio/mp4',
                                        'aac': 'audio/aac',
                                        'ogg': 'audio/ogg',
                                        'm4a': 'audio/mp4'
                                    };
                                    mimeType = mimeTypes[ext] || 'audio/mpeg';
                                }
LiangLiu's avatar
LiangLiu committed
6952

LiangLiu's avatar
LiangLiu committed
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
                                const file = new File([blob], filename, { type: mimeType });
                                currentForm.audioFile = file;
                                console.log('模板音频文件已加载');
                                // 使用FileReader生成data URL,与正常上传保持一致
                                const reader = new FileReader();
                                reader.onload = (e) => {
                                    setCurrentAudioPreview(e.target.result);
                                    console.log('模板音频预览已设置:', e.target.result.substring(0, 50) + '...');
                                };
                                reader.readAsDataURL(file);
                            } else {
                                console.warn('Failed to fetch audio from URL:', audioUrl);
                            }
                        } catch (error) {
                            console.warn('Failed to load template audio file:', error);
LiangLiu's avatar
LiangLiu committed
6968
                        }
LiangLiu's avatar
LiangLiu committed
6969
                        resolve();
LiangLiu's avatar
LiangLiu committed
6970
                    });
LiangLiu's avatar
LiangLiu committed
6971
                    loadingPromises.push(audioLoadPromise);
LiangLiu's avatar
LiangLiu committed
6972
6973
                }

LiangLiu's avatar
LiangLiu committed
6974
6975
6976
                // 等待所有文件加载完成
                if (loadingPromises.length > 0) {
                    await Promise.all(loadingPromises);
LiangLiu's avatar
LiangLiu committed
6977
6978
                }

LiangLiu's avatar
LiangLiu committed
6979
6980
6981
6982
6983
6984
6985
                showAlert(`模板加载完成`, 'success');
            } catch (error) {
                console.error('应用模板失败:', error);
                showAlert(`应用模板失败: ${error.message}`, 'danger');
            } finally {
                // 结束模板加载
                templateLoading.value = false;
LiangLiu's avatar
LiangLiu committed
6986
                templateLoadingMessage.value = '';
LiangLiu's avatar
LiangLiu committed
6987
6988
6989
6990
6991
            }
        };

        // 加载更多灵感
        const loadMoreInspiration = () => {
6992
            showAlert(t('loadMoreInspirationComingSoon'), 'info');
LiangLiu's avatar
LiangLiu committed
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
        };

        // 新增:任务详情弹窗方法
        const openTaskDetailModal = (task) => {
            console.log('openTaskDetailModal called with task:', task);
            modalTask.value = task;
            showTaskDetailModal.value = true;
            // 只有不在 /generate 页面时才更新路由
            // 在 /generate 页面打开任务详情时,保持在当前页面
            const currentRoute = router.currentRoute.value;
            if (task?.task_id && currentRoute.path !== '/generate') {
                router.push(`/task/${task.task_id}`);
            }
        };

        const closeTaskDetailModal = () => {
            showTaskDetailModal.value = false;
            modalTask.value = null;
            // 只有当前路由是 /task/:id 时才跳转回 Projects
            // 如果在其他页面(如 /generate)打开的弹窗,关闭时保持在原页面
            const currentRoute = router.currentRoute.value;
            if (currentRoute.path.startsWith('/task/')) {
                // 从任务详情路由打开的,返回 Projects 页面
            router.push({ name: 'Projects' });
            }
            // 如果不是任务详情路由,不做任何路由跳转,保持在当前页面
        };
LiangLiu's avatar
LiangLiu committed
7020

LiangLiu's avatar
LiangLiu committed
7021
7022
7023
7024
7025
        // 新增:分享功能相关方法
        const generateShareUrl = (taskId) => {
            const baseUrl = window.location.origin;
            return `${baseUrl}/share/${taskId}`;
        };
LiangLiu's avatar
LiangLiu committed
7026

LiangLiu's avatar
LiangLiu committed
7027
7028
7029
7030
7031
7032
        const copyShareLink = async (taskId, shareType = 'task') => {
            try {
                const token = localStorage.getItem('accessToken');
                if (!token) {
                    showAlert(t('pleaseLoginFirst'), 'warning');
                    return;
LiangLiu's avatar
LiangLiu committed
7033
7034
                }

LiangLiu's avatar
LiangLiu committed
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
                // 调用后端接口创建分享链接
                const response = await fetch('/api/v1/share/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        task_id: taskId,
                        share_type: shareType
                    })
                });
LiangLiu's avatar
LiangLiu committed
7047

LiangLiu's avatar
LiangLiu committed
7048
7049
                if (!response.ok) {
                    throw new Error('创建分享链接失败');
LiangLiu's avatar
LiangLiu committed
7050
7051
                }

LiangLiu's avatar
LiangLiu committed
7052
7053
                const data = await response.json();
                const shareUrl = `${window.location.origin}${data.share_url}`;
LiangLiu's avatar
LiangLiu committed
7054

LiangLiu's avatar
LiangLiu committed
7055
7056
                // 使用辅助函数复制,支持移动端
                const success = await copyToClipboard(shareUrl);
LiangLiu's avatar
LiangLiu committed
7057

LiangLiu's avatar
LiangLiu committed
7058
7059
7060
7061
7062
7063
7064
                // 如果成功复制,显示成功提示
                if (success) {
                // 显示带操作按钮的alert
                showAlert(t('shareLinkCopied'), 'success', {
                    label: t('view'),
                    onClick: () => {
                        window.open(shareUrl, '_blank');
LiangLiu's avatar
LiangLiu committed
7065
                    }
LiangLiu's avatar
LiangLiu committed
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
                });
                }
                // 如果返回false,说明已经显示了手动复制的弹窗,不需要额外提示
            } catch (err) {
                console.error('复制失败:', err);
                showAlert(t('copyFailed'), 'error');
            }
        };

        const shareToSocial = (taskId, platform) => {
            const shareUrl = generateShareUrl(taskId);
            const task = modalTask.value;
            const title = task?.params?.prompt || t('aiGeneratedVideo');
            const description = t('checkOutThisAIGeneratedVideo');

            let shareUrlWithParams = '';

            switch (platform) {
                case 'twitter':
                    shareUrlWithParams = `https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(shareUrl)}`;
                    break;
                case 'facebook':
                    shareUrlWithParams = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`;
                    break;
                case 'linkedin':
                    shareUrlWithParams = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`;
                    break;
                case 'whatsapp':
                    shareUrlWithParams = `https://wa.me/?text=${encodeURIComponent(title + ' ' + shareUrl)}`;
                    break;
                case 'telegram':
                    shareUrlWithParams = `https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(title)}`;
                    break;
                case 'weibo':
                    shareUrlWithParams = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(title)}`;
                    break;
                default:
                    return;
            }
LiangLiu's avatar
LiangLiu committed
7105

LiangLiu's avatar
LiangLiu committed
7106
7107
            window.open(shareUrlWithParams, '_blank', 'width=600,height=400');
        };
LiangLiu's avatar
LiangLiu committed
7108

LiangLiu's avatar
LiangLiu committed
7109
7110
7111
7112
7113
7114
        // 新增:从路由参数打开任务详情
        const openTaskFromRoute = async (taskId) => {
            try {
                // 如果任务列表为空,先加载任务数据
                if (tasks.value.length === 0) {
                    await refreshTasks();
LiangLiu's avatar
LiangLiu committed
7115
7116
                }

LiangLiu's avatar
LiangLiu committed
7117
7118
7119
7120
                if (showTaskDetailModal.value && modalTask.value?.task_id === taskId) {
                    console.log('任务详情已打开,不重复打开');
                    return;
                }
LiangLiu's avatar
LiangLiu committed
7121

LiangLiu's avatar
LiangLiu committed
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
                // 查找任务
                const task = tasks.value.find(t => t.task_id === taskId);
                if (task) {
                    modalTask.value = task;
                    openTaskDetailModal(task);
                } else {
                    // 如果任务不在当前列表中,尝试从API获取
                    showAlert(t('taskNotFound'), 'error');
                    router.push({ name: 'Projects' });
                }
            } catch (error) {
                console.error('打开任务失败:', error);
                showAlert(t('openTaskFailed'), 'error');
                router.push({ name: 'Projects' });
            }
        };
LiangLiu's avatar
LiangLiu committed
7138

LiangLiu's avatar
LiangLiu committed
7139
7140
7141
7142
7143
        // 新增:模板分享功能相关方法
        const generateTemplateShareUrl = (templateId) => {
            const baseUrl = window.location.origin;
            return `${baseUrl}/template/${templateId}`;
        };
LiangLiu's avatar
LiangLiu committed
7144

LiangLiu's avatar
LiangLiu committed
7145
7146
7147
7148
7149
        const copyTemplateShareLink = async (templateId) => {
            try {
                const shareUrl = generateTemplateShareUrl(templateId);
                // 使用辅助函数复制,支持移动端
                const success = await copyToClipboard(shareUrl);
LiangLiu's avatar
LiangLiu committed
7150

LiangLiu's avatar
LiangLiu committed
7151
7152
7153
7154
7155
7156
                // 如果成功复制,显示成功提示
                if (success) {
                showAlert(t('templateShareLinkCopied'), 'success', {
                    label: t('view'),
                    onClick: () => {
                        window.open(shareUrl, '_blank');
LiangLiu's avatar
LiangLiu committed
7157
                    }
LiangLiu's avatar
LiangLiu committed
7158
                });
LiangLiu's avatar
LiangLiu committed
7159
                }
LiangLiu's avatar
LiangLiu committed
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
                // 如果返回false,说明已经显示了手动复制的弹窗,不需要额外提示
            } catch (err) {
                console.error('复制模板分享链接失败:', err);
                showAlert(t('copyFailed'), 'error');
            }
        };

        const shareTemplateToSocial = (templateId, platform) => {
            const shareUrl = generateTemplateShareUrl(templateId);
            const template = selectedTemplate.value;
            const title = template?.params?.prompt || t('aiGeneratedTemplate');
            const description = t('checkOutThisAITemplate');

            let shareUrlWithParams = '';

            switch (platform) {
                case 'twitter':
                    shareUrlWithParams = `https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(shareUrl)}`;
                    break;
                case 'facebook':
                    shareUrlWithParams = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`;
                    break;
                case 'linkedin':
                    shareUrlWithParams = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`;
                    break;
                case 'whatsapp':
                    shareUrlWithParams = `https://wa.me/?text=${encodeURIComponent(title + ' ' + shareUrl)}`;
                    break;
                case 'telegram':
                    shareUrlWithParams = `https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(title)}`;
                    break;
                case 'weibo':
                    shareUrlWithParams = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(title)}`;
                    break;
                default:
                    return;
            }
LiangLiu's avatar
LiangLiu committed
7197

LiangLiu's avatar
LiangLiu committed
7198
7199
            window.open(shareUrlWithParams, '_blank', 'width=600,height=400');
        };
LiangLiu's avatar
LiangLiu committed
7200

LiangLiu's avatar
LiangLiu committed
7201
7202
7203
7204
7205
7206
7207
        // 新增:从路由参数打开模板详情
        const openTemplateFromRoute = async (templateId) => {
            try {
                // 如果模板列表为空,先加载模板数据
                if (inspirationItems.value.length === 0) {
                    await loadInspirationData();
                }
LiangLiu's avatar
LiangLiu committed
7208

LiangLiu's avatar
LiangLiu committed
7209
7210
7211
7212
                if (showTemplateDetailModal.value && selectedTemplate.value?.task_id === templateId) {
                    console.log('模板详情已打开,不重复打开');
                    return;
                }
LiangLiu's avatar
LiangLiu committed
7213

LiangLiu's avatar
LiangLiu committed
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
                // 查找模板
                const template = inspirationItems.value.find(t => t.task_id === templateId);
                if (template) {
                    selectedTemplate.value = template;
                    previewTemplateDetail(template);
                } else {
                    // 如果模板不在当前列表中,尝试从API获取
                    showAlert(t('templateNotFound'), 'error');
                    router.push({ name: 'Inspirations' });
                }
            } catch (error) {
                console.error('打开模板失败:', error);
                showAlert(t('openTemplateFailed'), 'error');
                router.push({ name: 'Inspirations' });
            }
        };

        // 精选模版相关数据
        const featuredTemplates = ref([]);
        const featuredTemplatesLoading = ref(false);

        // 主题管理
7236
        const theme = ref('dark'); // 'light', 'dark' - 默认深色模式
LiangLiu's avatar
LiangLiu committed
7237
7238
7239
7240
7241
7242
7243
7244

        // 初始化主题
        const initTheme = () => {
            const savedTheme = localStorage.getItem('theme') || 'dark'; // 默认深色模式
            theme.value = savedTheme;
            applyTheme(savedTheme);
        };

7245
        // 应用主题(优化版本,减少延迟)
LiangLiu's avatar
LiangLiu committed
7246
7247
7248
        const applyTheme = (newTheme) => {
            const html = document.documentElement;

7249
7250
7251
7252
7253
7254
            // 使用 requestAnimationFrame 优化 DOM 操作
            requestAnimationFrame(() => {
                // 临时禁用过渡动画以提高切换速度
                html.classList.add('theme-transitioning');

                if (newTheme === 'dark') {
LiangLiu's avatar
LiangLiu committed
7255
                    html.classList.add('dark');
7256
                    html.style.colorScheme = 'dark';
LiangLiu's avatar
LiangLiu committed
7257
7258
                } else {
                    html.classList.remove('dark');
7259
                    html.style.colorScheme = 'light';
LiangLiu's avatar
LiangLiu committed
7260
                }
7261
7262
7263
7264
7265
7266

                // 短暂延迟后移除过渡禁用类,恢复平滑过渡
                setTimeout(() => {
                    html.classList.remove('theme-transitioning');
                }, 50);
            });
LiangLiu's avatar
LiangLiu committed
7267
7268
        };

7269
        // 切换主题(优化版本)
LiangLiu's avatar
LiangLiu committed
7270
        const toggleTheme = () => {
7271
            const themes = ['light', 'dark'];
LiangLiu's avatar
LiangLiu committed
7272
7273
7274
7275
            const currentIndex = themes.indexOf(theme.value);
            const nextIndex = (currentIndex + 1) % themes.length;
            const nextTheme = themes[nextIndex];

7276
            // 立即更新状态
LiangLiu's avatar
LiangLiu committed
7277
            theme.value = nextTheme;
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291

            // 异步保存到 localStorage,不阻塞 UI
            if (window.requestIdleCallback) {
                requestIdleCallback(() => {
                    localStorage.setItem('theme', nextTheme);
                }, { timeout: 100 });
            } else {
                // 回退方案:使用 setTimeout
                setTimeout(() => {
                    localStorage.setItem('theme', nextTheme);
                }, 0);
            }

            // 立即应用主题
LiangLiu's avatar
LiangLiu committed
7292
7293
            applyTheme(nextTheme);

7294
            // 延迟显示提示,避免阻塞主题切换
LiangLiu's avatar
LiangLiu committed
7295
7296
7297
7298
            const themeNames = {
                'light': '浅色模式',
                'dark': '深色模式'
            };
7299
7300
7301
            setTimeout(() => {
                showAlert(`已切换到${themeNames[nextTheme]}`, 'info');
            }, 100);
LiangLiu's avatar
LiangLiu committed
7302
7303
7304
7305
7306
7307
7308
7309
        };

        // 获取主题图标
        const getThemeIcon = () => {
            const iconMap = {
                'light': 'fas fa-sun',
                'dark': 'fas fa-moon'
            };
7310
            return iconMap[theme.value] || 'fas fa-moon';
LiangLiu's avatar
LiangLiu committed
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
        };

        // 不需要认证的API调用(用于获取模版数据)
        const publicApiCall = async (endpoint, options = {}) => {
            const url = `${endpoint}`;
            const headers = {
                'Content-Type': 'application/json',
                ...options.headers
            };

            const response = await fetch(url, {
                ...options,
                headers
            });
LiangLiu's avatar
LiangLiu committed
7325

LiangLiu's avatar
LiangLiu committed
7326
7327
7328
7329
7330
            if (response.status === 400) {
                const error = await response.json();
                showAlert(error.message, 'danger');
                throw new Error(error.message);
            }
LiangLiu's avatar
LiangLiu committed
7331

LiangLiu's avatar
LiangLiu committed
7332
7333
            // 添加50ms延迟,防止触发服务端频率限制
            await new Promise(resolve => setTimeout(resolve, 50));
LiangLiu's avatar
LiangLiu committed
7334

LiangLiu's avatar
LiangLiu committed
7335
7336
            return response;
        };
LiangLiu's avatar
LiangLiu committed
7337

LiangLiu's avatar
LiangLiu committed
7338
7339
7340
7341
        // 获取精选模版数据
        const loadFeaturedTemplates = async (forceRefresh = false) => {
            try {
                featuredTemplatesLoading.value = true;
LiangLiu's avatar
LiangLiu committed
7342

LiangLiu's avatar
LiangLiu committed
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
                // 构建缓存键
                const cacheKey = `featured_templates_cache`;

                if (!forceRefresh) {
                    const cachedData = loadFromCache(cacheKey, TEMPLATES_CACHE_EXPIRY);
                    if (cachedData && cachedData.templates) {
                        console.log('从缓存加载精选模版数据:', cachedData.templates.length, '');
                        featuredTemplates.value = cachedData.templates;
                        featuredTemplatesLoading.value = false;
                        return;
LiangLiu's avatar
LiangLiu committed
7353
                    }
LiangLiu's avatar
LiangLiu committed
7354
                }
LiangLiu's avatar
LiangLiu committed
7355

LiangLiu's avatar
LiangLiu committed
7356
7357
7358
7359
                // 从API获取精选模版数据(不需要认证)
                const params = new URLSearchParams();
                params.append('category', '精选');
                params.append('page_size', '50'); // 获取更多数据用于随机选择
LiangLiu's avatar
LiangLiu committed
7360

LiangLiu's avatar
LiangLiu committed
7361
7362
                const apiUrl = `/api/v1/template/tasks?${params.toString()}`;
                const response = await publicApiCall(apiUrl);
LiangLiu's avatar
LiangLiu committed
7363

LiangLiu's avatar
LiangLiu committed
7364
7365
7366
                if (response.ok) {
                    const data = await response.json();
                    const templates = data.templates || [];
LiangLiu's avatar
LiangLiu committed
7367

LiangLiu's avatar
LiangLiu committed
7368
7369
7370
7371
7372
                    // 缓存数据
                    saveToCache(cacheKey, {
                        templates: templates,
                        timestamp: Date.now()
                    });
LiangLiu's avatar
LiangLiu committed
7373

LiangLiu's avatar
LiangLiu committed
7374
7375
7376
7377
                    featuredTemplates.value = templates;
                    console.log('成功加载精选模版数据:', templates.length, '个模版');
                } else {
                    console.warn('加载精选模版数据失败');
LiangLiu's avatar
LiangLiu committed
7378
7379
                    featuredTemplates.value = [];
                }
LiangLiu's avatar
LiangLiu committed
7380
7381
7382
7383
7384
7385
7386
            } catch (error) {
                console.warn('加载精选模版数据失败:', error);
                featuredTemplates.value = [];
            } finally {
                featuredTemplatesLoading.value = false;
            }
        };
LiangLiu's avatar
LiangLiu committed
7387

LiangLiu's avatar
LiangLiu committed
7388
7389
7390
7391
        // 获取随机精选模版
        const getRandomFeaturedTemplates = async (count = 10) => {
            try {
                featuredTemplatesLoading.value = true;
LiangLiu's avatar
LiangLiu committed
7392

LiangLiu's avatar
LiangLiu committed
7393
7394
7395
7396
                // 如果当前没有数据,先加载
                if (featuredTemplates.value.length === 0) {
                    await loadFeaturedTemplates();
                }
LiangLiu's avatar
LiangLiu committed
7397

LiangLiu's avatar
LiangLiu committed
7398
7399
                // 如果数据仍然为空,返回空数组
                if (featuredTemplates.value.length === 0) {
LiangLiu's avatar
LiangLiu committed
7400
7401
7402
                    return [];
                }

LiangLiu's avatar
LiangLiu committed
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
                // 随机选择指定数量的模版
                const shuffled = [...featuredTemplates.value].sort(() => 0.5 - Math.random());
                const randomTemplates = shuffled.slice(0, count);

                return randomTemplates;
            } catch (error) {
                console.error('获取随机精选模版失败:', error);
                return [];
            } finally {
                featuredTemplatesLoading.value = false;
            }
        };
LiangLiu's avatar
LiangLiu committed
7415
7416
7417
7418
7419
7420
        const removeTtsHistoryEntry = (entryId) => {
            if (!entryId) return;
            const currentHistory = loadTtsHistory().filter(entry => entry.id !== entryId);
            saveTtsHistory(currentHistory);
        };

7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
        const loadTtsHistory = () => {
            try {
                const stored = localStorage.getItem('ttsHistory');
                if (!stored) return [];
                const parsed = JSON.parse(stored);
                ttsHistory.value = Array.isArray(parsed) ? parsed : [];
                return ttsHistory.value;
            } catch (error) {
                console.error('加载TTS历史失败:', error);
                ttsHistory.value = [];
                return [];
            }
        };
LiangLiu's avatar
LiangLiu committed
7434

7435
7436
7437
7438
7439
7440
7441
7442
        const saveTtsHistory = (historyList) => {
            try {
                localStorage.setItem('ttsHistory', JSON.stringify(historyList));
                ttsHistory.value = historyList;
            } catch (error) {
                console.error('保存TTS历史失败:', error);
            }
        };
LiangLiu's avatar
LiangLiu committed
7443

7444
7445
7446
        const addTtsHistoryEntry = (text = '', instruction = '') => {
            const trimmedText = (text || '').trim();
            const trimmedInstruction = (instruction || '').trim();
LiangLiu's avatar
LiangLiu committed
7447

7448
7449
7450
            if (!trimmedText && !trimmedInstruction) {
                return;
            }
LiangLiu's avatar
LiangLiu committed
7451

7452
            const currentHistory = loadTtsHistory();
LiangLiu's avatar
LiangLiu committed
7453

7454
7455
7456
            const existingIndex = currentHistory.findIndex(entry =>
                entry.text === trimmedText && entry.instruction === trimmedInstruction
            );
LiangLiu's avatar
LiangLiu committed
7457

7458
            const timestamp = new Date().toISOString();
LiangLiu's avatar
LiangLiu committed
7459

7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
            if (existingIndex !== -1) {
                const existingEntry = currentHistory.splice(existingIndex, 1)[0];
                existingEntry.timestamp = timestamp;
                currentHistory.unshift(existingEntry);
            } else {
                currentHistory.unshift({
                    id: Date.now(),
                    text: trimmedText,
                    instruction: trimmedInstruction,
                    timestamp
                });
            }
LiangLiu's avatar
LiangLiu committed
7472

7473
7474
7475
            if (currentHistory.length > 20) {
                currentHistory.length = 20;
            }
LiangLiu's avatar
LiangLiu committed
7476

7477
7478
7479
7480
7481
7482
7483
            saveTtsHistory(currentHistory);
        };

        const clearTtsHistory = () => {
            ttsHistory.value = [];
            localStorage.removeItem('ttsHistory');
        };
LiangLiu's avatar
LiangLiu committed
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493

export {
            // 任务类型下拉菜单
            showTaskTypeMenu,
            showModelMenu,
            isLoggedIn,
            loading,
            loginLoading,
            initLoading,
            downloadLoading,
LiangLiu's avatar
LiangLiu committed
7494
            downloadLoadingMessage,
LiangLiu's avatar
LiangLiu committed
7495
            isLoading,
LiangLiu's avatar
LiangLiu committed
7496
            isPageLoading,
LiangLiu's avatar
LiangLiu committed
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518

            // 录音相关
            isRecording,
            recordingDuration,
            startRecording,
            stopRecording,
            formatRecordingDuration,

            loginWithGitHub,
            loginWithGoogle,
            // 短信登录相关
            phoneNumber,
            verifyCode,
            smsCountdown,
            showSmsForm,
            sendSmsCode,
            loginWithSms,
            handlePhoneEnter,
            handleVerifyCodeEnter,
            toggleSmsLogin,
            submitting,
            templateLoading,
LiangLiu's avatar
LiangLiu committed
7519
            templateLoadingMessage,
LiangLiu's avatar
LiangLiu committed
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
            taskSearchQuery,
            currentUser,
            models,
            tasks,
            alert,
            showErrorDetails,
            showFailureDetails,
            confirmDialog,
            showConfirmDialog,
            showTaskDetailModal,
            modalTask,
            showVoiceTTSModal,
7532
            showPodcastModal,
LiangLiu's avatar
LiangLiu committed
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
            currentTask,
            t2vForm,
            i2vForm,
            s2vForm,
            getCurrentForm,
            i2vImagePreview,
            s2vImagePreview,
            s2vAudioPreview,
            getCurrentImagePreview,
            getCurrentAudioPreview,
7543
            getCurrentVideoPreview,
LiangLiu's avatar
LiangLiu committed
7544
7545
            setCurrentImagePreview,
            setCurrentAudioPreview,
7546
            setCurrentVideoPreview,
LiangLiu's avatar
LiangLiu committed
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
            updateUploadedContentStatus,
            availableTaskTypes,
            availableModelClasses,
            currentTaskHints,
            currentHintIndex,
            startHintRotation,
            stopHintRotation,
            filteredTasks,
            selectedTaskId,
            selectedTask,
            selectedModel,
            selectedTaskFiles,
            loadingTaskFiles,
            statusFilter,
            pagination,
            paginationInfo,
            currentTaskPage,
            taskPageSize,
            taskPageInput,
            paginationKey,
            taskMenuVisible,
            toggleTaskMenu,
            closeAllTaskMenus,
            handleClickOutside,
            showAlert,
            setLoading,
            apiCall,
            logout,
            login,
            loadModels,
            sidebarCollapsed,
            sidebarWidth,
            showExpandHint,
            showGlow,
            isDefaultStateHidden,
            hideDefaultState,
            showDefaultState,
            isCreationAreaExpanded,
            hasUploadedContent,
            isContracting,
            expandCreationArea,
            contractCreationArea,
            taskFileCache,
            taskFileCacheLoaded,
            templateFileCache,
            templateFileCacheLoaded,
            loadTaskFiles,
            downloadFile,
            handleDownloadFile,
            viewFile,
            handleImageUpload,
7598
7599
7600
7601
7602
7603
7604
            detectFacesInImage,
            faceDetecting,
            audioSeparating,
            cropFaceImage,
            updateFaceRoleName,
            toggleFaceEditing,
            saveFaceRoleName,
LiangLiu's avatar
LiangLiu committed
7605
7606
7607
7608
7609
7610
7611
            selectTask,
            selectModel,
            resetForm,
            triggerImageUpload,
            triggerAudioUpload,
            removeImage,
            removeAudio,
7612
            removeVideo,
LiangLiu's avatar
LiangLiu committed
7613
            handleAudioUpload,
7614
7615
7616
7617
7618
7619
            handleVideoUpload,
            separateAudioTracks,
            updateSeparatedAudioRole,
            updateSeparatedAudioName,
            toggleSeparatedAudioEditing,
            saveSeparatedAudioName,
LiangLiu's avatar
LiangLiu committed
7620
7621
7622
7623
7624
7625
7626
7627
7628
            loadImageAudioTemplates,
            selectImageTemplate,
            selectAudioTemplate,
            previewAudioTemplate,
            stopAudioPlayback,
            setAudioStopCallback,
            getTemplateFile,
            imageTemplates,
            audioTemplates,
7629
            mergedTemplates,
LiangLiu's avatar
LiangLiu committed
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
            showImageTemplates,
            showAudioTemplates,
            mediaModalTab,
            templatePagination,
            templatePaginationInfo,
            templateCurrentPage,
            templatePageSize,
            templatePageInput,
            templatePaginationKey,
            imageHistory,
            audioHistory,
            showTemplates,
            showHistory,
            showPromptModal,
            promptModalTab,
            submitTask,
            fileToBase64,
            formatTime,
            refreshTasks,
            goToPage,
            jumpToPage,
            getVisiblePages,
            goToTemplatePage,
            jumpToTemplatePage,
            getVisibleTemplatePages,
            goToInspirationPage,
            jumpToInspirationPage,
            getVisibleInspirationPages,
            preloadTaskFilesUrl,
            preloadTemplateFilesUrl,
            loadTaskFilesFromCache,
            saveTaskFilesToCache,
            getTaskFileFromCache,
            setTaskFileToCache,
            getTaskFileUrlFromApi,
            getTaskFileUrlSync,
7666
7667
7668
7669
7670
7671
7672
7673
            // Podcast 音频缓存
            podcastAudioCache,
            podcastAudioCacheLoaded,
            loadPodcastAudioFromCache,
            savePodcastAudioToCache,
            getPodcastAudioFromCache,
            setPodcastAudioToCache,
            getPodcastAudioUrlFromApi,
LiangLiu's avatar
LiangLiu committed
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
            getTemplateFileUrlFromApi,
            getTemplateFileUrl,
            getTemplateFileUrlAsync,
            createTemplateFileUrlRef,
            createTaskFileUrlRef,
            loadTemplateFilesFromCache,
            saveTemplateFilesToCache,
            loadFromCache,
            saveToCache,
            clearAllCache,
            getStatusBadgeClass,
            viewSingleResult,
            cancelTask,
            resumeTask,
            deleteTask,
            startPollingTask,
            stopPollingTask,
            reuseTask,
            showTaskCreator,
            toggleSidebar,
            clearPrompt,
            getTaskItemClass,
            getStatusIndicatorClass,
            getTaskTypeBtnClass,
            getModelBtnClass,
            getTaskTypeIcon,
            getTaskTypeName,
            getPromptPlaceholder,
            getStatusTextClass,
            getImagePreview,
            getTaskInputUrl,
            getTaskInputImage,
            getTaskInputAudio,
            getTaskFileUrl,
            getHistoryImageUrl,
            getUserAvatarUrl,
            getCurrentImagePreviewUrl,
            getCurrentAudioPreviewUrl,
7712
            getCurrentVideoPreviewUrl,
LiangLiu's avatar
LiangLiu committed
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
            handleThumbnailError,
            handleImageError,
            handleImageLoad,
            handleAudioError,
            handleAudioLoad,
            getTaskStatusDisplay,
            getTaskStatusColor,
            getTaskStatusIcon,
            getTaskDuration,
            getRelativeTime,
            getTaskHistory,
            getActiveTasks,
            getOverallProgress,
            getProgressTitle,
            getProgressInfo,
            getSubtaskProgress,
            getSubtaskStatusText,
            formatEstimatedTime,
            formatDuration,
            searchTasks,
            filterTasksByStatus,
            filterTasksByType,
            getAlertClass,
            getAlertBorderClass,
            getAlertTextClass,
            getAlertIcon,
            getAlertIconBgClass,
            getPromptTemplates,
            selectPromptTemplate,
            promptHistory,
            getPromptHistory,
            addTaskToHistory,
            getLocalTaskHistory,
            selectPromptHistory,
            clearPromptHistory,
            getImageHistory,
            getAudioHistory,
            selectImageHistory,
            selectAudioHistory,
            previewAudioHistory,
            clearImageHistory,
            clearAudioHistory,
            clearLocalStorage,
            getAudioMimeType,
            getAuthHeaders,
            startResize,
            sidebar,
            switchToCreateView,
            switchToProjectsView,
            switchToInspirationView,
            switchToLoginView,
            openTaskDetailModal,
            closeTaskDetailModal,
            generateShareUrl,
            copyShareLink,
            shareToSocial,
            openTaskFromRoute,
            generateTemplateShareUrl,
            copyTemplateShareLink,
            shareTemplateToSocial,
            openTemplateFromRoute,
            // 灵感广场相关
            inspirationSearchQuery,
            selectedInspirationCategory,
            inspirationItems,
            InspirationCategories,
            loadInspirationData,
            selectInspirationCategory,
            handleInspirationSearch,
            loadMoreInspiration,
            inspirationPagination,
            inspirationPaginationInfo,
            // 精选模版相关
            featuredTemplates,
            featuredTemplatesLoading,
            loadFeaturedTemplates,
            getRandomFeaturedTemplates,
            inspirationCurrentPage,
            inspirationPageSize,
            inspirationPageInput,
            inspirationPaginationKey,
            // 工具函数
            formatDate,
            // 模板详情弹窗相关
            showTemplateDetailModal,
            selectedTemplate,
            previewTemplateDetail,
            closeTemplateDetailModal,
            useTemplate,
            // 图片放大弹窗相关
            showImageZoomModal,
            zoomedImageUrl,
            showImageZoom,
            closeImageZoomModal,
            // 模板素材应用相关
            applyTemplateImage,
            applyTemplateAudio,
            applyTemplatePrompt,
            copyPrompt,
            // 视频播放控制
            playVideo,
            pauseVideo,
            toggleVideoPlay,
            pauseAllVideos,
            updateVideoIcon,
            onVideoLoaded,
            onVideoError,
            onVideoEnded,
            applyMobileStyles,
            handleLoginCallback,
            init,
            validateToken,
            pollingInterval,
            pollingTasks,
            apiRequest,
            // 主题相关
            theme,
            initTheme,
            toggleTheme,
            getThemeIcon,
LiangLiu's avatar
LiangLiu committed
7833
7834
7835
7836
7837
7838
            loadTtsHistory,
            removeTtsHistoryEntry,
            ttsHistory,
            addTtsHistoryEntry,
            saveTtsHistory,
            clearTtsHistory,
LiangLiu's avatar
LiangLiu committed
7839
        };