Generate.vue 185 KB
Newer Older
LiangLiu's avatar
LiangLiu committed
1
<script setup>
LiangLiu's avatar
LiangLiu committed
2
3
4
import {
            submitting,
            templateLoading,
LiangLiu's avatar
LiangLiu committed
5
            templateLoadingMessage,
LiangLiu's avatar
LiangLiu committed
6
7
8
9
10
11
12
13
14
            // 任务类型下拉菜单
            showTaskTypeMenu,
            showModelMenu,

            isLoggedIn,
            loading,
            loginLoading,
            initLoading,
            downloadLoading,
LiangLiu's avatar
LiangLiu committed
15
            downloadLoadingMessage,
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

            // 录音相关
            isRecording,
            recordingDuration,
            startRecording,
            stopRecording,
            formatRecordingDuration,
            taskSearchQuery,
            currentUser,
            models,
            tasks,
            alert,
            showErrorDetails,
            showFailureDetails,
            confirmDialog,
            showConfirmDialog,
            showTaskDetailModal,
            modalTask,
            currentTask,
            t2vForm,
            i2vForm,
            s2vForm,
            getCurrentForm,
            i2vImagePreview,
            s2vImagePreview,
            s2vAudioPreview,
            getCurrentImagePreview,
            getCurrentAudioPreview,
44
            getCurrentVideoPreview,
LiangLiu's avatar
LiangLiu committed
45
46
            setCurrentImagePreview,
            setCurrentAudioPreview,
47
            setCurrentVideoPreview,
LiangLiu's avatar
LiangLiu committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
95
            updateUploadedContentStatus,
            availableTaskTypes,
            availableModelClasses,
            currentTaskHints,
            currentHintIndex,
            startHintRotation,
            stopHintRotation,
            filteredTasks,
            selectedTaskId,
            selectedTask,
            selectedModel,
            loadingTaskFiles,
            statusFilter,
            pagination,
            paginationInfo,
            currentTaskPage,
            taskPageSize,
            taskPageInput,
            paginationKey,
            taskMenuVisible,
            toggleTaskMenu,
            closeAllTaskMenus,
            handleClickOutside,
            showAlert,
            setLoading,
            apiCall,
            logout,
            loadModels,
            sidebarCollapsed,
            sidebarWidth,
            showExpandHint,
            showGlow,
            isDefaultStateHidden,
            hideDefaultState,
            showDefaultState,
            isCreationAreaExpanded,
            hasUploadedContent,
            isContracting,
            expandCreationArea,
            contractCreationArea,
            taskFileCache,
            taskFileCacheLoaded,
            templateFileCache,
            templateFileCacheLoaded,
            loadTaskFiles,
            downloadFile,
            viewFile,
            handleImageUpload,
96
97
98
99
100
101
102
            detectFacesInImage,
            faceDetecting,
            audioSeparating,
            cropFaceImage,
            updateFaceRoleName,
            toggleFaceEditing,
            saveFaceRoleName,
LiangLiu's avatar
LiangLiu committed
103
104
105
106
107
108
109
            selectTask,
            selectModel,
            resetForm,
            triggerImageUpload,
            triggerAudioUpload,
            removeImage,
            removeAudio,
110
            removeVideo,
LiangLiu's avatar
LiangLiu committed
111
            handleAudioUpload,
112
113
114
115
116
117
            handleVideoUpload,
            separateAudioTracks,
            updateSeparatedAudioRole,
            updateSeparatedAudioName,
            toggleSeparatedAudioEditing,
            saveSeparatedAudioName,
LiangLiu's avatar
LiangLiu committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
            loadImageAudioTemplates,
            selectImageTemplate,
            selectAudioTemplate,
            previewAudioTemplate,
            getTemplateFile,
            imageTemplates,
            audioTemplates,
            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,
            getTaskFileUrl,
            getTaskFileUrlSync,
            getTemplateFileUrlFromApi,
            getTemplateFileUrl,
            getTemplateFileUrlAsync,
            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,
            getHistoryImageUrl,
            getUserAvatarUrl,
            getCurrentImagePreviewUrl,
            getCurrentAudioPreviewUrl,
197
            getCurrentVideoPreviewUrl,
LiangLiu's avatar
LiangLiu committed
198
199
200
201
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
            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,
            getAudioMimeType,
            getAuthHeaders,
            startResize,
            sidebar,
            switchToCreateView,
            switchToProjectsView,
            switchToInspirationView,
            switchToLoginView,
            openTaskDetailModal,
            closeTaskDetailModal,
            // 灵感广场相关
            inspirationSearchQuery,
            selectedInspirationCategory,
            inspirationItems,
            InspirationCategories,
            loadInspirationData,
            selectInspirationCategory,
            handleInspirationSearch,
            loadMoreInspiration,
            inspirationPagination,
            inspirationPaginationInfo,
            inspirationCurrentPage,
            inspirationPageSize,
            inspirationPageInput,
            inspirationPaginationKey,
            // 精选模版相关
            featuredTemplates,
            featuredTemplatesLoading,
            loadFeaturedTemplates,
            getRandomFeaturedTemplates,
            // 工具函数
            formatDate,
            // 模板详情弹窗相关
            showTemplateDetailModal,
            selectedTemplate,
            previewTemplateDetail,
            closeTemplateDetailModal,
            useTemplate,
            // 图片放大弹窗相关
            showImageZoomModal,
            zoomedImageUrl,
            showImageZoom,
            closeImageZoomModal,
            // 模板素材应用相关
            applyTemplateImage,
            applyTemplateAudio,
            applyTemplatePrompt,
            copyPrompt,
            // 视频播放控制
            playVideo,
            pauseVideo,
            toggleVideoPlay,
            pauseAllVideos,
            updateVideoIcon,
            onVideoLoaded,
            onVideoError,
            onVideoEnded,
            generateShareUrl,
            copyShareLink,
            shareToSocial,
LiangLiu's avatar
LiangLiu committed
300
301
            openTaskFromRoute,
            showVoiceTTSModal
LiangLiu's avatar
LiangLiu committed
302
303
        } from '../utils/other'

LiangLiu's avatar
LiangLiu committed
304
305
306
307
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { watch, onMounted, computed, ref, nextTick, onUnmounted } from 'vue'
import ModelDropdown from './ModelDropdown.vue'
LiangLiu's avatar
LiangLiu committed
308
import TaskCarousel from './TaskCarousel.vue'
LiangLiu's avatar
LiangLiu committed
309
310
311
312
313
314
315
316
317

// Props
const props = defineProps({
  query: {
    type: Object,
    default: () => ({})
  }
})

318
const { t, tm, locale } = useI18n()
LiangLiu's avatar
LiangLiu committed
319
320
321
322
323
324
325
326
327
const route = useRoute()
const router = useRouter()

// 当前显示的精选模版
const currentFeaturedTemplates = ref([])

// 屏幕尺寸响应式状态
const screenSize = ref('large') // 'small' 或 'large'

LiangLiu's avatar
LiangLiu committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// 精选模版瀑布流容器高度控制
const featuredMasonryRef = ref(null)
const baseMasonryHeight = computed(() => (screenSize.value === 'large' ? 600 : 400))
const masonryHeight = ref(baseMasonryHeight.value)

const updateMasonryHeight = () => {
    const container = featuredMasonryRef.value
    if (!container) {
        masonryHeight.value = baseMasonryHeight.value
        return
    }

    const columnEls = container.querySelectorAll('[data-masonry-column]')
    if (!columnEls.length) {
        masonryHeight.value = baseMasonryHeight.value
        return
    }

    let maxBottom = 0
    columnEls.forEach((column) => {
        const bottom = column.offsetTop + column.offsetHeight
        if (bottom > maxBottom) {
            maxBottom = bottom
        }
    })

    masonryHeight.value = Math.max(Math.ceil(maxBottom) + 32, baseMasonryHeight.value)
}

const scheduleMasonryUpdate = () => {
    requestAnimationFrame(() => updateMasonryHeight())
}

LiangLiu's avatar
LiangLiu committed
361
362
363
// 拖拽状态
const isDragOver = ref(false)

LiangLiu's avatar
LiangLiu committed
364
365
366
367
368
369
370
// 音频预览播放器相关
const audioPreviewElement = ref(null)
const audioPreviewIsPlaying = ref(false)
const audioPreviewDuration = ref(0)
const audioPreviewCurrentTime = ref(0)
const audioPreviewIsDragging = ref(false)

371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
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
888
889
890
891
892
893
894
895
896
897
898
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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
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
// 分离后的音频播放器相关状态
const separatedAudioElements = ref([]) // Array of audio elements
const separatedAudioPlaying = ref({}) // { index: boolean }
const separatedAudioDuration = ref({}) // { index: number }
const separatedAudioCurrentTime = ref({}) // { index: number }
const separatedAudioIsDragging = ref({}) // { index: boolean }

// 拖拽排序相关状态
const draggedRoleIndex = ref(-1)
const draggedAudioIndex = ref(-1)
const dragOverRoleIndex = ref(-1)
const dragOverAudioIndex = ref(-1)
const dragPreviewElement = ref(null)
const dragOffset = ref({ x: 0, y: 0 })

// 计算属性:当前表单检测到的脸
const currentDetectedFaces = computed(() => {
    const form = getCurrentForm()
    return form?.detectedFaces || []
})

// 计算属性:当前表单分离后的音频
const currentSeparatedAudios = computed(() => {
    const form = getCurrentForm()
    const audios = form?.separatedAudios || []
    // Debug log
    if (audios.length > 0) {
        console.log('currentSeparatedAudios computed:', audios.length, 'audios')
    }
    return audios
})

// 计算属性:当前音频预览
const currentAudioPreview = computed(() => {
    return getCurrentAudioPreview()
})

// 记录上次分离的角色个数,避免重复分离
const lastSeparatedFaceCount = ref(0)
const lastSeparatedAudioUrl = ref('')

// 角色模式:单角色/多角色
const isMultiRoleMode = ref(false) // false = 单角色模式, true = 多角色模式(默认关闭,单人模式)

// 监听任务类型变化,切换任务时重置为单人模式
watch(selectedTaskId, (newTaskId, oldTaskId) => {
    if (newTaskId !== oldTaskId) {
        // 切换任务类型时,重置为单人模式
        isMultiRoleMode.value = false
        // 重置分离记录
        lastSeparatedFaceCount.value = 0
        lastSeparatedAudioUrl.value = ''
    }
})

// 统一监听 detectedFaces 和音频预览,当两者都存在且角色个数 > 1 时,自动分离音频
// 这样可以覆盖所有场景:上传音频、应用历史音频、使用音频模板、复用任务等
watch([currentDetectedFaces, currentAudioPreview, selectedTaskId], ([newFaces, audioUrl, taskType], [oldFaces, oldAudioUrl, oldTaskType]) => {
    // 只在 s2v 任务下处理
    if (taskType !== 's2v') {
        // 如果不是 s2v 任务,清空分离记录
        if (oldTaskType === 's2v') {
            lastSeparatedFaceCount.value = 0
            lastSeparatedAudioUrl.value = ''
        }
        return
    }

    const faceCount = newFaces?.length || 0
    const oldFaceCount = oldFaces?.length || 0

    // 如果角色个数 <= 1清空分离的音频
    if (faceCount <= 1) {
        if (oldFaceCount > 1) {
            const form = getCurrentForm()
            if (form) {
                form.separatedAudios = []
            }
            lastSeparatedFaceCount.value = 0
            lastSeparatedAudioUrl.value = ''
        }
        return
    }

    // 如果角色个数 > 1 且有音频预览
    if (faceCount > 1 && audioUrl) {
        // 检查是否需要分离(避免重复分离)
        const needsSeparation =
            faceCount !== lastSeparatedFaceCount.value ||
            audioUrl !== lastSeparatedAudioUrl.value

        if (needsSeparation) {
            console.log(`[自动音频分离] 检测到 ${faceCount} 个角色且有音频,开始分离...`, {
                faceCount,
                audioUrl: audioUrl.substring(0, 50) + '...',
                lastSeparatedFaceCount: lastSeparatedFaceCount.value,
                lastSeparatedAudioUrl: lastSeparatedAudioUrl.value?.substring(0, 50) + '...'
            })

            separateAudioTracks(audioUrl, faceCount)
                .then(() => {
                    // 分离成功,更新记录
                    lastSeparatedFaceCount.value = faceCount
                    lastSeparatedAudioUrl.value = audioUrl
                    console.log(`[自动音频分离] 分离成功,角色个数: ${faceCount}`)
                })
                .catch(error => {
                    console.error('[自动音频分离] 分离失败:', error)
                    // 分离失败,不清空记录,允许重试
                })
        } else {
            console.log(`[自动音频分离] 跳过重复分离,角色个数: ${faceCount},音频未变化`)
        }
    } else if (faceCount > 1 && !audioUrl) {
        // 有多个角色但没有音频,清空分离的音频
        const form = getCurrentForm()
        if (form && form.separatedAudios && form.separatedAudios.length > 0) {
            form.separatedAudios = []
            lastSeparatedFaceCount.value = 0
            lastSeparatedAudioUrl.value = ''
        }
    }
}, { immediate: true })

// 手动切换模式
const toggleRoleMode = async () => {
    if (selectedTaskId.value !== 's2v') return

    const form = getCurrentForm()
    if (!form) return

    const newMode = !isMultiRoleMode.value

    if (newMode) {
        // 切换到多角色模式
        isMultiRoleMode.value = true

        // 如果还没有检测到角色,调用角色识别功能
        if (!form.detectedFaces || form.detectedFaces.length === 0) {
            const imageUrl = getCurrentImagePreviewUrl()
            if (imageUrl) {
                try {
                    faceDetecting.value = true
                    await detectFacesInImage(imageUrl)
                } catch (error) {
                    console.error('Face detection failed:', error)
                    showAlert(t('faceDetectionFailed') + ': ' + (error.message || t('unknownError')), 'error')
                } finally {
                    faceDetecting.value = false
                }
            } else {
                showAlert(t('pleaseUploadImage'), 'warning')
                isMultiRoleMode.value = false
                return
            }
        }

        // 如果检测后仍然只有0个或1个角色,提示用户
        if (!form.detectedFaces || form.detectedFaces.length <= 1) {
            showAlert(t('multiRoleModeRequires'), 'info')
            return
        }

        // 如果有音频,自动分离
        if (form.audioFile && getCurrentAudioPreview()) {
            const audioDataUrl = getCurrentAudioPreview()
            if (audioDataUrl && form.detectedFaces && form.detectedFaces.length > 1) {
                try {
                    await separateAudioTracks(audioDataUrl, form.detectedFaces.length)
                } catch (error) {
                    console.error('Audio separation failed:', error)
                    showAlert(t('audioSeparationFailed') + ': ' + error.message, 'error')
                }
            }
        }
    } else {
        // 切换到单角色模式
        isMultiRoleMode.value = false

        // 清空分离的音频(单角色模式不需要分离)
        form.separatedAudios = []

        // 如果有多于1个角色的情况下切回单模式,提示用户
        if (form.detectedFaces && form.detectedFaces.length > 1) {
            showAlert(t('singleRoleModeInfo'), 'info')
        }
    }
}

// 处理删除图片,同时重置多角色模式
const handleRemoveImage = () => {
    removeImage()
    // 删除图片后,自动切回单角色模式
    if (selectedTaskId.value === 's2v' && isMultiRoleMode.value) {
        isMultiRoleMode.value = false
        const form = getCurrentForm()
        if (form) {
            form.separatedAudios = []
        }
    }
}

// 脸部放大图片编辑相关状态
const showFaceEditModal = ref(false)
const editingFaceIndex = ref(-1)
const editingFaceBbox = ref([0, 0, 0, 0]) // [x1, y1, x2, y2]
const originalImageUrl = ref('')
const imageContainerRef = ref(null)
const imageLoaded = ref(false) // 图片是否已加载完成
const imageNaturalSize = ref({ width: 0, height: 0 }) // 图片原始尺寸
const isDraggingBbox = ref(false)
const dragType = ref('move') // 'move', 'resize-n', 'resize-s', 'resize-w', 'resize-e', 'resize-nw', 'resize-ne', 'resize-sw', 'resize-se'
const dragStartPos = ref({ x: 0, y: 0 })
const dragStartBbox = ref([0, 0, 0, 0]) // 拖拽开始时的bbox坐标
const bboxOffset = ref({ x: 0, y: 0 })
const isAddingNewFace = ref(false) // 是否在新增角色模式
const faceSaving = ref(false) // 是否正在保存角色(用于显示加载状态)
const showRoleModeInfo = ref(false) // 是否显示角色模式说明

// 打开脸部编辑模态框
const openFaceEditModal = async (faceIndex) => {
    const form = getCurrentForm()
    if (!form) return

    originalImageUrl.value = getCurrentImagePreviewUrl()
    imageLoaded.value = false // 重置图片加载状态
    imageNaturalSize.value = { width: 0, height: 0 } // 重置图片尺寸

    // 如果是新增模式(faceIndex 为 -1)
    if (faceIndex === -1) {
        isAddingNewFace.value = true
        editingFaceIndex.value = -1
        showFaceEditModal.value = true

        // 等待DOM更新,确保图片元素已渲染
        await nextTick()
        await nextTick() // 多等待一次,确保图片元素完全渲染

        // 等待图片加载完成
        const img = imageContainerRef.value?.querySelector('img')
        if (img) {
            // 如果图片已经加载完成(从缓存),立即设置状态
            if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
                imageNaturalSize.value = { width: img.naturalWidth, height: img.naturalHeight }
                imageLoaded.value = true
            } else {
                // 确保图片完全加载
                await new Promise((resolve) => {
                    if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
                        imageNaturalSize.value = { width: img.naturalWidth, height: img.naturalHeight }
                        imageLoaded.value = true
                        resolve()
                    } else {
                        const onLoad = () => {
                            // 确保图片尺寸已正确设置
                            if (img.naturalWidth > 0 && img.naturalHeight > 0) {
                                imageNaturalSize.value = { width: img.naturalWidth, height: img.naturalHeight }
                                imageLoaded.value = true
                                img.removeEventListener('load', onLoad)
                                img.removeEventListener('error', onError)
                                resolve()
                            }
                        }
                        const onError = () => {
                            imageLoaded.value = true
                            img.removeEventListener('load', onLoad)
                            img.removeEventListener('error', onError)
                            resolve() // 即使加载失败也继续
                        }
                        img.addEventListener('load', onLoad)
                        img.addEventListener('error', onError)
                    }
                })
            }

            // 再次等待,确保图片尺寸已正确设置
            await nextTick()

            // 计算图片的原始尺寸
            const imgNaturalWidth = img.naturalWidth
            const imgNaturalHeight = img.naturalHeight

            if (imgNaturalWidth > 0 && imgNaturalHeight > 0) {
                imageNaturalSize.value = { width: imgNaturalWidth, height: imgNaturalHeight }
                // 默认居中,大小为图片的 30%
                const bboxSize = Math.min(imgNaturalWidth, imgNaturalHeight) * 0.3
                const centerX = imgNaturalWidth / 2
                const centerY = imgNaturalHeight / 2

                editingFaceBbox.value = [
                    centerX - bboxSize / 2,
                    centerY - bboxSize / 2,
                    centerX + bboxSize / 2,
                    centerY + bboxSize / 2
                ]

                // 标记图片已加载
                imageLoaded.value = true
                // 再次等待DOM更新,确保边界框已渲染
                await nextTick()
            } else {
                // 如果图片尺寸无效,使用默认值
                editingFaceBbox.value = [0, 0, 100, 100]
                imageLoaded.value = true
                await nextTick()
            }
        } else {
            // 如果图片还没加载,使用默认值
            editingFaceBbox.value = [0, 0, 100, 100]
            imageLoaded.value = true
            await nextTick()
        }
    } else {
        // 编辑现有角色
        if (!form.detectedFaces || !form.detectedFaces[faceIndex]) return
        isAddingNewFace.value = false
        const face = form.detectedFaces[faceIndex]
        editingFaceIndex.value = faceIndex
        editingFaceBbox.value = [...(face.bbox || [0, 0, 0, 0])]
        showFaceEditModal.value = true

        // 等待DOM更新,确保图片元素已渲染
        await nextTick()
        await nextTick() // 多等待一次,确保图片元素完全渲染

        // 等待图片加载完成,确保边界框能正确显示
        const img = imageContainerRef.value?.querySelector('img')
        if (img) {
            // 如果图片已经加载完成(从缓存),立即设置状态
            if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
                imageNaturalSize.value = { width: img.naturalWidth, height: img.naturalHeight }
                imageLoaded.value = true
            } else {
                // 确保图片完全加载
                await new Promise((resolve) => {
                    if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
                        imageNaturalSize.value = { width: img.naturalWidth, height: img.naturalHeight }
                        imageLoaded.value = true
                        resolve()
                    } else {
                        const onLoad = () => {
                            // 确保图片尺寸已正确设置
                            if (img.naturalWidth > 0 && img.naturalHeight > 0) {
                                imageNaturalSize.value = { width: img.naturalWidth, height: img.naturalHeight }
                                imageLoaded.value = true
                                img.removeEventListener('load', onLoad)
                                img.removeEventListener('error', onError)
                                resolve()
                            }
                        }
                        const onError = () => {
                            imageLoaded.value = true
                            img.removeEventListener('load', onLoad)
                            img.removeEventListener('error', onError)
                            resolve() // 即使加载失败也继续
                        }
                        img.addEventListener('load', onLoad)
                        img.addEventListener('error', onError)
                    }
                })
            }

            // 再次等待,确保图片尺寸已正确设置
            await nextTick()
        } else {
            imageLoaded.value = true
        }
    }
}

// 处理脸部编辑模态框中的图片加载
const handleFaceEditImageLoad = () => {
    const img = imageContainerRef.value?.querySelector('img')
    if (img && img.naturalWidth > 0 && img.naturalHeight > 0) {
        imageNaturalSize.value = { width: img.naturalWidth, height: img.naturalHeight }
        imageLoaded.value = true
        nextTick()
    }
}

// 处理脸部编辑模态框中的图片加载错误
const handleFaceEditImageError = () => {
    imageLoaded.value = true // 即使加载失败也显示,避免一直显示加载中
}

// 关闭脸部编辑模态框
const closeFaceEditModal = () => {
    showFaceEditModal.value = false
    editingFaceIndex.value = -1
    isDraggingBbox.value = false
    isAddingNewFace.value = false
    imageLoaded.value = false
    imageNaturalSize.value = { width: 0, height: 0 }
}

// 保存边界框更改
const saveFaceBbox = async () => {
    const form = getCurrentForm()
    if (!form) return

    // 保存当前状态(在关闭模态框之前)
    const wasAddingNewFace = isAddingNewFace.value
    const currentEditingIndex = editingFaceIndex.value // 保存编辑索引
    const currentBbox = [...editingFaceBbox.value] // 保存边界框
    const currentImageUrl = originalImageUrl.value // 保存图片URL

    // 立即关闭模态框
    closeFaceEditModal()

    // 如果是新增模式,显示加载状态
    if (wasAddingNewFace) {
        faceSaving.value = true
    }

    try {
        // 如果是新增模式
        if (wasAddingNewFace) {
            if (!form.detectedFaces) {
                form.detectedFaces = []
            }

            // 创建新角色
            const newFaceIndex = form.detectedFaces.length
            const newFace = {
                bbox: [...currentBbox],
                roleName: `角色${newFaceIndex + 1}`,
                roleIndex: newFaceIndex,
                isEditing: false,
                face_image: null
            }

            // 根据新的 bbox 坐标,从原始图片裁剪出新的 face_image
            try {
                let imageUrl = currentImageUrl
                if (imageUrl.startsWith('data:image')) {
                    // 保持 data URL 格式,可以直接使用
                } else if (!imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                    imageUrl = currentImageUrl
                }

                // 裁剪出新的 face_image
                const croppedImage = await cropFaceImage(imageUrl, newFace.bbox)

                // 移除 data URL 前缀,只保留 base64 部分(与后端返回的格式一致)
                const base64Data = croppedImage.split(',')[1] || croppedImage
                newFace.face_image = base64Data

            } catch (error) {
                console.error('Failed to crop face image:', error)
            }

            // 添加到角色列表
            form.detectedFaces.push(newFace)
            // 触发响应式更新
            form.detectedFaces = [...form.detectedFaces]

            // 如果是在 s2v 模式下且有上传的音频,自动重新分割音频
            if (selectedTaskId.value === 's2v' && getCurrentAudioPreview()) {
                try {
                    const audioDataUrl = getCurrentAudioPreview()
                    await separateAudioTracks(audioDataUrl, form.detectedFaces.length)
                } catch (error) {
                    console.error('Failed to re-separate audio after adding face:', error)
                }
            }

        } else {
            // 编辑现有角色
            if (!form.detectedFaces || currentEditingIndex < 0 || !form.detectedFaces[currentEditingIndex]) {
                console.error('Invalid editing index or face not found:', currentEditingIndex)
                return
            }

            const face = form.detectedFaces[currentEditingIndex]

            // editingFaceBbox.value 存储的是原始图片坐标 [x1, y1, x2, y2]
            face.bbox = [...currentBbox]

            // 根据新的 bbox 坐标,从原始图片裁剪出新的 face_image
            try {
                let imageUrl = currentImageUrl
                if (imageUrl.startsWith('data:image')) {
                    // 保持 data URL 格式,可以直接使用
                } else if (!imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                    imageUrl = currentImageUrl
                }

                // 裁剪出新的 face_image
                const croppedImage = await cropFaceImage(imageUrl, face.bbox)

                // 移除 data URL 前缀,只保留 base64 部分(与后端返回的格式一致)
                const base64Data = croppedImage.split(',')[1] || croppedImage
                face.face_image = base64Data

            } catch (error) {
                console.error('Failed to crop face image:', error)
            }

            // 触发响应式更新
            form.detectedFaces = [...form.detectedFaces]
        }
    } finally {
        // 隐藏加载状态
        faceSaving.value = false
    }
}

// 删除角色
const removeFace = async (faceIndex) => {
    const form = getCurrentForm()
    if (!form || !form.detectedFaces || faceIndex < 0 || faceIndex >= form.detectedFaces.length) return

    // 从角色列表中删除
    form.detectedFaces.splice(faceIndex, 1)
    // 触发响应式更新
    form.detectedFaces = [...form.detectedFaces]

    // 如果是在 s2v 模式下且有上传的音频,自动重新分割音频
    if (selectedTaskId.value === 's2v' && getCurrentAudioPreview() && form.detectedFaces.length > 0) {
        try {
            const audioDataUrl = getCurrentAudioPreview()
            await separateAudioTracks(audioDataUrl, form.detectedFaces.length)
        } catch (error) {
            console.error('Failed to re-separate audio after removing face:', error)
        }
    } else if (selectedTaskId.value === 's2v') {
        // 如果没有角色了,清空分离的音频
        s2vForm.value.separatedAudios = []
    }
}

// 获取图片缩放比例
const getImageScale = () => {
    const container = imageContainerRef.value
    if (!container) return { scaleX: 1, scaleY: 1, imgWidth: 0, imgHeight: 0 }

    const img = container.querySelector('img')
    if (!img || !img.complete) return { scaleX: 1, scaleY: 1, imgWidth: 0, imgHeight: 0 }

    const imgRect = img.getBoundingClientRect()
    const scaleX = img.naturalWidth > 0 ? imgRect.width / img.naturalWidth : 1
    const scaleY = img.naturalHeight > 0 ? imgRect.height / img.naturalHeight : 1

    return { scaleX, scaleY, imgWidth: imgRect.width, imgHeight: imgRect.height }
}

// 获取图片相对于容器的偏移
const getImageOffset = () => {
    const container = imageContainerRef.value
    if (!container) return { offsetX: 0, offsetY: 0 }

    const img = container.querySelector('img')
    if (!img) return { offsetX: 0, offsetY: 0 }

    const containerRect = container.getBoundingClientRect()
    const imgRect = img.getBoundingClientRect()

    return {
        offsetX: imgRect.left - containerRect.left,
        offsetY: imgRect.top - containerRect.top
    }
}

// 开始拖拽边界框
const startDragBbox = (event, type = 'move') => {
    event.preventDefault()
    event.stopPropagation()

    const container = imageContainerRef.value
    if (!container) return

    const img = container.querySelector('img')
    if (!img) return

    // 获取图片的实际显示尺寸和原始尺寸
    const imgRect = img.getBoundingClientRect()
    const containerRect = container.getBoundingClientRect()
    const displayWidth = imgRect.width
    const displayHeight = imgRect.height
    const naturalWidth = img.naturalWidth
    const naturalHeight = img.naturalHeight

    // 检查图片是否已加载(通过尺寸判断,而不是 complete 属性)
    // 因为 complete 可能在图片尺寸设置之前就为 true
    if (naturalWidth === 0 || naturalHeight === 0 || displayWidth === 0 || displayHeight === 0) {
        console.warn('Image not ready for dragging:', { naturalWidth, naturalHeight, displayWidth, displayHeight, complete: img.complete })
        return
    }

    // 检查 #app 是否有 transform: scale
    const appElement = document.getElementById('app')
    let appScale = 1
    if (appElement) {
        const appStyle = window.getComputedStyle(appElement)
        const transform = appStyle.transform
        if (transform && transform !== 'none') {
            const matrix = transform.match(/matrix\(([^)]+)\)/)
            if (matrix) {
                const values = matrix[1].split(',').map(v => parseFloat(v.trim()))
                appScale = values[0] || 1
            } else {
                const scaleMatch = transform.match(/scale\(([^)]+)\)/)
                if (scaleMatch) {
                    appScale = parseFloat(scaleMatch[1])
                }
            }
        }
    }

    // 计算缩放比例(补偿 #app 的缩放)
    const scaleX = displayWidth / (naturalWidth * appScale)
    const scaleY = displayHeight / (naturalHeight * appScale)

    // 图片在容器中的偏移
    const offsetX = imgRect.left - containerRect.left
    const offsetY = imgRect.top - containerRect.top

    // 边界框坐标
    const [x1, y1, x2, y2] = editingFaceBbox.value

    // 计算边界框在容器中的显示位置
    const bboxRect = {
        left: offsetX + x1 * scaleX,
        top: offsetY + y1 * scaleY,
        right: offsetX + x2 * scaleX,
        bottom: offsetY + y2 * scaleY
    }

    // 点击位置相对于容器
    const clickX = event.clientX - containerRect.left
    const clickY = event.clientY - containerRect.top

    // 如果是拖拽手柄(type 不是 'move'),直接开始拖拽
    if (type !== 'move') {
        isDraggingBbox.value = true
        dragType.value = type
        dragStartPos.value = { x: clickX, y: clickY }
        dragStartBbox.value = [...editingFaceBbox.value]
        return
    }

    // 检查点击是否在边界框内(移动模式)
    if (clickX < bboxRect.left || clickX > bboxRect.right ||
        clickY < bboxRect.top || clickY > bboxRect.bottom) {
        return
    }

    isDraggingBbox.value = true
    dragType.value = 'move'
    dragStartPos.value = { x: clickX, y: clickY }
    dragStartBbox.value = [...editingFaceBbox.value]
}

// 拖拽边界框
const dragBbox = (event) => {
    if (!isDraggingBbox.value) return

    const container = imageContainerRef.value
    if (!container) return

    const img = container.querySelector('img')
    if (!img || !img.complete) return

    // 获取图片的实际显示尺寸和原始尺寸
    const imgRect = img.getBoundingClientRect()
    const containerRect = container.getBoundingClientRect()
    const displayWidth = imgRect.width
    const displayHeight = imgRect.height
    const naturalWidth = img.naturalWidth
    const naturalHeight = img.naturalHeight

    if (naturalWidth === 0 || naturalHeight === 0) return

    // 检查 #app 是否有 transform: scale
    const appElement = document.getElementById('app')
    let appScale = 1
    if (appElement) {
        const appStyle = window.getComputedStyle(appElement)
        const transform = appStyle.transform
        if (transform && transform !== 'none') {
            const matrix = transform.match(/matrix\(([^)]+)\)/)
            if (matrix) {
                const values = matrix[1].split(',').map(v => parseFloat(v.trim()))
                appScale = values[0] || 1
            } else {
                const scaleMatch = transform.match(/scale\(([^)]+)\)/)
                if (scaleMatch) {
                    appScale = parseFloat(scaleMatch[1])
                }
            }
        }
    }

    // 计算缩放比例(补偿 #app 的缩放)
    // displayWidth 已经是经过 appScale 缩放后的尺寸,所以需要除以 appScale 来得到相对于原始图片的缩放比例
    const scaleX = displayWidth / (naturalWidth * appScale)
    const scaleY = displayHeight / (naturalHeight * appScale)

    // 图片在容器中的偏移
    const offsetX = imgRect.left - containerRect.left
    const offsetY = imgRect.top - containerRect.top

    // 鼠标当前位置相对于容器
    const containerRect2 = container.getBoundingClientRect()
    const currentX = event.clientX - containerRect2.left
    const currentY = event.clientY - containerRect2.top

    // 将坐标转换为相对于图片的位置(考虑图片在容器中的偏移)
    const imgCurrentX = currentX - offsetX
    const imgCurrentY = currentY - offsetY
    const imgStartX = dragStartPos.value.x - offsetX
    const imgStartY = dragStartPos.value.y - offsetY

    const deltaX = (imgCurrentX - imgStartX) / scaleX
    const deltaY = (imgCurrentY - imgStartY) / scaleY

    // 获取拖拽开始时的bbox
    const [startX1, startY1, startX2, startY2] = dragStartBbox.value
    const startWidth = startX2 - startX1
    const startHeight = startY2 - startY1

    let newX1 = startX1
    let newY1 = startY1
    let newX2 = startX2
    let newY2 = startY2

    // 根据拖拽类型调整bbox
    const type = dragType.value
    if (type === 'move') {
        // 移动模式:整体移动
        newX1 = startX1 + deltaX
        newY1 = startY1 + deltaY
        newX2 = startX2 + deltaX
        newY2 = startY2 + deltaY
    } else if (type === 'resize-n') {
        // 调整顶部
        newY1 = Math.min(startY1 + deltaY, startY2 - 10) // 最小高度10px
        newX1 = startX1
        newX2 = startX2
        newY2 = startY2
    } else if (type === 'resize-s') {
        // 调整底部
        newY2 = Math.max(startY2 + deltaY, startY1 + 10) // 最小高度10px
        newX1 = startX1
        newY1 = startY1
        newX2 = startX2
    } else if (type === 'resize-w') {
        // 调整左侧
        newX1 = Math.min(startX1 + deltaX, startX2 - 10) // 最小宽度10px
        newY1 = startY1
        newX2 = startX2
        newY2 = startY2
    } else if (type === 'resize-e') {
        // 调整右侧
        newX2 = Math.max(startX2 + deltaX, startX1 + 10) // 最小宽度10px
        newX1 = startX1
        newY1 = startY1
        newY2 = startY2
    } else if (type === 'resize-nw') {
        // 调整左上角
        newX1 = Math.min(startX1 + deltaX, startX2 - 10)
        newY1 = Math.min(startY1 + deltaY, startY2 - 10)
        newX2 = startX2
        newY2 = startY2
    } else if (type === 'resize-ne') {
        // 调整右上角
        newX2 = Math.max(startX2 + deltaX, startX1 + 10)
        newY1 = Math.min(startY1 + deltaY, startY2 - 10)
        newX1 = startX1
        newY2 = startY2
    } else if (type === 'resize-sw') {
        // 调整左下角
        newX1 = Math.min(startX1 + deltaX, startX2 - 10)
        newY2 = Math.max(startY2 + deltaY, startY1 + 10)
        newX2 = startX2
        newY1 = startY1
    } else if (type === 'resize-se') {
        // 调整右下角
        newX2 = Math.max(startX2 + deltaX, startX1 + 10)
        newY2 = Math.max(startY2 + deltaY, startY1 + 10)
        newX1 = startX1
        newY1 = startY1
    }

    // 边界限制:确保bbox在图片范围内
    const minSize = 10 // 最小尺寸

    // X方向边界限制
    if (newX1 < 0) {
        newX1 = 0
        if (type.includes('w') || type === 'resize-nw' || type === 'resize-sw') {
            // 如果是调整左边或左角,需要保持宽度
            newX2 = Math.max(newX2, minSize)
        }
    }
    if (newX2 > naturalWidth) {
        newX2 = naturalWidth
        if (type.includes('e') || type === 'resize-ne' || type === 'resize-se') {
            // 如果是调整右边或右角,需要保持宽度
            newX1 = Math.min(newX1, naturalWidth - minSize)
        }
    }

    // Y方向边界限制
    if (newY1 < 0) {
        newY1 = 0
        if (type.includes('n') || type === 'resize-nw' || type === 'resize-ne') {
            // 如果是调整上边或上角,需要保持高度
            newY2 = Math.max(newY2, minSize)
        }
    }
    if (newY2 > naturalHeight) {
        newY2 = naturalHeight
        if (type.includes('s') || type === 'resize-sw' || type === 'resize-se') {
            // 如果是调整下边或下角,需要保持高度
            newY1 = Math.min(newY1, naturalHeight - minSize)
        }
    }

    // 确保最小尺寸
    if (newX2 - newX1 < minSize) {
        if (type.includes('w') || type === 'resize-nw' || type === 'resize-sw') {
            newX1 = newX2 - minSize
        } else {
            newX2 = newX1 + minSize
        }
    }
    if (newY2 - newY1 < minSize) {
        if (type.includes('n') || type === 'resize-nw' || type === 'resize-ne') {
            newY1 = newY2 - minSize
        } else {
            newY2 = newY1 + minSize
        }
    }

    // 更新边界框坐标
    editingFaceBbox.value = [newX1, newY1, newX2, newY2]
}

// 结束拖拽
const endDragBbox = () => {
    isDraggingBbox.value = false
    dragType.value = 'move'
}

// 计算边界框的样式(用于在放大图片上显示)
const getBboxStyle = computed(() => {
    if (!imageContainerRef.value || editingFaceBbox.value.length !== 4 || !imageLoaded.value) {
        return {}
    }

    const container = imageContainerRef.value
    const img = container.querySelector('img')
    if (!img || !img.complete || img.naturalWidth === 0 || img.naturalHeight === 0) {
        return {}
    }

    // 获取图片的实际显示尺寸
    // getBoundingClientRect() 返回的是相对于 viewport 的坐标
    // 如果 #app 有 transform: scale(0.8),那么所有元素都会被缩放 0.8
    const imgRect = img.getBoundingClientRect()
    const containerRect = container.getBoundingClientRect()

    // 图片的实际显示尺寸(已考虑所有CSS样式和可能的缩放,包括 #app 的 0.8 缩放)
    const displayWidth = imgRect.width
    const displayHeight = imgRect.height

    // 图片的原始尺寸(naturalWidth/naturalHeight 是图片文件的真实尺寸)
    const naturalWidth = img.naturalWidth
    const naturalHeight = img.naturalHeight

    if (naturalWidth === 0 || naturalHeight === 0) {
        return {}
    }

    // 检查 #app 是否有 transform: scale
    // 如果模态框在 #app 内部,会受到 #app 的 transform 影响
    const appElement = document.getElementById('app')
    let appScale = 1
    if (appElement) {
        const appStyle = window.getComputedStyle(appElement)
        const transform = appStyle.transform
        if (transform && transform !== 'none') {
            // 解析 transform matrix 或 scale
            const matrix = transform.match(/matrix\(([^)]+)\)/)
            if (matrix) {
                const values = matrix[1].split(',').map(v => parseFloat(v.trim()))
                // matrix(a, b, c, d, tx, ty) 中,a 和 d 是缩放值
                appScale = values[0] || 1
            } else {
                const scaleMatch = transform.match(/scale\(([^)]+)\)/)
                if (scaleMatch) {
                    appScale = parseFloat(scaleMatch[1])
                }
            }
        }
    }

    // 计算缩放比例
    // displayWidth 已经是经过 appScale 缩放后的尺寸
    // 所以相对于原始图片的实际缩放比例是 displayWidth / naturalWidth
    // 但由于 #app 的缩放,边界框在模态框中的尺寸需要补偿这个缩放
    // 如果 appScale = 0.8,那么边界框的尺寸应该是 displayWidth / appScale / naturalWidth = displayWidth / (naturalWidth * appScale)
    const scaleX = displayWidth / (naturalWidth * appScale)
    const scaleY = displayHeight / (naturalHeight * appScale)

    // 图片在容器中的偏移(相对于容器)
    // 如果容器是 inline-block,图片和容器可能在同一位置
    // 我们需要检查容器是否包裹了图片,或者图片就是容器的唯一内容
    let offsetX = imgRect.left - containerRect.left
    let offsetY = imgRect.top - containerRect.top

    // 如果计算出的偏移很小(可能是浮点数误差),或者容器和图片尺寸相同,说明图片填充了整个容器
    // 在这种情况下,offset 应该为 0
    if (Math.abs(offsetX) < 1 && Math.abs(offsetY) < 1) {
        offsetX = 0
        offsetY = 0
    }

    // 边界框坐标(原始图片坐标 [x1, y1, x2, y2])
    // 这些坐标是基于原始图片尺寸的绝对像素坐标
    const [x1, y1, x2, y2] = editingFaceBbox.value

    // 转换为显示坐标
    // bbox坐标是基于原始图片尺寸的,需要乘以缩放比例得到显示尺寸
    // 注意:这里计算的是边界框在容器中的位置和尺寸
    const left = offsetX + x1 * scaleX
    const top = offsetY + y1 * scaleY
    const width = (x2 - x1) * scaleX
    const height = (y2 - y1) * scaleY

    const indicatorSize = 12

    // 确保边界框的尺寸计算正确(考虑 border 的影响)
    // border-2 = 2px,左右各2px,所以总宽度需要包含 border
    // 但由于使用了 box-sizing: border-box,所以不需要额外调整

    return {
        left: `${left}px`,
        top: `${top}px`,
        width: `${width}px`,
        height: `${height}px`,
        indicatorSize: indicatorSize,
        boxSizing: 'border-box'
    }
})

// 计算角色名字标签的样式(显示在边界框上方)
const getRoleNameLabelStyle = computed(() => {
    const bboxStyle = getBboxStyle.value
    if (!bboxStyle.left || !bboxStyle.top) {
        return {}
    }

    // 获取当前编辑的人脸信息
    const form = getCurrentForm()
    let roleName

    // 如果是新增模式
    if (isAddingNewFace.value) {
        // 计算新角色的序号:当前角色数量 + 1
        const newRoleIndex = (form?.detectedFaces?.length || 0) + 1
        roleName = `角色${newRoleIndex}`
    } else {
        // 编辑现有角色
        const face = form?.detectedFaces?.[editingFaceIndex.value]
        roleName = face?.roleName || `角色${editingFaceIndex.value + 1}`
    }

    // 计算标签位置:在边界框上方居中
    const left = parseFloat(bboxStyle.left) || 0
    const top = parseFloat(bboxStyle.top) || 0
    const width = parseFloat(bboxStyle.width) || 0

    // 标签在边界框上方,水平居中
    const labelLeft = left + width / 2

    return {
        left: `${labelLeft}px`,
        top: `${top - 28}px`,  // 在边界框上方 28px
        transform: 'translateX(-50%)',  // 水平居中
        roleName: roleName
    }
})

LiangLiu's avatar
LiangLiu committed
1356

LiangLiu's avatar
LiangLiu committed
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
// 处理提交任务并滚动到任务区域
const handleSubmitTask = async () => {
    try {
        // 提交任务,获取新任务ID
        const newTaskId = await submitTask()

        if (!newTaskId) {
            console.error('任务提交失败,未获取到任务ID')
            return
        }

        // 刷新任务列表
        await refreshTasks(true)

        // 等待 Vue 更新 DOM
        await nextTick()

        // 查找新创建的任务并设置为当前任务
        const newTask = tasks.value.find(task => task.task_id === newTaskId)
        if (newTask) {
            currentTask.value = newTask
            console.log('已将新任务设置为当前任务:', newTaskId)
        }

        // 滚动到任务区域
        scrollToTaskArea()
    } catch (error) {
        console.error('提交任务失败:', error)
    }
}

LiangLiu's avatar
LiangLiu committed
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
const handleMasonryVideoLoaded = (event) => {
    onVideoLoaded(event)
    scheduleMasonryUpdate()
}

const handleMasonryVideoEnded = (event) => {
    onVideoEnded(event)
    scheduleMasonryUpdate()
}

const handleMasonryVideoError = (event) => {
    onVideoError(event)
    scheduleMasonryUpdate()
}

const handleMasonryImageLoaded = () => {
    scheduleMasonryUpdate()
}

const handleMasonryImageError = (event) => {
    handleThumbnailError(event)
    scheduleMasonryUpdate()
}

LiangLiu's avatar
LiangLiu committed
1412
1413
1414
1415
1416
1417
// 滚动到任务区域
const scrollToTaskArea = () => {
    const taskArea = document.querySelector('.task-carousel')
    if (taskArea) {
        taskArea.scrollIntoView({
            behavior: 'smooth',
LiangLiu's avatar
LiangLiu committed
1418
            block: 'start'
LiangLiu's avatar
LiangLiu committed
1419
1420
1421
1422
        })
    }
}

LiangLiu's avatar
LiangLiu committed
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
// 滚动到生成区域
const scrollToCreationArea = () => {
    const creationArea = document.querySelector('#task-creator')
    if (creationArea) {
        creationArea.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
    }
}
LiangLiu's avatar
LiangLiu committed
1433
1434
1435
1436
1437
1438
1439
1440

// 包装 useTemplate 函数,在应用模板后滚动到生成区域
const handleUseTemplate = async (item) => {
    await useTemplate(item)
    // 等待 DOM 更新后再滚动
    await nextTick()
    // 延迟一下确保展开动画完成
    setTimeout(() => {
LiangLiu's avatar
LiangLiu committed
1441
        scrollToCreationArea()
LiangLiu's avatar
LiangLiu committed
1442
1443
1444
    }, 100)
}

LiangLiu's avatar
LiangLiu committed
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
// 处理语音合成完成后的回调
const handleTTSComplete = (audioBlob) => {
    // 创建File对象
    const audioFile = new File([audioBlob], 'tts_audio.mp3', { type: 'audio/mpeg' })

    // 模拟文件上传事件
    const dataTransfer = new DataTransfer()
    dataTransfer.items.add(audioFile)
    const fileList = dataTransfer.files

    const event = {
        target: {
            files: fileList
        }
    }

    // 处理音频上传
    handleAudioUpload(event)

    // 关闭模态框
    showVoiceTTSModal.value = false

    // 显示成功提示
1468
    showAlert(t('ttsCompleted'), 'success')
LiangLiu's avatar
LiangLiu committed
1469
}
LiangLiu's avatar
LiangLiu committed
1470

LiangLiu's avatar
LiangLiu committed
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
// 跳转到项目页面
const goToProjects = () => {
    // 构建查询参数,包含当前的表单数据
    const query = {}

    // 添加任务类型
    if (selectedTaskId.value) {
        query.taskType = selectedTaskId.value
    }

    // 添加模型
    if (selectedModel.value) {
        query.model = selectedModel.value
    }

    // 添加提示词
    if (getCurrentForm().prompt) {
        query.prompt = getCurrentForm().prompt
    }

    // 添加图片(如果有)
    if (getCurrentImagePreview()) {
        query.hasImage = 'true'
    }

    // 添加音频(如果有)
    if (getCurrentAudioPreview()) {
        query.hasAudio = 'true'
    }

    // 跳转到项目页面
    router.push({
        path: '/projects',
        query: query
    })
}

LiangLiu's avatar
LiangLiu committed
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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
// 获取随机精选模版
const refreshRandomTemplates = async () => {
    const randomTemplates = await getRandomFeaturedTemplates(10) // 获取10个模版
    currentFeaturedTemplates.value = randomTemplates
}

// 随机列布局相关函数
const generateRandomColumnLayout = (templates) => {
    if (!templates || templates.length === 0) return { columns: [], templates: [] }

    // 响应式列数控制
    const getColumnCount = () => {
        if (screenSize.value === 'large') {
            // 大屏幕:4-6列
            return Math.floor(Math.random() * 2) + 4 // 4, 5, 6列
        } else {
            // 小屏幕:2-3列
            return Math.floor(Math.random() * 2) + 2 // 2, 3列
        }
    }

    const numColumns = getColumnCount()

    // 生成随机列宽(总和为100%)
    const columnWidths = []
    let remainingWidth = 100

    for (let i = 0; i < numColumns; i++) {
        if (i === numColumns - 1) {
            // 最后一列使用剩余宽度
            columnWidths.push(remainingWidth)
        } else {
            // 随机宽度:20% 到 50%
            const minWidth = 20
            const maxWidth = Math.min(50, remainingWidth - (numColumns - i - 1) * minWidth)
            const width = Math.random() * (maxWidth - minWidth) + minWidth
            columnWidths.push(Math.round(width))
            remainingWidth -= Math.round(width)
        }
    }

    // 生成每列的起始位置(距离顶部的距离)
    const columnStartPositions = []
    for (let i = 0; i < numColumns; i++) {
        // 随机起始位置:0% 到 20%
        const startPosition = Math.random() * 20
        columnStartPositions.push(Math.round(startPosition))
    }

    // 计算每列的起始left位置
    const columnLeftPositions = []
    let currentLeft = 0
    for (let i = 0; i < numColumns; i++) {
        columnLeftPositions.push(currentLeft)
        currentLeft += columnWidths[i]
    }

    // 将模版分配到各列
    const columnTemplates = Array.from({ length: numColumns }, () => [])
    templates.forEach((template, index) => {
        const columnIndex = index % numColumns
        columnTemplates[columnIndex].push(template)
    })

    // 生成列配置
    const columns = columnWidths.map((width, index) => ({
        width: `${width}%`,
        left: `${columnLeftPositions[index]}%`,
        top: `${columnStartPositions[index]}%`,
        templates: columnTemplates[index]
    }))

    return { columns, templates }
}

// 计算属性:带随机列布局的模版
const templatesWithRandomColumns = computed(() => {
    return generateRandomColumnLayout(currentFeaturedTemplates.value)
})

LiangLiu's avatar
LiangLiu committed
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
watch(currentFeaturedTemplates, async () => {
    masonryHeight.value = baseMasonryHeight.value
    await nextTick()
    scheduleMasonryUpdate()
}, { deep: true })

watch(templatesWithRandomColumns, async () => {
    await nextTick()
    scheduleMasonryUpdate()
})

watch(baseMasonryHeight, (value) => {
    masonryHeight.value = value
    scheduleMasonryUpdate()
})

LiangLiu's avatar
LiangLiu committed
1604
1605
1606
1607
1608
1609
1610
1611
1612
// 屏幕尺寸监听器
const updateScreenSize = () => {
    screenSize.value = window.innerWidth >= 1024 ? 'large' : 'small'
}

// 监听屏幕尺寸变化
let resizeHandler = null

// 路由监听和URL同步
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
// 标记是否正在更新 URL,避免循环更新
let isUpdatingUrl = false
// 标记是否正在从路由恢复状态
let isRestoringFromRoute = false

// 存储待处理的路由参数(当 availableTaskTypes 还未加载完成时)
let pendingRouteRestore = null

// 处理路由参数恢复的函数
const restoreFromRoute = (newQuery, oldQuery) => {
    // 如果正在更新 URL,跳过处理,避免循环更新
    if (isUpdatingUrl) {
        return
    }

    // 如果 availableTaskTypes 还没有加载完成,保存参数等待处理
    if (availableTaskTypes.value.length === 0) {
        pendingRouteRestore = { newQuery, oldQuery }
        return
    }

    // 标记正在从路由恢复状态
    isRestoringFromRoute = true

LiangLiu's avatar
LiangLiu committed
1637
    // 同步URL参数到组件状态
1638
1639
1640
1641
    // 首次加载时(oldQuery 为 undefined),或者参数真正变化时才更新
    const isInitialLoad = !oldQuery

    // 处理任务类型
LiangLiu's avatar
LiangLiu committed
1642
1643
    if (newQuery.taskType) {
        const taskType = newQuery.taskType
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
        const shouldUpdate = isInitialLoad || (newQuery.taskType !== oldQuery?.taskType)
        // availableTaskTypes 是字符串数组,不是对象数组
        if (shouldUpdate && availableTaskTypes.value.includes(taskType)) {
            // 如果当前任务类型不匹配,执行 selectTask
            // 在首次加载时,即使值已经匹配,也执行 selectTask 以确保所有相关状态正确设置
            if (selectedTaskId.value !== taskType || isInitialLoad) {
                selectTask(taskType)

                // 等待 selectTask 完成后再处理 model(因为 selectTask 可能会改变 availableModelClasses)
                // 使用 nextTick 确保 selectTask 的副作用已完成
                nextTick(() => {
                    // 再次等待,确保 availableModelClasses 已更新
                    setTimeout(() => {
                        // 处理模型(在任务类型设置后)
                        if (newQuery.model) {
                            const model = newQuery.model
                            const shouldUpdateModel = isInitialLoad || (newQuery.model !== oldQuery?.model)
                            // availableModelClasses 是字符串数组,不是对象数组
                            // 在首次加载时,即使值已经匹配,也执行 selectModel 以确保所有相关状态正确设置
                            if (shouldUpdateModel && availableModelClasses.value.includes(model) && (selectedModel.value !== model || isInitialLoad)) {
                                selectModel(model)
                            }
                        }
                    }, 100)
                })
            }
        } else if (!shouldUpdate && newQuery.model) {
            // 如果任务类型没有变化,但需要更新模型
            const model = newQuery.model
            const shouldUpdateModel = isInitialLoad || (newQuery.model !== oldQuery?.model)
            // availableModelClasses 是字符串数组,不是对象数组
            // 在首次加载时,即使值已经匹配,也执行 selectModel 以确保所有相关状态正确设置
            if (shouldUpdateModel && availableModelClasses.value.includes(model) && (selectedModel.value !== model || isInitialLoad)) {
                selectModel(model)
            }
LiangLiu's avatar
LiangLiu committed
1679
        }
1680
1681
    } else if (newQuery.model && selectedTaskId.value) {
        // 如果没有任务类型参数,但任务类型已经设置,直接处理模型
LiangLiu's avatar
LiangLiu committed
1682
        const model = newQuery.model
1683
1684
1685
1686
        const shouldUpdate = isInitialLoad || (newQuery.model !== oldQuery?.model)
        // availableModelClasses 是字符串数组,不是对象数组
        // 在首次加载时,即使值已经匹配,也执行 selectModel 以确保所有相关状态正确设置
        if (shouldUpdate && availableModelClasses.value.includes(model) && (selectedModel.value !== model || isInitialLoad)) {
LiangLiu's avatar
LiangLiu committed
1687
1688
1689
            selectModel(model)
        }
    }
1690
1691
1692
1693

    // 处理 expanded 状态
    const shouldBeExpanded = newQuery.expanded === 'true'
    if (shouldBeExpanded && !isCreationAreaExpanded.value) {
LiangLiu's avatar
LiangLiu committed
1694
1695
        // 展开创建区域
        expandCreationArea()
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
    } else if (!shouldBeExpanded && isCreationAreaExpanded.value && (isInitialLoad || oldQuery?.expanded === 'true')) {
        // 如果 URL 中 expanded 从 'true' 变为其他值,收缩创建区域
        contractCreationArea()
    }

    // 恢复状态完成,使用 setTimeout 确保所有状态更新完成后再重置标志
    setTimeout(() => {
        isRestoringFromRoute = false
    }, 200)
}

// 监听 availableTaskTypes,当它加载完成后处理待处理的路由恢复
watch(availableTaskTypes, (newVal) => {
    if (newVal && newVal.length > 0 && pendingRouteRestore) {
        // availableTaskTypes 加载完成,处理待处理的路由恢复
        const { newQuery, oldQuery } = pendingRouteRestore
        pendingRouteRestore = null
        restoreFromRoute(newQuery, oldQuery)
LiangLiu's avatar
LiangLiu committed
1714
    }
1715
}, { immediate: true })
LiangLiu's avatar
LiangLiu committed
1716

1717
1718
watch(() => route.query, (newQuery, oldQuery) => {
    restoreFromRoute(newQuery, oldQuery)
LiangLiu's avatar
LiangLiu committed
1719
1720
1721
1722
1723
    // 注意:分享数据导入功能已移至 Share.vue 中的 createSimilar 函数
    // 这里不再需要处理分享数据导入
}, { immediate: true })

// 监听组件状态变化,同步到URL
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
watch([selectedTaskId, isCreationAreaExpanded, selectedModel], (newVals, oldVals) => {
    // 如果正在更新 URL 或正在从路由恢复状态,跳过处理,避免循环更新
    if (isUpdatingUrl || isRestoringFromRoute) {
        return
    }

    // 检查任务类型是否变化
    const taskTypeChanged = oldVals && oldVals[0] !== newVals[0]

    // 如果任务类型变化,检查当前模型是否属于新任务类型
    if (taskTypeChanged && selectedTaskId.value && selectedModel.value) {
        const isModelValid = availableModelClasses.value.includes(selectedModel.value)
        // 如果模型不属于新任务类型,延迟更新路由,等待模型更新完成
        if (!isModelValid) {
            setTimeout(() => {
                // 再次检查,确保模型已经更新
                if (!isUpdatingUrl && !isRestoringFromRoute) {
                    updateRouteFromState()
                }
            }, 150)
            return
        }
    }

    updateRouteFromState()
}, { deep: true })

// 更新路由的函数
const updateRouteFromState = () => {
    // 如果正在更新 URL 或正在从路由恢复状态,跳过处理,避免循环更新
    if (isUpdatingUrl || isRestoringFromRoute) {
        return
    }

    // 获取当前查询参数,保留其他参数(如分享相关的参数)
    const currentQuery = { ...route.query }
LiangLiu's avatar
LiangLiu committed
1760
    const query = {}
1761
1762

    // 只更新我们关心的参数
LiangLiu's avatar
LiangLiu committed
1763
1764
    if (selectedTaskId.value) {
        query.taskType = selectedTaskId.value
1765
1766
1767
    } else {
        // 如果任务类型被清除,也从 URL 中移除
        delete currentQuery.taskType
LiangLiu's avatar
LiangLiu committed
1768
    }
1769

LiangLiu's avatar
LiangLiu committed
1770
1771
    if (isCreationAreaExpanded.value) {
        query.expanded = 'true'
1772
1773
1774
    } else {
        // 如果创作区域收缩,从 URL 中移除 expanded 参数
        delete currentQuery.expanded
LiangLiu's avatar
LiangLiu committed
1775
    }
1776

LiangLiu's avatar
LiangLiu committed
1777
1778
    if (selectedModel.value) {
        query.model = selectedModel.value
1779
1780
1781
    } else {
        // 如果模型被清除,也从 URL 中移除
        delete currentQuery.model
LiangLiu's avatar
LiangLiu committed
1782
1783
    }

1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
    // 合并查询参数,保留其他参数
    const finalQuery = { ...currentQuery, ...query }

    // 检查是否需要更新 URL(避免不必要的更新)
    const needsUpdate =
        finalQuery.taskType !== route.query.taskType ||
        finalQuery.expanded !== route.query.expanded ||
        finalQuery.model !== route.query.model

    if (needsUpdate) {
        isUpdatingUrl = true
        // 更新URL但不触发路由监听(使用 replace 而不是 push,避免历史记录堆积)
        router.replace({ query: finalQuery }).finally(() => {
            // 使用 nextTick 确保路由更新完成后再重置标志
            nextTick(() => {
                isUpdatingUrl = false
            })
        })
    }
}
LiangLiu's avatar
LiangLiu committed
1804
1805
1806
1807


// 组件挂载时初始化
onMounted(async () => {
1808
1809
1810
    // 注意:watch route.query 已经使用 immediate: true 处理了 URL 参数的恢复
    // 这里不需要再次处理,避免重复执行
    // 如果需要额外的初始化逻辑,可以在这里添加
LiangLiu's avatar
LiangLiu committed
1811
1812
1813
1814
1815
1816
1817

    // 初始化屏幕尺寸
    updateScreenSize()

    // 添加屏幕尺寸监听器
    resizeHandler = () => {
        updateScreenSize()
LiangLiu's avatar
LiangLiu committed
1818
        scheduleMasonryUpdate()
LiangLiu's avatar
LiangLiu committed
1819
1820
1821
    }
    window.addEventListener('resize', resizeHandler)

1822
1823
1824
1825
    // 添加全局鼠标事件监听用于拖拽边界框
    document.addEventListener('mousemove', dragBbox)
    document.addEventListener('mouseup', endDragBbox)

LiangLiu's avatar
LiangLiu committed
1826
1827
1828
1829
1830
    // 加载精选模版数据
    await loadFeaturedTemplates(true)
    // 获取随机精选模版
    const randomTemplates = await getRandomFeaturedTemplates(10) // 获取10个模版
    currentFeaturedTemplates.value = randomTemplates
LiangLiu's avatar
LiangLiu committed
1831
1832
    await nextTick()
    scheduleMasonryUpdate()
LiangLiu's avatar
LiangLiu committed
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
})

// 拖拽处理函数
const handleDragOver = (e) => {
    e.preventDefault()
    e.stopPropagation()
}

const handleDragEnter = (e) => {
    e.preventDefault()
    e.stopPropagation()
    isDragOver.value = true
}

const handleDragLeave = (e) => {
    e.preventDefault()
    e.stopPropagation()
    // 只有当离开整个拖拽区域时才设置为false
    if (!e.currentTarget.contains(e.relatedTarget)) {
        isDragOver.value = false
    }
}

const handleImageDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    isDragOver.value = false

    const files = Array.from(e.dataTransfer.files)
    const imageFile = files.find(file => file.type.startsWith('image/'))

    if (imageFile) {
        // 创建FileList对象来模拟input[type="file"]的change事件
        const dataTransfer = new DataTransfer()
        dataTransfer.items.add(imageFile)
        const fileList = dataTransfer.files

        // 创建模拟的change事件
        const event = {
            target: {
                files: fileList
            }
        }

        handleImageUpload(event)
1878
        showAlert(t('imageDragSuccess'), 'success')
LiangLiu's avatar
LiangLiu committed
1879
    } else {
1880
        showAlert(t('pleaseDragImage'), 'warning')
LiangLiu's avatar
LiangLiu committed
1881
1882
1883
1884
1885
1886
1887
1888
1889
    }
}

const handleAudioDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    isDragOver.value = false

    const files = Array.from(e.dataTransfer.files)
LiangLiu's avatar
LiangLiu committed
1890
    const audioFile = files.find(file => file.type.startsWith('audio/') || file.type.startsWith('video/'))
LiangLiu's avatar
LiangLiu committed
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905

    if (audioFile) {
        // 创建FileList对象来模拟input[type="file"]的change事件
        const dataTransfer = new DataTransfer()
        dataTransfer.items.add(audioFile)
        const fileList = dataTransfer.files

        // 创建模拟的change事件
        const event = {
            target: {
                files: fileList
            }
        }

        handleAudioUpload(event)
1906
        showAlert(t('audioDragSuccess'), 'success')
LiangLiu's avatar
LiangLiu committed
1907
    } else {
1908
1909
1910
1911
1912
1913
1914
1915
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
1950
        showAlert(t('pleaseDragAudio'), 'warning')
    }
}

// 触发视频上传
const triggerVideoUpload = () => {
    // 使用 nextTick 确保 DOM 已更新
    nextTick(() => {
        const videoInput = document.querySelector('input[type="file"][data-role="video-input"]')
        if (videoInput) {
            videoInput.click()
        } else {
            console.warn('视频输入框未找到,请确保已选择 animate 任务类型')
        }
    })
}

// 处理视频拖拽上传
const handleVideoDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    isDragOver.value = false

    const files = Array.from(e.dataTransfer.files)
    const videoFile = files.find(file => file.type.startsWith('video/'))

    if (videoFile) {
        // 创建FileList对象来模拟input[type="file"]的change事件
        const dataTransfer = new DataTransfer()
        dataTransfer.items.add(videoFile)
        const fileList = dataTransfer.files

        // 创建模拟的change事件
        const event = {
            target: {
                files: fileList
            }
        }

        handleVideoUpload(event)
        showAlert(t('videoDragSuccess'), 'success')
    } else {
        showAlert(t('pleaseDragVideo'), 'warning')
LiangLiu's avatar
LiangLiu committed
1951
1952
1953
    }
}

LiangLiu's avatar
LiangLiu committed
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
// 格式化音频预览时间
const formatAudioPreviewTime = (seconds) => {
    if (!seconds || isNaN(seconds)) return '0:00'
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 切换音频预览播放/暂停
const toggleAudioPreviewPlayback = () => {
    if (!audioPreviewElement.value) return

    if (audioPreviewElement.value.paused) {
        audioPreviewElement.value.play().catch(error => {
            console.log('播放失败:', error)
        })
    } else {
        audioPreviewElement.value.pause()
    }
}

// 音频预览加载完成
const onAudioPreviewLoaded = () => {
    if (audioPreviewElement.value) {
        audioPreviewDuration.value = audioPreviewElement.value.duration || 0
    }
}

// 音频预览时间更新
const onAudioPreviewTimeUpdate = () => {
    if (audioPreviewElement.value && !audioPreviewIsDragging.value) {
        audioPreviewCurrentTime.value = audioPreviewElement.value.currentTime || 0
    }
}

// 音频预览进度条变化处理(点击或拖拽)
const onAudioPreviewProgressChange = (event) => {
    if (audioPreviewDuration.value > 0 && audioPreviewElement.value && event.target) {
        const newTime = parseFloat(event.target.value)
        audioPreviewCurrentTime.value = newTime
        // 立即更新音频位置
        audioPreviewElement.value.currentTime = newTime
    }
}

// 音频预览进度条拖拽结束处理
const onAudioPreviewProgressEnd = (event) => {
    if (audioPreviewElement.value && audioPreviewDuration.value > 0 && event.target) {
        const newTime = parseFloat(event.target.value)
        audioPreviewElement.value.currentTime = newTime
        audioPreviewCurrentTime.value = newTime
    }
    audioPreviewIsDragging.value = false
}

// 音频预览播放结束
const onAudioPreviewEnded = () => {
    audioPreviewIsPlaying.value = false
    audioPreviewCurrentTime.value = 0
}

// 监听音频预览变化,重置状态
watch(() => getCurrentAudioPreview(), (newPreview) => {
    // 停止当前播放
    if (audioPreviewElement.value) {
        audioPreviewElement.value.pause()
    }
    audioPreviewIsPlaying.value = false
    audioPreviewCurrentTime.value = 0
    audioPreviewDuration.value = 0

    if (newPreview) {
        // 等待 DOM 更新后加载新音频
        nextTick(() => {
            if (audioPreviewElement.value) {
                audioPreviewElement.value.load()
            }
        })
    }
})

2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
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
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
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
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
// 监听分离后的音频变化,重置播放器状态
watch(() => s2vForm.value.separatedAudios, (newAudios, oldAudios) => {
    // 如果音频列表发生变化(重新分割),清理旧的音频元素和状态
    if (newAudios && newAudios.length > 0 && oldAudios && oldAudios.length > 0) {
        // 检查是否是重新分割(音频数量或内容发生变化)
        const isReseparation = newAudios.length !== oldAudios.length ||
            newAudios.some((audio, index) => {
                const oldAudio = oldAudios[index]
                return !oldAudio || audio.audioDataUrl !== oldAudio.audioDataUrl
            })

        if (isReseparation) {
            // 停止所有正在播放的音频
            separatedAudioElements.value.forEach((audioElement, index) => {
                if (audioElement) {
                    audioElement.pause()
                    separatedAudioElements.value[index] = null
                }
            })

            // 清理所有状态
            separatedAudioElements.value = []
            separatedAudioPlaying.value = {}
            separatedAudioDuration.value = {}
            separatedAudioCurrentTime.value = {}
            separatedAudioIsDragging.value = {}

            // 等待 DOM 更新后重新加载音频
            nextTick(() => {
                // 音频元素会在模板中自动重新创建和加载
            })
        }
    } else if (!newAudios || newAudios.length === 0) {
        // 如果音频列表被清空,清理所有状态
        separatedAudioElements.value.forEach((audioElement, index) => {
            if (audioElement) {
                audioElement.pause()
                separatedAudioElements.value[index] = null
            }
        })
        separatedAudioElements.value = []
        separatedAudioPlaying.value = {}
        separatedAudioDuration.value = {}
        separatedAudioCurrentTime.value = {}
        separatedAudioIsDragging.value = {}
    }
}, { deep: true })

// 分离后的音频播放器控制函数
const toggleSeparatedAudioPlayback = (index) => {
    const audioElement = separatedAudioElements.value[index]
    if (!audioElement) return

    if (audioElement.paused) {
        audioElement.play().catch(error => {
            console.log('播放失败:', error)
        })
    } else {
        audioElement.pause()
    }
}

const getSeparatedAudioPlaying = (index) => {
    return separatedAudioPlaying.value[index] || false
}

const getSeparatedAudioDuration = (index) => {
    return separatedAudioDuration.value[index] || 0
}

const getSeparatedAudioCurrentTime = (index) => {
    return separatedAudioCurrentTime.value[index] || 0
}

const onSeparatedAudioLoaded = (index) => {
    const audioElement = separatedAudioElements.value[index]
    if (audioElement) {
        separatedAudioDuration.value[index] = audioElement.duration || 0
    }
}

const onSeparatedAudioTimeUpdate = (index) => {
    const audioElement = separatedAudioElements.value[index]
    if (audioElement && !separatedAudioIsDragging.value[index]) {
        separatedAudioCurrentTime.value[index] = audioElement.currentTime || 0
    }
}

const onSeparatedAudioProgressChange = (index, event) => {
    if (separatedAudioDuration.value[index] > 0 && separatedAudioElements.value[index] && event.target) {
        const newTime = parseFloat(event.target.value)
        separatedAudioCurrentTime.value[index] = newTime
        separatedAudioElements.value[index].currentTime = newTime
    }
}

const onSeparatedAudioProgressEnd = (index, event) => {
    const audioElement = separatedAudioElements.value[index]
    if (audioElement && separatedAudioDuration.value[index] > 0 && event.target) {
        const newTime = parseFloat(event.target.value)
        audioElement.currentTime = newTime
        separatedAudioCurrentTime.value[index] = newTime
    }
    separatedAudioIsDragging.value[index] = false
}

const onSeparatedAudioEnded = (index) => {
    separatedAudioPlaying.value[index] = false
    separatedAudioCurrentTime.value[index] = 0
}

const handleSeparatedAudioError = (index) => {
    console.error(`分离后的音频 ${index} 加载失败`)
    separatedAudioPlaying.value[index] = false
}

// 拖拽排序函数 - 角色
const onRoleDragStart = (event, index) => {
    draggedRoleIndex.value = index
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/html', event.target.outerHTML)

    // 创建拖拽预览
    const target = event.currentTarget
    const rect = target.getBoundingClientRect()
    dragOffset.value = {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    }

    // 创建拖拽预览图片
    const dragImage = target.cloneNode(true)
    // 设置固定尺寸,确保预览正确显示
    dragImage.style.width = `${rect.width}px`
    dragImage.style.height = `${rect.height}px`
    dragImage.style.position = 'fixed'
    dragImage.style.top = '-9999px'
    dragImage.style.left = '-9999px'
    dragImage.style.opacity = '0.9'
    dragImage.style.transform = 'rotate(2deg)'
    dragImage.style.pointerEvents = 'none'
    dragImage.style.zIndex = '10000'
    dragImage.style.boxShadow = '0 8px 24px rgba(0,0,0,0.3)'
    dragImage.style.backgroundColor = 'transparent'

    // 立即添加到 DOM
    document.body.appendChild(dragImage)

    // 强制重排,确保元素已渲染
    void dragImage.offsetHeight

    // 同步设置拖拽图片(必须在 dragstart 事件中同步调用)
    try {
        event.dataTransfer.setDragImage(dragImage, dragOffset.value.x, dragOffset.value.y)
    } catch (e) {
        console.warn('Failed to set drag image:', e)
    }

    // 延迟移除预览元素
    setTimeout(() => {
        if (dragImage.parentNode) {
            dragImage.parentNode.removeChild(dragImage)
        }
    }, 0)
}

const onRoleDragOver = (event, index) => {
    event.preventDefault()
    event.dataTransfer.dropEffect = 'move'
    if (draggedRoleIndex.value !== index) {
        dragOverRoleIndex.value = index
    }
}

const onRoleDragLeave = () => {
    dragOverRoleIndex.value = -1
}

const onRoleDrop = (event, targetIndex) => {
    event.preventDefault()
    if (draggedRoleIndex.value === -1 || draggedRoleIndex.value === targetIndex) {
        draggedRoleIndex.value = -1
        dragOverRoleIndex.value = -1
        return
    }

    const form = getCurrentForm()
    if (!form || !form.detectedFaces) return

    // 保存原始状态
    const originalFaces = [...form.detectedFaces]

    // 重新排序角色(只改变角色顺序,不影响音频顺序)
    const faces = [...form.detectedFaces]
    const draggedFace = faces[draggedRoleIndex.value]
    faces.splice(draggedRoleIndex.value, 1)
    faces.splice(targetIndex, 0, draggedFace)
    form.detectedFaces = faces

    // 更新音频的 roleIndex 和 roleName,以匹配新的角色位置
    // 但不改变音频的显示顺序
    if (s2vForm.value.separatedAudios && s2vForm.value.separatedAudios.length > 0) {
        s2vForm.value.separatedAudios.forEach((audio) => {
            // 找到这个音频原来对应的角色
            const originalRoleIndex = audio.roleIndex !== undefined ? audio.roleIndex : -1
            if (originalRoleIndex >= 0 && originalRoleIndex < originalFaces.length) {
                const originalFace = originalFaces[originalRoleIndex]
                // 找到这个角色在新列表中的位置
                const newRoleIndex = faces.findIndex(f => f === originalFace)
                if (newRoleIndex >= 0) {
                    audio.roleIndex = newRoleIndex
                    audio.roleName = faces[newRoleIndex].roleName || `角色${newRoleIndex + 1}`
                }
            }
        })
        // 触发响应式更新
        s2vForm.value.separatedAudios = [...s2vForm.value.separatedAudios]
    }

    draggedRoleIndex.value = -1
    dragOverRoleIndex.value = -1
}

// 拖拽排序函数 - 音频
const onAudioDragStart = (event, index) => {
    draggedAudioIndex.value = index
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/html', event.target.outerHTML)

    // 创建拖拽预览
    const target = event.currentTarget
    const rect = target.getBoundingClientRect()
    dragOffset.value = {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    }

    // 创建拖拽预览图片
    const dragImage = target.cloneNode(true)
    // 设置固定尺寸,确保预览正确显示
    dragImage.style.width = `${rect.width}px`
    dragImage.style.height = `${rect.height}px`
    dragImage.style.position = 'fixed'
    dragImage.style.top = '-9999px'
    dragImage.style.left = '-9999px'
    dragImage.style.opacity = '0.9'
    dragImage.style.transform = 'rotate(2deg)'
    dragImage.style.pointerEvents = 'none'
    dragImage.style.zIndex = '10000'
    dragImage.style.boxShadow = '0 8px 24px rgba(0,0,0,0.3)'
    dragImage.style.backgroundColor = 'transparent'

    // 立即添加到 DOM
    document.body.appendChild(dragImage)

    // 强制重排,确保元素已渲染
    void dragImage.offsetHeight

    // 同步设置拖拽图片(必须在 dragstart 事件中同步调用)
    try {
        event.dataTransfer.setDragImage(dragImage, dragOffset.value.x, dragOffset.value.y)
    } catch (e) {
        console.warn('Failed to set drag image:', e)
    }

    // 延迟移除预览元素
    setTimeout(() => {
        if (dragImage.parentNode) {
            dragImage.parentNode.removeChild(dragImage)
        }
    }, 0)
}

const onAudioDragOver = (event, index) => {
    event.preventDefault()
    event.dataTransfer.dropEffect = 'move'
    if (draggedAudioIndex.value !== index) {
        dragOverAudioIndex.value = index
    }
}

const onAudioDragLeave = () => {
    dragOverAudioIndex.value = -1
}

const onAudioDrop = (event, targetIndex) => {
    event.preventDefault()
    if (draggedAudioIndex.value === -1 || draggedAudioIndex.value === targetIndex) {
        draggedAudioIndex.value = -1
        dragOverAudioIndex.value = -1
        return
    }

    if (!s2vForm.value.separatedAudios) return

    // 重新排序音频(只改变音频顺序,不影响角色顺序)
    const audios = [...s2vForm.value.separatedAudios]
    const draggedAudio = audios[draggedAudioIndex.value]
    audios.splice(draggedAudioIndex.value, 1)
    audios.splice(targetIndex, 0, draggedAudio)

    // 音频的 roleIndex 和 roleName 保持不变,因为它们仍然对应原来的角色
    // 不需要更新 roleIndex,因为角色顺序没有改变

    s2vForm.value.separatedAudios = audios

    draggedAudioIndex.value = -1
    dragOverAudioIndex.value = -1
}


LiangLiu's avatar
LiangLiu committed
2346
2347
2348
2349
2350
// 组件卸载时清理
onUnmounted(() => {
    if (resizeHandler) {
        window.removeEventListener('resize', resizeHandler)
    }
LiangLiu's avatar
LiangLiu committed
2351
2352
2353
2354
2355
    // 停止音频预览播放
    if (audioPreviewElement.value) {
        audioPreviewElement.value.pause()
        audioPreviewElement.value = null
    }
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
    // 停止并清理所有分离后的音频播放器
    separatedAudioElements.value.forEach((audioElement, index) => {
        if (audioElement) {
            audioElement.pause()
            separatedAudioElements.value[index] = null
        }
    })
    separatedAudioElements.value = []
    separatedAudioPlaying.value = {}
    separatedAudioDuration.value = {}
    separatedAudioCurrentTime.value = {}
    separatedAudioIsDragging.value = {}
LiangLiu's avatar
LiangLiu committed
2368
2369
2370
2371
})

</script>
<template>
LiangLiu's avatar
LiangLiu committed
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
    <div
      v-if="templateLoading || downloadLoading"
      class="fixed right-6 top-24 sm:top-20 z-[9999] w-auto min-w-[260px] sm:min-w-[300px] max-w-[calc(100vw-2.5rem)] sm:max-w-md px-4 sm:px-5 transition-all duration-300 ease-out"
    >
      <div
        class="pointer-events-auto text-[#1d1d1f] bg-white/95 dark:text-white dark:bg-[#0d0d12]/90 backdrop-blur-[20px] backdrop-saturate-[180%] border border-black/8 dark:border-white/8 rounded-2xl shadow-[0_4px_6px_-1px_rgba(0,0,0,0.1),0_2px_4px_-1px_rgba(0,0,0,0.06),0_0_0_1px_rgba(0,0,0,0.05)] dark:shadow-[0_12px_32px_rgba(0,0,0,0.6),0_4px_12px_rgba(0,0,0,0.4),0_0_0_1px_rgba(255,255,255,0.06)]"
      >
        <div class="flex items-center gap-3 px-5 py-3">
          <div class="flex items-center justify-center w-9 h-9 rounded-full bg-[color:var(--brand-primary)]/10 dark:bg-[color:var(--brand-primary-light)]/15 text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]">
            <i class="fas fa-spinner fa-spin text-sm"></i>
          </div>
          <div class="flex-1 text-sm font-medium tracking-tight">
            {{ templateLoading ? (templateLoadingMessage || t('prefillLoadingDefault')) : (downloadLoadingMessage || t('downloadPreparing')) }}
          </div>
        </div>
      </div>
    </div>
LiangLiu's avatar
LiangLiu committed
2389
                <!-- 主内容区域 - 响应式布局 -->
LiangLiu's avatar
LiangLiu committed
2390
                <div class="flex-1 flex flex-col min-h-0 mobile-content">
LiangLiu's avatar
LiangLiu committed
2391
2392
2393
2394
2395
2396
2397
                    <!-- 生成视频区域 -->
                    <div class="flex-1 flex flex-col">
                        <!-- 内容区域 -->
                        <div class="flex-1 p-6">


                        <!-- 任务创建面板 -->
LiangLiu's avatar
LiangLiu committed
2398
                        <div class="max-w-4xl mx-auto min-h-[100vh] flex flex-col" id="task-creator">
LiangLiu's avatar
LiangLiu committed
2399
                            <!-- 合并的创作区域 -->
LiangLiu's avatar
LiangLiu committed
2400
                            <div class="creation-area-container flex-1 flex flex-col justify-center">
LiangLiu's avatar
LiangLiu committed
2401
2402

                                <div class="default-state-container">
LiangLiu's avatar
LiangLiu committed
2403
2404
                                    <!-- 两个并列的下拉菜单 - Apple 风格 -->
                                    <div class="flex justify-center gap-6 mb-10">
LiangLiu's avatar
LiangLiu committed
2405
2406
                                        <!-- 任务类型下拉菜单 -->
                                        <ModelDropdown
LiangLiu's avatar
LiangLiu committed
2407
2408
2409
2410
2411
2412
                                            :available-models="availableTaskTypes.map(taskType => ({
                                                value: taskType,
                                                label: getTaskTypeName(taskType),
                                                icon: getTaskTypeIcon(taskType)
                                            }))"
                                            :selected-model="selectedTaskId"
LiangLiu's avatar
LiangLiu committed
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
                                            @select-model="selectTask"
                                        />

                                        <!-- 模型选择下拉菜单 -->
                                        <ModelDropdown
                                            :available-models="availableModelClasses"
                                            :selected-model="getCurrentForm().model_cls"
                                            @select-model="selectModel"
                                        />
                                    </div>

                                 <!-- 默认状态:中心文字 -->
                                <div v-show="!isCreationAreaExpanded" class="flex flex-col items-center justify-center">

                                    <div class="text-center">

LiangLiu's avatar
LiangLiu committed
2429
                                        <h2 class="text-3xl sm:text-3xl md:text-4xl lg:text-4xl font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] mb-8 tracking-tight">{{ t('whatDoYouWantToDo') }}</h2>
LiangLiu's avatar
LiangLiu committed
2430

LiangLiu's avatar
LiangLiu committed
2431
2432
2433
                                        <!-- 动态滚动提示 - Apple 风格 -->
                                        <div class="hint-container mb-12 pb-10">
                                            <div class="hint-text text-[#86868b] dark:text-[#98989d] text-base min-h-[60px] flex items-center justify-center tracking-tight">
LiangLiu's avatar
LiangLiu committed
2434
                                                <transition name="hint-fade" mode="out-in">
LiangLiu's avatar
LiangLiu committed
2435
                                                    <p :key="currentHintIndex" class="text-center max-w-2xl">
LiangLiu's avatar
LiangLiu committed
2436
2437
2438
2439
                                                        {{ currentTaskHints[currentHintIndex] }}
                                                    </p>
                                                </transition>
                                            </div>
LiangLiu's avatar
LiangLiu committed
2440
2441
                                            <!-- 提示指示器 - Apple 风格 -->
                                            <div class="flex justify-center mt-6 gap-2">
LiangLiu's avatar
LiangLiu committed
2442
2443
                                                <div v-for="(hint, index) in currentTaskHints" :key="index"
                                                    class="w-2 h-2 rounded-full transition-all duration-300"
LiangLiu's avatar
LiangLiu committed
2444
                                                    :class="index === currentHintIndex ? 'bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] scale-110' : 'bg-[#86868b]/30 dark:bg-[#98989d]/30'">
LiangLiu's avatar
LiangLiu committed
2445
2446
2447
2448
2449
                                                </div>
                                            </div>
                                        </div>
                                    </div>

LiangLiu's avatar
LiangLiu committed
2450
2451
                                    <!-- 展开开关 - Apple 极简风格 -->
                                    <div class="relative group cursor-pointer" @click="expandCreationArea">
LiangLiu's avatar
LiangLiu committed
2452
                                        <button
LiangLiu's avatar
LiangLiu committed
2453
                                            class="cursor-pointer relative bg-white/95 dark:bg-[#2c2c2e]/95 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-full px-8 py-4 text-base font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] hover:scale-105 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:hover:shadow-[0_8px_24px_rgba(0,0,0,0.3)] active:scale-100 transition-all duration-200 ease-out min-w-[250px] max-w-[400px] tracking-tight"
LiangLiu's avatar
LiangLiu committed
2454
                                        >
LiangLiu's avatar
LiangLiu committed
2455
2456
                                        <i class="fi fi-sr-cursor-finger-click text-lg text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)] transition-all duration-200 pointer-events-none"></i>
                                        <span class="pl-2 text-base font-semibold transition-all duration-200 pointer-events-none">{{ t('startCreatingVideo') }}</span>
LiangLiu's avatar
LiangLiu committed
2457
2458
2459
2460
2461
2462
                                        </button>
                                    </div>
                                </div>

                                <!-- 展开状态:素材区域 -->
                                <div v-if="isCreationAreaExpanded" class="mb-8 prompt-input-section">
LiangLiu's avatar
LiangLiu committed
2463
                                    <!-- 中心文字 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
2464
2465
                                    <div class="text-center">

LiangLiu's avatar
LiangLiu committed
2466
                                        <h2 class="text-3xl sm:text-3xl md:text-3xl lg:text-4xl font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] mb-6 animate-fade-in tracking-tight">{{ t('whatMaterialsDoYouNeed') }}</h2>
LiangLiu's avatar
LiangLiu committed
2467

LiangLiu's avatar
LiangLiu committed
2468
                                        <p class="text-[#86868b] dark:text-[#98989d] text-base mb-10 transition-all duration-300 tracking-tight">
LiangLiu's avatar
LiangLiu committed
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
                                            <span v-if="selectedTaskId === 't2v'"
                                                  class="inline-block animate-fade-in">{{ t('pleaseEnterTheMostDetailedVideoScript') }}</span>
                                            <span v-else-if="selectedTaskId === 'i2v'"
                                                  class="inline-block animate-fade-in">{{ t('pleaseUploadAnImageAsTheFirstFrameOfTheVideoAndTheMostDetailedVideoScript') }}</span>
                                            <span v-else-if="selectedTaskId === 's2v'"
                                                  class="inline-block animate-fade-in">{{ t('pleaseUploadARoleImageAnAudioAndTheGeneralVideoRequirements') }}</span>
                                            <span v-else
                                                  class="inline-block animate-fade-in">选择任务类型开始创作您的视频</span>
                                        </p>
                                    </div>

LiangLiu's avatar
LiangLiu committed
2480
                                 <!-- 收缩开关 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
2481
2482
2483
2484

                                <div
                                    class="creation-area transition-all duration-500 ease-out max-w-10xl mx-auto"
                                    @click.stop>
LiangLiu's avatar
LiangLiu committed
2485
2486
                                    <!-- 收起按钮 - Apple 风格 -->
                                    <div class="flex justify-center mb-6">
LiangLiu's avatar
LiangLiu committed
2487
                                        <button @click="contractCreationArea"
LiangLiu's avatar
LiangLiu committed
2488
                                                class="flex items-center gap-2 px-4 py-2 bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/6 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/10 dark:hover:border-white/12 hover:shadow-[0_2px_8px_rgba(0,0,0,0.08)] dark:hover:shadow-[0_2px_8px_rgba(0,0,0,0.3)] rounded-full transition-all duration-200 ease-out group"
LiangLiu's avatar
LiangLiu committed
2489
2490
2491
                                                :class="{ 'animate-pulse': isContracting }">
                                            <i class="fas fa-compress-alt text-sm transition-transform duration-200 group-hover:scale-110"
                                               :class="{ 'animate-spin': isContracting }"></i>
LiangLiu's avatar
LiangLiu committed
2492
                                            <span class="text-sm font-medium tracking-tight">
LiangLiu's avatar
LiangLiu committed
2493
2494
2495
2496
2497
2498
2499
                                                {{ t('collapseCreationArea') }}
                                            </span>
                                            <i class="fas fa-chevron-up text-xs transition-transform duration-200 group-hover:translate-y-[-2px]"
                                               :class="{ 'animate-bounce': isContracting }"></i>
                                        </button>
                                    </div>

2500
                                    <div v-if="selectedTaskId === 'i2v' || selectedTaskId === 's2v' || selectedTaskId === 'animate'" class="upload-section">
LiangLiu's avatar
LiangLiu committed
2501
                                    <!-- 上传图片 - Apple 风格 -->
2502
                                    <div v-if="selectedTaskId === 'i2v' || selectedTaskId === 's2v' || selectedTaskId === 'animate'">
LiangLiu's avatar
LiangLiu committed
2503
2504
2505
                                        <!-- 图片标签 -->
                                        <div class="flex justify-between items-center mb-3">
                                                <label class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">
LiangLiu's avatar
LiangLiu committed
2506
2507
2508
                                                                {{ t('image') }}
                                                </label>
                                        </div>
LiangLiu's avatar
LiangLiu committed
2509
2510
                                        <!-- 上传图片区域 - Apple 风格 -->
                                        <div class="relative bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-2xl p-2 min-h-[220px] transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_16px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_16px_rgba(0,0,0,0.3)]"
LiangLiu's avatar
LiangLiu committed
2511
2512
2513
2514
                                            @drop="handleImageDrop"
                                            @dragover="handleDragOver"
                                            @dragenter="handleDragEnter"
                                            @dragleave="handleDragLeave"
LiangLiu's avatar
LiangLiu committed
2515
2516
2517
2518
                                            :class="{
                                                'border-[color:var(--brand-primary)] dark:border-[color:var(--brand-primary-light)] bg-[color:var(--brand-primary)]/5 dark:bg-[color:var(--brand-primary-light)]/10': isDragOver,
                                                'p-8': !getCurrentImagePreview()
                                            }"
LiangLiu's avatar
LiangLiu committed
2519
                                            >
LiangLiu's avatar
LiangLiu committed
2520
2521
2522
2523
2524
2525
                                            <!-- 默认上传界面 - Apple 风格 -->
                                            <div v-if="!getCurrentImagePreview()" class="flex flex-col items-center justify-center h-full">
                                            <p class="text-base font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] mb-2 tracking-tight">{{ t('uploadImage') }}</p>
                                            <p class="text-xs text-[#86868b] dark:text-[#98989d] mb-6 tracking-tight">{{ t('supportedImageFormats') }}</p>
                                            <div class="flex items-center justify-center gap-4">
                                                        <div class="flex flex-col items-center gap-2">
LiangLiu's avatar
LiangLiu committed
2526
                                                            <button
LiangLiu's avatar
LiangLiu committed
2527
                                                                class="w-12 h-12 flex items-center justify-center bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(var(--brand-primary-rgb),0.3)] dark:hover:shadow-[0_4px_12px_rgba(var(--brand-primary-light-rgb),0.4)] active:scale-100"
LiangLiu's avatar
LiangLiu committed
2528
2529
                                                                @click="triggerImageUpload"
                                                                :title="t('uploadImage')">
LiangLiu's avatar
LiangLiu committed
2530
                                                                <i class="fas fa-upload text-base"></i>
LiangLiu's avatar
LiangLiu committed
2531
                                                            </button>
LiangLiu's avatar
LiangLiu committed
2532
                                                            <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ t('upload') }}</span>
LiangLiu's avatar
LiangLiu committed
2533
                                                        </div>
LiangLiu's avatar
LiangLiu committed
2534
                                                        <div class="flex flex-col items-center gap-2">
LiangLiu's avatar
LiangLiu committed
2535
2536
                                                            <button
                                                                @click.stop="showImageTemplates = true; mediaModalTab = 'history'; getImageHistory()"
LiangLiu's avatar
LiangLiu committed
2537
                                                                class="w-12 h-12 flex items-center justify-center bg-white dark:bg-[#3a3a3c] border border-black/8 dark:border-white/8 text-[#1d1d1f] dark:text-[#f5f5f7] rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.3)] active:scale-100"
LiangLiu's avatar
LiangLiu committed
2538
                                                                :title="t('templates')">
LiangLiu's avatar
LiangLiu committed
2539
                                                                <i class="fas fa-history text-base"></i>
LiangLiu's avatar
LiangLiu committed
2540
                                                            </button>
LiangLiu's avatar
LiangLiu committed
2541
                                                            <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ t('templates') }}</span>
LiangLiu's avatar
LiangLiu committed
2542
2543
2544
2545
                                                        </div>
                                            </div>
                                            </div>

2546
2547
2548
2549
                                            <!-- 图片预览区域 - 只显示主图 -->
                                            <div v-if="getCurrentImagePreview()" class="flex items-center justify-center w-full min-h-[220px]">
                                                <!-- 主图预览 - Apple 风格 -->
                                                <div class="relative w-auto max-w-full min-h-[220px] flex items-center justify-center group">
LiangLiu's avatar
LiangLiu committed
2550
                                                    <img :src="getCurrentImagePreviewUrl()" alt="t('previewImage')"
LiangLiu's avatar
LiangLiu committed
2551
                                                        class="max-w-full max-h-[220px] w-auto h-auto object-contain rounded-xl transition-all duration-200">
LiangLiu's avatar
LiangLiu committed
2552

2553
                                                    <!-- 删除按钮 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
2554
                                                    <div
LiangLiu's avatar
LiangLiu committed
2555
                                                        class="absolute inset-x-0 bottom-4 flex items-center justify-center opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-200">
2556
                                                        <button @click.stop="handleRemoveImage"
LiangLiu's avatar
LiangLiu committed
2557
                                                            class="w-11 h-11 flex items-center justify-center bg-white/95 dark:bg-[#2c2c2e]/95 backdrop-blur-[20px] border border-black/8 dark:border-white/8 text-red-500 dark:text-red-400 rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(239,68,68,0.2)] dark:hover:shadow-[0_4px_12px_rgba(248,113,113,0.3)] active:scale-100"
2558
                                                            :title="t('deleteImage')">
LiangLiu's avatar
LiangLiu committed
2559
                                                            <i class="fas fa-trash text-base"></i>
LiangLiu's avatar
LiangLiu committed
2560
2561
2562
                                                        </button>
                                                    </div>
                                                </div>
2563

LiangLiu's avatar
LiangLiu committed
2564
2565
2566
2567
                                            </div>
                                                <input type="file" ref="imageInput" @change="handleImageUpload" accept="image/*"
                                                style="display: none;">
                                            </div>
2568
2569
2570
2571
2572
2573

                                            <!-- 角色检测加载提示 -->
                                            <div v-if="faceDetecting" class="mt-3 flex items-center justify-center gap-2 text-sm text-[#86868b] dark:text-[#98989d] tracking-tight">
                                                <i class="fas fa-spinner fa-spin text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                                                <span>{{ t('detectingCharacters') }}</span>
                                            </div>
LiangLiu's avatar
LiangLiu committed
2574
2575
                                    </div>

LiangLiu's avatar
LiangLiu committed
2576
                                    <!-- 上传音频 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
2577
                                    <div v-if="selectedTaskId === 's2v'">
LiangLiu's avatar
LiangLiu committed
2578
2579
2580
                                        <!-- 音频标签 -->
                                        <div class="flex justify-between items-center mb-3">
                                                        <label class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">
LiangLiu's avatar
LiangLiu committed
2581
2582
2583
                                                                        {{ t('audio') }}
                                                        </label>
                                        </div>
LiangLiu's avatar
LiangLiu committed
2584
2585
                                        <!-- 上传音频区域 - Apple 风格 -->
                                        <div class="relative bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-2xl p-2 min-h-[220px] transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_16px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_16px_rgba(0,0,0,0.3)]"
LiangLiu's avatar
LiangLiu committed
2586
2587
2588
2589
                                            @drop="handleAudioDrop"
                                            @dragover="handleDragOver"
                                            @dragenter="handleDragEnter"
                                            @dragleave="handleDragLeave"
LiangLiu's avatar
LiangLiu committed
2590
2591
2592
2593
                                            :class="{
                                                'border-[color:var(--brand-primary)] dark:border-[color:var(--brand-primary-light)] bg-[color:var(--brand-primary)]/5 dark:bg-[color:var(--brand-primary-light)]/10': isDragOver,
                                                'p-8': !getCurrentAudioPreview()
                                            }"
LiangLiu's avatar
LiangLiu committed
2594
                                            >
LiangLiu's avatar
LiangLiu committed
2595
2596
                                        <!-- 默认上传界面 - Apple 风格 -->
                                            <div v-if="!getCurrentAudioPreview()" class="flex flex-col items-center justify-center h-full"
LiangLiu's avatar
LiangLiu committed
2597
                                                >
LiangLiu's avatar
LiangLiu committed
2598
2599
                                                <p class="text-base font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] mb-2 tracking-tight">{{ t('uploadAudio') }}</p>
                                                <p class="text-xs text-[#86868b] dark:text-[#98989d] mb-6 tracking-tight">{{ t('supportedAudioFormats') }}</p>
LiangLiu's avatar
LiangLiu committed
2600
2601
2602
2603
2604
2605

                                                <div class="flex items-center justify-center gap-3">
                                                    <div class="flex flex-col items-center gap-2">
                                                        <button @click.stop="showVoiceTTSModal = true"
                                                            class="w-12 h-12 flex items-center justify-center bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] border border-black/8 dark:border-white/8 text-white rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.3)] active:scale-100"
                                                            :title="t('textToSpeech')">
2606
                                                            <i class="fi fi-bs-text text-lg"></i>
LiangLiu's avatar
LiangLiu committed
2607
2608
2609
                                                        </button>
                                                        <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ t('textToSpeech') }}</span>
                                                    </div>
2610
2611
2612
2613
2614
2615
2616
2617
2618
                                                    <div class="flex flex-col items-center gap-2">
                                                        <button @click.stop="router.push('/podcast_generate')"
                                                            class="w-12 h-12 flex items-center justify-center bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] border border-black/8 dark:border-white/8 text-white rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.3)] active:scale-100"
                                                            :title="t('podcast.dualPersonPodcast')">
                                                            <!-- 讲话的icon,用fa-microphone-alt如果有,否则fa-microphone -->
                                                            <i class="fi fi-bs-signal-stream text-xl"></i>
                                                        </button>
                                                        <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ t('podcast.dualPersonPodcast') }}</span>
                                                    </div>
LiangLiu's avatar
LiangLiu committed
2619
                                                    <div class="flex flex-col items-center gap-2">
LiangLiu's avatar
LiangLiu committed
2620
                                                        <button
LiangLiu's avatar
LiangLiu committed
2621
2622
2623
2624
                                                            class="w-12 h-12 flex items-center justify-center bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(var(--brand-primary-rgb),0.3)] dark:hover:shadow-[0_4px_12px_rgba(var(--brand-primary-light-rgb),0.4)] active:scale-100"
                                                            @click="triggerAudioUpload"
                                                            :title="t('uploadAudio')">
                                                            <i class="fas fa-upload text-base"></i>
LiangLiu's avatar
LiangLiu committed
2625
                                                        </button>
LiangLiu's avatar
LiangLiu committed
2626
                                                        <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ t('upload') }}</span>
LiangLiu's avatar
LiangLiu committed
2627
                                                    </div>
LiangLiu's avatar
LiangLiu committed
2628
                                                    <div class="flex flex-col items-center gap-2">
LiangLiu's avatar
LiangLiu committed
2629
                                                        <button
LiangLiu's avatar
LiangLiu committed
2630
2631
2632
2633
                                                            @click.stop="showAudioTemplates = true; mediaModalTab = 'history'; getAudioHistory()"
                                                            class="w-12 h-12 flex items-center justify-center bg-white dark:bg-[#3a3a3c] border border-black/8 dark:border-white/8 text-[#1d1d1f] dark:text-[#f5f5f7] rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.3)] active:scale-100"
                                                            :title="t('templates')">
                                                            <i class="fas fa-history text-base"></i>
LiangLiu's avatar
LiangLiu committed
2634
                                                        </button>
LiangLiu's avatar
LiangLiu committed
2635
                                                        <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ t('templates') }}</span>
LiangLiu's avatar
LiangLiu committed
2636
                                                    </div>
LiangLiu's avatar
LiangLiu committed
2637
                                                    <div class="flex flex-col items-center gap-2">
LiangLiu's avatar
LiangLiu committed
2638
                                                        <button @click.stop="isRecording ? stopRecording() : startRecording()"
LiangLiu's avatar
LiangLiu committed
2639
2640
2641
                                                        class="w-12 h-12 flex items-center justify-center rounded-full transition-all duration-200 hover:scale-110 active:scale-100"
                                                            :class="isRecording ? 'bg-red-500 dark:bg-red-400 text-white shadow-[0_4px_12px_rgba(239,68,68,0.3)] dark:shadow-[0_4px_12px_rgba(248,113,113,0.4)]' : 'bg-white dark:bg-[#3a3a3c] border border-black/8 dark:border-white/8 text-[#1d1d1f] dark:text-[#f5f5f7] hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.3)]'"
                                                            :title="isRecording ? t('stopRecording') : t('recordAudio')">
2642
                                                        <i class="fas fa-microphone-alt text-base" :class="{ 'animate-pulse': isRecording }"></i>
LiangLiu's avatar
LiangLiu committed
2643
                                                    </button>
LiangLiu's avatar
LiangLiu committed
2644
                                                        <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ isRecording ? formatRecordingDuration(recordingDuration) : t('recordAudio') }}</span>
LiangLiu's avatar
LiangLiu committed
2645
2646
2647
2648
2649
                                                    </div>

                                        </div>
                                            </div>

2650
                                        <!-- 音频预览 - 原始音频播放器 -->
LiangLiu's avatar
LiangLiu committed
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
                                            <div v-if="getCurrentAudioPreview()" class="relative w-full min-h-[220px] flex items-center justify-center">
                                                <div class="bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_12px_rgba(0,0,0,0.08)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.2)] w-full p-4">
                                                    <div class="relative flex items-center mb-3">
                                                        <!-- 头像容器 -->
                                                        <div class="relative mr-3 flex-shrink-0">
                                                            <!-- 透明白色头像 -->
                                                            <div class="w-12 h-12 rounded-full bg-white/40 dark:bg-white/20 border border-white/30 dark:border-white/20 transition-all duration-200"></div>
                                                            <!-- 播放/暂停按钮 -->
                                                            <button
                                                                @click="toggleAudioPreviewPlayback"
                                                                class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 bg-[color:var(--brand-primary)]/90 dark:bg-[color:var(--brand-primary-light)]/90 rounded-full flex items-center justify-center text-white cursor-pointer hover:scale-110 transition-all duration-200 z-20 shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.3)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.4)]"
                                                            >
                                                                <i :class="audioPreviewIsPlaying ? 'fas fa-pause' : 'fas fa-play'" class="text-xs ml-0.5"></i>
                                                            </button>
                                                        </div>

                                                        <!-- 音频信息 -->
                                                        <div class="flex-1 min-w-0">
                                                            <div class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight truncate">
                                                                {{ t('audio') }}
                                                            </div>
                                                        </div>

                                                        <!-- 音频时长 -->
                                                        <div class="text-xs font-medium text-[#86868b] dark:text-[#98989d] tracking-tight flex-shrink-0 mr-3">
                                                            {{ formatAudioPreviewTime(audioPreviewCurrentTime) }} / {{ formatAudioPreviewTime(audioPreviewDuration) }}
                                                        </div>
LiangLiu's avatar
LiangLiu committed
2678

LiangLiu's avatar
LiangLiu committed
2679
                                                        <!-- 删除按钮 -->
LiangLiu's avatar
LiangLiu committed
2680
                                                        <button @click.stop="removeAudio"
LiangLiu's avatar
LiangLiu committed
2681
                                                            class="w-9 h-9 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-red-500 dark:text-red-400 rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(239,68,68,0.2)] dark:hover:shadow-[0_4px_12px_rgba(248,113,113,0.3)] active:scale-100 flex-shrink-0"
LiangLiu's avatar
LiangLiu committed
2682
                                                            :title="t('deleteAudio')">
LiangLiu's avatar
LiangLiu committed
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
                                                            <i class="fas fa-trash text-sm"></i>
                                                        </button>
                                                    </div>

                                                    <!-- 进度条 -->
                                                    <div class="flex items-center gap-2" v-if="audioPreviewDuration > 0">
                                                        <input
                                                            type="range"
                                                            :min="0"
                                                            :max="audioPreviewDuration"
                                                            :value="audioPreviewCurrentTime"
                                                            @input="onAudioPreviewProgressChange"
                                                            @change="onAudioPreviewProgressChange"
                                                            @mousedown="audioPreviewIsDragging = true"
                                                            @mouseup="onAudioPreviewProgressEnd"
                                                            @touchstart="audioPreviewIsDragging = true"
                                                            @touchend="onAudioPreviewProgressEnd"
                                                            class="flex-1 h-1 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                                                        />
                                                    </div>
LiangLiu's avatar
LiangLiu committed
2703
                                                </div>
LiangLiu's avatar
LiangLiu committed
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716

                                                <!-- 隐藏的音频元素 -->
                                                <audio
                                                    ref="audioPreviewElement"
                                                    :src="getCurrentAudioPreviewUrl()"
                                                    @loadedmetadata="onAudioPreviewLoaded"
                                                    @timeupdate="onAudioPreviewTimeUpdate"
                                                    @ended="onAudioPreviewEnded"
                                                    @play="audioPreviewIsPlaying = true"
                                                    @pause="audioPreviewIsPlaying = false"
                                                    @error="handleAudioError"
                                                    class="hidden"
                                                ></audio>
LiangLiu's avatar
LiangLiu committed
2717
2718
                                            </div>

2719
                                            <input type="file" ref="audioInput" @change="handleAudioUpload" accept="audio/*,audio/mp4,audio/x-m4a,video/*" data-role="audio-input"
LiangLiu's avatar
LiangLiu committed
2720
2721
                                            style="display: none;">
                                        </div>
2722
2723
2724
2725
2726
2727

                                        <!-- 音频分割加载提示 -->
                                        <div v-if="audioSeparating" class="mt-3 flex items-center justify-center gap-2 text-sm text-[#86868b] dark:text-[#98989d] tracking-tight">
                                            <i class="fas fa-spinner fa-spin text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                                            <span>{{t('splitingAudio')}}</span>
                                        </div>
LiangLiu's avatar
LiangLiu committed
2728
2729
                                    </div>

2730
2731
2732
                                    <!-- 上传视频 - Apple 风格(用于 animate 任务类型) -->
                                    <div v-if="selectedTaskId === 'animate'">
                                        <!-- 视频标签 -->
LiangLiu's avatar
LiangLiu committed
2733
                                        <div class="flex justify-between items-center mb-3">
2734
2735
                                            <label class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">
                                                {{ t('video') || '视频' }}
LiangLiu's avatar
LiangLiu committed
2736
2737
                                            </label>
                                        </div>
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
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
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
                                        <!-- 上传视频区域 - Apple 风格 -->
                                        <div class="relative bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-2xl p-2 min-h-[220px] transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_16px_rgba(0,0,0,0.1)] dark:hover:shadow-[0_4px_16px_rgba(0,0,0,0.3)]"
                                            @drop="handleVideoDrop"
                                            @dragover="handleDragOver"
                                            @dragenter="handleDragEnter"
                                            @dragleave="handleDragLeave"
                                            :class="{
                                                'border-[color:var(--brand-primary)] dark:border-[color:var(--brand-primary-light)] bg-[color:var(--brand-primary)]/5 dark:bg-[color:var(--brand-primary-light)]/10': isDragOver,
                                                'p-8': !getCurrentVideoPreview()
                                            }"
                                            >
                                            <!-- 默认上传界面 - Apple 风格 -->
                                            <div v-if="!getCurrentVideoPreview()" class="flex flex-col items-center justify-center h-full">
                                                <p class="text-base font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] mb-2 tracking-tight">{{ t('uploadVideo')}}</p>
                                                <p class="text-xs text-[#86868b] dark:text-[#98989d] mb-6 tracking-tight">{{ t('supportedVideoFormats') }}</p>
                                                <div class="flex items-center justify-center gap-4">
                                                    <div class="flex flex-col items-center gap-2">
                                                        <button
                                                            class="w-12 h-12 flex items-center justify-center bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] text-white rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(var(--brand-primary-rgb),0.3)] dark:hover:shadow-[0_4px_12px_rgba(var(--brand-primary-light-rgb),0.4)] active:scale-100"
                                                            @click="triggerVideoUpload"
                                                            :title="t('uploadVideo') || '上传视频'">
                                                            <i class="fas fa-upload text-base"></i>
                                                        </button>
                                                        <span class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">{{ t('upload') }}</span>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- 视频预览区域 -->
                                            <div v-if="getCurrentVideoPreview()" class="relative w-full min-h-[220px] flex items-center justify-center">
                                                <div class="bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_12px_rgba(0,0,0,0.08)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.2)] w-full p-4">
                                                    <div class="relative flex items-center mb-3">
                                                        <!-- 视频预览 -->
                                                        <div class="flex-1 min-w-0">
                                                            <video
                                                                :src="getCurrentVideoPreviewUrl()"
                                                                class="w-full max-h-[180px] rounded-lg object-contain"
                                                                controls
                                                                preload="metadata"
                                                            ></video>
                                                        </div>

                                                        <!-- 删除按钮 -->
                                                        <button @click.stop="removeVideo"
                                                            class="ml-3 w-9 h-9 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-red-500 dark:text-red-400 rounded-full transition-all duration-200 hover:scale-110 hover:shadow-[0_4px_12px_rgba(239,68,68,0.2)] dark:hover:shadow-[0_4px_12px_rgba(248,113,113,0.3)] active:scale-100 flex-shrink-0"
                                                            :title="t('deleteVideo') || '删除视频'">
                                                            <i class="fas fa-trash text-sm"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>

                                            <input type="file" ref="videoInput" @change="handleVideoUpload" accept="video/*" data-role="video-input"
                                                style="display: none;">
LiangLiu's avatar
LiangLiu committed
2792
                                        </div>
2793
2794
                                    </div>
                                </div>
LiangLiu's avatar
LiangLiu committed
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
                                <!-- 角色和音频配对区域 -->
                                <div v-if="selectedTaskId === 's2v'" class="mt-8">
                                    <!-- 模式切换开关 - 始终显示 -->
                                    <div class="flex justify-center items-center mb-4">
                                        <div class="flex items-center gap-3">

                                            <!-- 开关按钮 -->
                                            <button
                                                @click="toggleRoleMode"
                                                class="relative w-14 h-7 rounded-full transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-[color:var(--brand-primary)]/20 dark:focus:ring-[color:var(--brand-primary-light)]/20"
                                                :class="isMultiRoleMode ? 'bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)]' : 'bg-[#86868b]/30 dark:bg-[#98989d]/30'"
                                                :title="isMultiRoleMode ? '切换到单角色模式' : '切换到多角色模式'"
                                            >
                                                <!-- 滑动圆点 -->
                                                <span
                                                    class="absolute top-0.5 left-0.5 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 flex items-center justify-center"
                                                    :class="{ 'translate-x-7': isMultiRoleMode, 'translate-x-0': !isMultiRoleMode }"
                                                >
                                                    <i :class="isMultiRoleMode ? 'fas fa-users text-[8px] text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]' : 'fas fa-user text-[8px] text-[#86868b] dark:text-[#98989d]'"></i>
                                                </span>
                                            </button>

                                            <span class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight" :class="{ 'text-[#86868b] dark:text-[#98989d]': isMultiRoleMode }">{{ isMultiRoleMode ? '多角色模式' : '单角色模式' }}</span>

                                            <!-- Info 图标按钮 -->
                                            <button
                                                @click="showRoleModeInfo = true"
                                                class="w-5 h-5 flex items-center justify-center text-[#86868b] dark:text-[#98989d] hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] transition-colors duration-200 rounded-full hover:bg-[#86868b]/10 dark:hover:bg-[#98989d]/10"
                                                :title="t('roleModeInfo.title')"
                                            >
                                                <i class="fas fa-info-circle text-xs"></i>
LiangLiu's avatar
LiangLiu committed
2827
                                            </button>
2828
2829
                                        </div>
                                    </div>
LiangLiu's avatar
LiangLiu committed
2830

2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
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
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
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
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
                                    <!-- 角色模式说明弹窗 - Apple 风格 -->
                                    <div v-if="showRoleModeInfo"
                                        class="fixed inset-0 bg-black/50 dark:bg-black/60 backdrop-blur-sm z-[70] flex items-center justify-center p-4"
                                        @click="showRoleModeInfo = false">
                                        <div class="w-full max-w-md bg-white/95 dark:bg-[#1e1e1e]/95 backdrop-blur-[40px] backdrop-saturate-[180%] border border-black/10 dark:border-white/10 rounded-3xl shadow-[0_20px_60px_rgba(0,0,0,0.2)] dark:shadow-[0_20px_60px_rgba(0,0,0,0.6)] overflow-hidden"
                                            @click.stop>
                                            <!-- 弹窗头部 -->
                                            <div class="flex items-center justify-between px-6 py-4 border-b border-black/8 dark:border-white/8 bg-white/50 dark:bg-[#1e1e1e]/50 backdrop-blur-[20px]">
                                                <h3 class="text-lg font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">
                                                    {{ t('roleModeInfo.title') }}
                                                </h3>
                                                <button @click="showRoleModeInfo = false"
                                                    class="w-8 h-8 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-red-500 dark:hover:text-red-400 hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200 hover:scale-110 active:scale-100"
                                                    :title="t('close')">
                                                    <i class="fas fa-times text-sm"></i>
                                                </button>
                                            </div>

                                            <!-- 弹窗内容 -->
                                            <div class="p-6 space-y-6">
                                                <!-- 单角色模式说明 -->
                                                <div class="space-y-3">
                                                    <h4 class="text-base font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight flex items-center gap-2">
                                                        <i class="fas fa-user text-sm text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                                                        {{ t('roleModeInfo.singleMode.title') }}
                                                    </h4>
                                                    <ul class="space-y-2 pl-6">
                                                        <li v-for="(point, index) in tm('roleModeInfo.singleMode.points')" :key="index"
                                                            class="text-sm text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight leading-relaxed flex items-start gap-2">
                                                            <span class="text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)] mt-1.5 flex-shrink-0"></span>
                                                            <span>{{ point }}</span>
                                                        </li>
                                                    </ul>
                                                </div>

                                                <!-- 多角色模式说明 -->
                                                <div class="space-y-3">
                                                    <h4 class="text-base font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight flex items-center gap-2">
                                                        <i class="fas fa-users text-sm text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                                                        {{ t('roleModeInfo.multiMode.title') }}
                                                    </h4>
                                                    <ul class="space-y-2 pl-6">
                                                        <li v-for="(point, index) in tm('roleModeInfo.multiMode.points')" :key="index"
                                                            class="text-sm text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight leading-relaxed flex items-center gap-2">
                                                            <span class="text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)] flex-shrink-0"></span>
                                                            <span>{{ point }}</span>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 保存角色加载提示 -->
                                    <div v-if="faceSaving" class="flex items-center justify-center gap-2 text-sm text-[#86868b] dark:text-[#98989d] tracking-tight mb-4">
                                        <i class="fas fa-spinner fa-spin text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                                        <span>正在保存角色并更新音频...</span>
                                    </div>

                                    <!-- 角色和音频配对区域 - 每行一个配对(仅在多角色模式且有角色时显示) -->
                                    <div v-if="isMultiRoleMode && currentDetectedFaces && currentDetectedFaces.length > 0" class="flex flex-col items-center space-y-3">
                                        <div
                                            v-for="(face, index) in currentDetectedFaces"
                                            :key="index"
                                            class="flex items-stretch gap-4"
                                            :class="{
                                                'border-[color:var(--brand-primary)]/50 dark:border-[color:var(--brand-primary-light)]/50': dragOverRoleIndex === index || dragOverAudioIndex === index
                                            }"
                                        >
                                            <!-- 左侧:角色卡片 -->
                                            <div
                                                class="w-85 bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl p-3 transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_12px_rgba(0,0,0,0.08)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.2)]"
                                                :class="{
                                                    'border-[color:var(--brand-primary)]/50 dark:border-[color:var(--brand-primary-light)]/50 bg-[color:var(--brand-primary)]/5 dark:bg-[color:var(--brand-primary-light)]/10': dragOverRoleIndex === index,
                                                    'opacity-40 scale-95 shadow-lg': draggedRoleIndex === index,
                                                    'transform translate-y-0': draggedRoleIndex !== index
                                                }"
                                                @dragover.prevent="onRoleDragOver($event, index)"
                                                @dragleave="onRoleDragLeave"
                                                @drop="onRoleDrop($event, index)"
                                            >
                                                <!-- 角色区域 - 可拖拽 -->
                                                <div
                                                    class="flex items-center justify-between gap-2 h-full w-full transition-all duration-200"
                                                    :class="{
                                                        'opacity-50 scale-95': draggedRoleIndex === index,
                                                        'opacity-100': draggedRoleIndex !== index
                                                    }"
                                                    :draggable="true"
                                                    @dragstart="onRoleDragStart($event, index)"
                                                    @dragend="draggedRoleIndex = -1; dragOverRoleIndex = -1"
                                                >
                                                    <!-- 左侧:拖拽手柄和角色名 -->
                                                    <div class="flex items-center gap-2 flex-1 min-w-0">
                                                        <!-- 拖拽手柄 -->
                                                        <div class="cursor-move text-[#86868b] dark:text-[#98989d] hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] transition-colors">
                                                            <i class="fas fa-grip-vertical text-sm"></i>
                                                        </div>

                                                        <!-- 角色名显示/编辑 -->
                                                        <div class="flex items-center">
                                                            <!-- 编辑模式 -->
                                                            <input
                                                                v-if="face.isEditing"
                                                                type="text"
                                                                :value="face.roleName"
                                                                :data-face-index="index"
                                                                @input="updateFaceRoleName(index, $event.target.value)"
                                                                @blur="saveFaceRoleName(index, $event.target.value)"
                                                                @keyup.enter="saveFaceRoleName(index, $event.target.value)"
                                                                @keyup.esc="toggleFaceEditing(index)"
                                                                :ref="(el) => { if (el && face.isEditing) { nextTick(() => el.focus()); } }"
                                                                class="w-24 px-2 py-1.5 text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] bg-white/80 dark:bg-[#2c2c2e]/80 border border-[color:var(--brand-primary)]/50 dark:border-[color:var(--brand-primary-light)]/60 rounded-lg focus:outline-none focus:ring-2 focus:ring-[color:var(--brand-primary)]/20 dark:focus:ring-[color:var(--brand-primary-light)]/20 transition-all duration-200"
                                                                :placeholder="`角色${index + 1}`"
                                                                @click.stop>
                                                            <!-- 显示模式 - 可点击编辑 -->
                                                            <span
                                                                v-else
                                                                @click.stop="toggleFaceEditing(index)"
                                                                class="w-24 px-2 py-1.5 text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] truncate tracking-tight cursor-text hover:bg-[color:var(--brand-primary)]/10 dark:hover:bg-[color:var(--brand-primary-light)]/15 hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] rounded transition-colors duration-200"
                                                            >
                                                                {{ face.roleName || `角色${index + 1}` }}
                                                            </span>
                                                        </div>
                                                    </div>

                                                    <!-- 右侧头像编辑按钮和删除按钮 -->
                                                    <div class="flex items-center gap-2 flex-shrink-0">
                                                        <!-- 角色头像容器 - 相对定位用于放置编辑按钮 -->
                                                        <div class="relative flex-shrink-0">
                                                            <!-- 角色头像 - 可点击 -->
                                                            <div
                                                                @click.stop="openFaceEditModal(index)"
                                                                class="flex-shrink-0 w-14 h-14 rounded-lg overflow-hidden border border-black/8 dark:border-white/8 bg-black/5 dark:bg-white/5 cursor-pointer hover:border-[color:var(--brand-primary)]/50 dark:hover:border-[color:var(--brand-primary-light)]/50 transition-all duration-200 hover:scale-105"
                                                            >
                                                                <img v-if="face.face_image"
                                                                    :src="'data:image/png;base64,' + face.face_image"
                                                                    alt="Face"
                                                                    class="w-full h-full object-cover"
                                                                    @error="(e) => { console.error('Face image load error:', index, e); e.target.style.display = 'none'; }">
                                                                <div v-else class="w-full h-full flex items-center justify-center text-[#86868b] dark:text-[#98989d] text-xs">
                                                                    <i class="fas fa-image"></i>
                                                                </div>
                                                            </div>

                                                            <!-- 编辑按钮 - 放在头像右上角 -->
                                                            <button
                                                                v-if="!face.isEditing"
                                                                @click.stop="openFaceEditModal(index)"
                                                                class="absolute -top-1 -right-1 w-5 h-5 flex items-center justify-center bg-white/95 dark:bg-[#2c2c2e]/95 backdrop-blur-[10px] border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] rounded-full transition-all duration-200 hover:scale-110 shadow-sm"
                                                                :title="t('edit') || '编辑'">
                                                                <i class="fas fa-edit text-xs"></i>
                                                            </button>
                                                            <!-- 保存按钮 -->
                                                            <button
                                                                v-else
                                                                @click.stop="() => {
                                                                    const inputEl = document.querySelector(`input[data-face-index='${index}']`);
                                                                    const newRoleName = inputEl?.value || face.roleName;
                                                                    saveFaceRoleName(index, newRoleName);
                                                                }"
                                                                class="absolute -top-1 -right-1 w-5 h-5 flex items-center justify-center bg-[color:var(--brand-primary)]/90 dark:bg-[color:var(--brand-primary-light)]/90 text-white rounded-full transition-all duration-200 hover:scale-110 shadow-sm"
                                                                :title="t('save') || '保存'">
                                                                <i class="fas fa-check text-xs"></i>
                                                            </button>
                                                        </div>

                                                        <!-- 删除按钮 -->
                                                        <button
                                                            @click.stop="removeFace(index)"
                                                            class="flex-shrink-0 w-6 h-6 flex items-center justify-center text-red-500 dark:text-red-400 hover:text-red-600 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-all duration-200"
                                                            :title="t('delete') || '删除'">
                                                            <i class="fas fa-trash text-xs"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- 中间链接符号 -->
                                            <div class="flex items-center justify-center flex-shrink-0">
                                                <div class="w-8 h-8 flex items-center justify-center text-[#86868b] dark:text-[#98989d]">
                                                    <i class="fas fa-link text-lg"></i>
                                                </div>
                                            </div>

                                            <!-- 右侧音频卡片 -->
                                            <div
                                                v-if="currentSeparatedAudios && currentSeparatedAudios.length > index"
                                                class="w-85 bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl p-3 transition-all duration-200 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_4px_12px_rgba(0,0,0,0.08)] dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.2)]"
                                                :class="{
                                                    'border-[color:var(--brand-primary)]/50 dark:border-[color:var(--brand-primary-light)]/50 bg-[color:var(--brand-primary)]/5 dark:bg-[color:var(--brand-primary-light)]/10': dragOverAudioIndex === index,
                                                    'opacity-40 scale-95 shadow-lg': draggedAudioIndex === index,
                                                    'transform translate-y-0': draggedAudioIndex !== index
                                                }"
                                                @dragover.prevent="onAudioDragOver($event, index)"
                                                @dragleave="onAudioDragLeave"
                                                @drop="onAudioDrop($event, index)"
                                            >
                                                <!-- 音频区域 - 可拖拽 -->
                                                <div
                                                    class="flex items-center gap-2 h-full transition-all duration-200"
                                                    :class="{
                                                        'opacity-50 scale-95': draggedAudioIndex === index,
                                                        'opacity-100': draggedAudioIndex !== index
                                                    }"
                                                    :draggable="true"
                                                    @dragstart="onAudioDragStart($event, index)"
                                                    @dragend="draggedAudioIndex = -1; dragOverAudioIndex = -1"
                                                >
                                                    <!-- 拖拽手柄 -->
                                                    <div class="cursor-move text-[#86868b] dark:text-[#98989d] hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] transition-colors">
                                                        <i class="fas fa-grip-vertical text-sm"></i>
                                                    </div>

                                                    <!-- 音色名显示/编辑 -->
                                                    <div class="flex items-center">
                                                        <!-- 编辑模式 -->
                                                        <input
                                                            v-if="currentSeparatedAudios[index].isEditing"
                                                            type="text"
                                                            :value="currentSeparatedAudios[index].audioName"
                                                            @input="updateSeparatedAudioName(index, $event.target.value)"
                                                            @blur="saveSeparatedAudioName(index, $event.target.value)"
                                                            @keyup.enter="saveSeparatedAudioName(index, $event.target.value)"
                                                            @keyup.esc="toggleSeparatedAudioEditing(index)"
                                                            :ref="(el) => { if (el && currentSeparatedAudios[index].isEditing) { nextTick(() => el.focus()); } }"
                                                            class="w-24 px-2 py-1 text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] bg-white/80 dark:bg-[#2c2c2e]/80 border border-[color:var(--brand-primary)]/50 dark:border-[color:var(--brand-primary-light)]/60 rounded-lg focus:outline-none focus:ring-2 focus:ring-[color:var(--brand-primary)]/20 dark:focus:ring-[color:var(--brand-primary-light)]/20 transition-all duration-200"
                                                            :placeholder="`音色${index + 1}`"
                                                            @click.stop>
                                                        <!-- 显示模式 - 可点击编辑 -->
                                                        <span
                                                            v-else
                                                            @click.stop="toggleSeparatedAudioEditing(index)"
                                                            class="w-24 px-2 py-1 text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight truncate cursor-text hover:bg-[color:var(--brand-primary)]/10 dark:hover:bg-[color:var(--brand-primary-light)]/15 hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] rounded transition-colors duration-200"
                                                        >
                                                            {{ currentSeparatedAudios[index].audioName || `音色${index + 1}` }}
                                                        </span>
                                                    </div>

                                                    <!-- 音频播放器 -->
                                                    <div class="flex items-center gap-2 justify-center flex-shrink-0">
                                                        <!-- 播放/暂停按钮 -->
                                                        <button
                                                            @click="toggleSeparatedAudioPlayback(index)"
                                                            class="flex-shrink-0 w-10 h-10 bg-[color:var(--brand-primary)]/90 dark:bg-[color:var(--brand-primary-light)]/90 rounded-full flex items-center justify-center text-white cursor-pointer hover:scale-110 transition-all duration-200 shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.3)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.4)]"
                                                        >
                                                            <i :class="getSeparatedAudioPlaying(index) ? 'fas fa-pause' : 'fas fa-play'" class="text-xs ml-0.5"></i>
                                                        </button>

                                                        <!-- 右侧时长和进度条 -->
                                                        <div class="flex flex-col justify-center" style="gap: 2px;">
                                                            <!-- 音频时长 - 显示在进度条上方 -->
                                                            <div class="text-xs font-medium text-[#86868b] dark:text-[#98989d] tracking-tight text-center" style="width: 128px;">
                                                                {{ formatAudioPreviewTime(getSeparatedAudioCurrentTime(index)) }} / {{ formatAudioPreviewTime(getSeparatedAudioDuration(index)) }}
                                                            </div>

                                                            <!-- 进度条 -->
                                                            <div class="w-32" v-if="getSeparatedAudioDuration(index) > 0">
                                                                <input
                                                                    type="range"
                                                                    :min="0"
                                                                    :max="getSeparatedAudioDuration(index)"
                                                                    :value="getSeparatedAudioCurrentTime(index)"
                                                                    @input="(e) => onSeparatedAudioProgressChange(index, e)"
                                                                    @change="(e) => onSeparatedAudioProgressChange(index, e)"
                                                                    @mousedown="separatedAudioIsDragging[index] = true"
                                                                    @mouseup="(e) => onSeparatedAudioProgressEnd(index, e)"
                                                                    class="w-full h-1 bg-black/6 dark:bg-white/15 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-[color:var(--brand-primary)] dark:[&::-webkit-slider-thumb]:bg-[color:var(--brand-primary-light)] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer"
                                                                />
                                                            </div>
                                                        </div>

                                                        <!-- 隐藏的音频元素 -->
                                                        <audio
                                                            :ref="el => { if (el) separatedAudioElements[index] = el }"
                                                            :src="currentSeparatedAudios[index].audioDataUrl"
                                                            @loadedmetadata="() => onSeparatedAudioLoaded(index)"
                                                            @timeupdate="() => onSeparatedAudioTimeUpdate(index)"
                                                            @ended="() => onSeparatedAudioEnded(index)"
                                                            @play="() => separatedAudioPlaying[index] = true"
                                                            @pause="() => separatedAudioPlaying[index] = false"
                                                            @error="() => handleSeparatedAudioError(index)"
                                                            class="hidden"
                                                        ></audio>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- 音频占位符如果没有对应的分离音频 -->
                                            <div
                                                v-else
                                                class="w-85 bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-xl p-3 flex items-center justify-center text-sm text-[#86868b] dark:text-[#98989d] tracking-tight"
                                            >
                                                <span>{{ t('waitingForMultipleRolesAudio') }}</span>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 新增角色按钮 -->
                                    <div v-if="selectedTaskId === 's2v' && getCurrentImagePreview() && isMultiRoleMode" class="flex justify-center mt-4">
                                        <button
                                            @click="openFaceEditModal(-1)"
                                            class="w-8 h-8 flex items-center justify-center bg-[#86868b]/20 dark:bg-[#98989d]/20 text-[#86868b] dark:text-[#98989d] rounded-full transition-all duration-200 hover:bg-[#86868b]/30 dark:hover:bg-[#98989d]/30 hover:scale-110 active:scale-100"
                                            :title="t('addRole') || '新增角色'"
                                        >
                                            <i class="fas fa-plus text-sm"></i>
                                        </button>
                                    </div>
                                </div>

                                        <!-- 提示词输入区域 - Apple 风格animate 任务类型不显示 -->
                                        <div v-if="selectedTaskId !== 'animate'">
                                            <div class="mt-8 space-y-3 flex justify-between items-center mb-3">
                                                <label class="text-sm font-medium text-[#1d1d1f] dark:text-[#f5f5f7] flex items-center tracking-tight">
                                                        {{ t('prompt') }}
                                                        <button @click="showPromptModal = true; promptModalTab = 'templates'"
                                                            class="ml-2 text-xs text-[#86868b] dark:text-[#98989d] hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] transition-colors"
                                                            :title="t('promptTemplates')">
                                                        <i class="fas fa-lightbulb text-lg"></i>
                                                    </button>
                                                </label>
                                                <div class="text-xs text-[#86868b] dark:text-[#98989d] tracking-tight">
                                                    {{ getCurrentForm().prompt?.length || 0 }} / 1000
                                                </div>
                                            </div>
                                            <div class="relative">
                                                <textarea v-model="getCurrentForm().prompt"
                                                    class="relative w-full bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-2xl px-5 py-4 text-[15px] text-[#1d1d1f] dark:text-[#f5f5f7] transition-all duration-200 resize-none main-scrollbar placeholder-[#86868b] dark:placeholder-[#98989d] tracking-tight hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 focus:outline-none focus:border-[color:var(--brand-primary)]/50 dark:focus:border-[color:var(--brand-primary-light)]/60 focus:shadow-[0_4px_16px_rgba(var(--brand-primary-rgb),0.12)] dark:focus:shadow-[0_4px_16px_rgba(var(--brand-primary-light-rgb),0.2)]"
                                                    :placeholder="getPromptPlaceholder()"
                                                    rows="2"
                                                    maxlength="1000"
                                                    required></textarea>
                                            </div>

                                            <div class="flex justify-between items-center mt-3">
                                                <button @click="clearPrompt"
                                                    class="flex items-center text-sm rounded-lg px-3 py-1.5 transition-all duration-200 text-[#86868b] dark:text-[#98989d] hover:text-[color:var(--brand-primary)] dark:hover:text-[color:var(--brand-primary-light)] hover:bg-black/4 dark:hover:bg-white/6 group tracking-tight">
                                                    <i class="fas fa-sync-alt text-sm mr-2 group-hover:rotate-180 transition-transform duration-300"></i>
                                                    {{ t('clear') }}
                                                </button>

                                            </div>
LiangLiu's avatar
LiangLiu committed
3173
                                        </div>
LiangLiu's avatar
LiangLiu committed
3174
3175
3176
                                <!-- 提交按钮 - Apple 极简风格 -->
                                <div class="flex justify-center mt-8">
                                    <button @click="handleSubmitTask" :disabled="submitting || templateLoading"
LiangLiu's avatar
LiangLiu committed
3177
                                            class="gap-3 cursor-pointer relative bg-white/95 dark:bg-[#2c2c2e]/95 backdrop-blur-[20px] border border-black/8 dark:border-white/8 rounded-full px-10 py-4 text-base font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] hover:scale-105 hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/12 dark:hover:border-white/12 hover:shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:hover:shadow-[0_8px_24px_rgba(0,0,0,0.3)] active:scale-100 transition-all duration-200 ease-out min-w-[250px] max-w-[400px] tracking-tight disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100 disabled:hover:shadow-none"
LiangLiu's avatar
LiangLiu committed
3178
3179
                                            :class="{ 'disabled': submitting || templateLoading }">

LiangLiu's avatar
LiangLiu committed
3180
3181
                                        <i v-if="submitting" class="fas fa-spinner fa-spin text-lg mr-2 text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
                                        <i v-else-if="templateLoading" class="fas fa-spinner fa-spin text-lg mr-2 text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)]"></i>
3182
                                        <i v-else class="fi fi-sr-select text-lg text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)] transition-all duration-200 pointer-events-none"></i>
LiangLiu's avatar
LiangLiu committed
3183
                                        <span class="pl-2 text-base font-semibold transition-all duration-200 pointer-events-none">{{ submitting ? t('submitting') : templateLoading ? '模板加载中...' : t('generateVideo') }}</span>
LiangLiu's avatar
LiangLiu committed
3184
                                        </button>
LiangLiu's avatar
LiangLiu committed
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
                                </div>

                                </div>

                                </div>

                            </div>
                </div>

                        </div>
                </div>
                        </div>

LiangLiu's avatar
LiangLiu committed
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
                    <!-- 历史任务区域 - Apple 风格 -->
                    <div v-if="tasks.length > 0" class="task-carousel mt-16">
                        <div class="flex-1 p-6">
                            <div class="relative flex items-center justify-center mb-8">
                                <!-- 标题 - Apple 风格 -->
                                <h2 class="text-3xl sm:text-3xl md:text-4xl lg:text-4xl font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">{{ t('historyTask') }}</h2>
                                <!-- 更多按钮 - Apple 风格 -->
                                <button @click="switchToProjectsView()"
                                    class="absolute right-0 flex items-center gap-2 px-4 py-2 bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/6 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/10 dark:hover:border-white/12 rounded-full transition-all duration-200"
                                    :title="t('viewMore')">
                                <span class="text-sm font-medium tracking-tight">{{ t('more') }}</span>
                                <i class="fas fa-arrow-right text-xs"></i>
                            </button>
                            </div>
                            <div class="mx-auto">
                                <TaskCarousel :tasks="tasks" />
                            </div>
                        </div>
                    </div>
LiangLiu's avatar
LiangLiu committed
3217

LiangLiu's avatar
LiangLiu committed
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227

                    <!-- 精选模版区域 - Apple 风格 -->
                    <div v-if="currentFeaturedTemplates.length > 0" class="flex-1 flex flex-col min-h-0 mt-20">
                        <div class="flex-1 p-6">
                            <!-- 控制区域 - Apple 风格 -->
                            <div class="relative flex items-center justify-center mb-8">
                                <!-- 标题和随机按钮 -->
                                <div class="flex items-center gap-4">
                                    <h2 class="text-3xl sm:text-3xl md:text-4xl lg:text-4xl font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] tracking-tight">{{ t('discover') }}</h2>
                                    <!-- 随机图标按钮 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
3228
3229
                                    <button @click="refreshRandomTemplates"
                                            :disabled="featuredTemplatesLoading"
LiangLiu's avatar
LiangLiu committed
3230
                                            class="w-10 h-10 flex items-center justify-center bg-[color:var(--brand-primary)]/10 dark:bg-[color:var(--brand-primary-light)]/15 border border-[color:var(--brand-primary)]/20 dark:border-[color:var(--brand-primary-light)]/20 text-[color:var(--brand-primary)] dark:text-[color:var(--brand-primary-light)] rounded-full transition-all duration-200 hover:scale-110 hover:bg-[color:var(--brand-primary)]/20 dark:hover:bg-[color:var(--brand-primary-light)]/25 active:scale-100 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
LiangLiu's avatar
LiangLiu committed
3231
                                            :title="t('refreshRandomTemplates')">
LiangLiu's avatar
LiangLiu committed
3232
                                        <i class="fas fa-random text-sm"
LiangLiu's avatar
LiangLiu committed
3233
3234
3235
                                           :class="{ 'animate-spin': featuredTemplatesLoading }"></i>
                                    </button>
                                </div>
LiangLiu's avatar
LiangLiu committed
3236
                                <!-- 更多按钮 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
3237
                                <button @click="switchToInspirationView()"
LiangLiu's avatar
LiangLiu committed
3238
                                    class="absolute right-0 flex items-center gap-2 px-4 py-2 bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] border border-black/6 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] hover:border-black/10 dark:hover:border-white/12 rounded-full transition-all duration-200"
LiangLiu's avatar
LiangLiu committed
3239
                                    :title="t('viewMore')">
LiangLiu's avatar
LiangLiu committed
3240
                                <span class="text-sm font-medium tracking-tight">{{ t('more') }}</span>
LiangLiu's avatar
LiangLiu committed
3241
3242
3243
3244
                                <i class="fas fa-arrow-right text-xs"></i>
                            </button>
                            </div>

LiangLiu's avatar
LiangLiu committed
3245
                            <!-- 精选模版随机列布局 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
3246
3247
3248
3249
                            <div
                                ref="featuredMasonryRef"
                                class="relative"
                                :style="{ height: masonryHeight + 'px' }">
LiangLiu's avatar
LiangLiu committed
3250
3251
                            <!-- 随机列 -->
                            <div v-for="(column, columnIndex) in templatesWithRandomColumns.columns" :key="columnIndex"
LiangLiu's avatar
LiangLiu committed
3252
                                    data-masonry-column
LiangLiu's avatar
LiangLiu committed
3253
3254
3255
3256
3257
3258
3259
                                    class="absolute transition-all duration-500 animate-fade-in"
                                    :style="{
                                        width: column.width,
                                        left: column.left,
                                        top: column.top,
                                        animationDelay: `${columnIndex * 0.2}s`
                                    }">
LiangLiu's avatar
LiangLiu committed
3260
                                <!-- 列内的模版卡片 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
3261
                                <div v-for="item in column.templates" :key="item.task_id"
LiangLiu's avatar
LiangLiu committed
3262
                                        class="mb-3 group relative bg-white/80 dark:bg-[#2c2c2e]/80 backdrop-blur-[20px] rounded-2xl overflow-hidden border border-black/8 dark:border-white/8 hover:border-[color:var(--brand-primary)]/30 dark:hover:border-[color:var(--brand-primary-light)]/30 hover:bg-white dark:hover:bg-[#3a3a3c] transition-all duration-200 hover:shadow-[0_8px_24px_rgba(var(--brand-primary-rgb),0.15)] dark:hover:shadow-[0_8px_24px_rgba(var(--brand-primary-light-rgb),0.2)]">
LiangLiu's avatar
LiangLiu committed
3263
                                <!-- 视频缩略图区域 -->
LiangLiu's avatar
LiangLiu committed
3264
3265
                                <div class="cursor-pointer bg-black/2 dark:bg-white/2 relative flex flex-col"
                                @click="previewTemplateDetail(item, false)"
LiangLiu's avatar
LiangLiu committed
3266
3267
3268
3269
                                :title="t('viewTemplateDetail')">
                                        <!-- 视频预览 -->
                                        <video v-if="item?.outputs?.output_video"
                                            :src="getTemplateFileUrl(item.outputs.output_video,'videos')"
3270
                                            :poster="item?.inputs?.input_image ? getTemplateFileUrl(item.inputs.input_image,'images') : undefined"
LiangLiu's avatar
LiangLiu committed
3271
                                            class="w-full h-auto object-contain group-hover:scale-[1.02] transition-transform duration-200"
LiangLiu's avatar
LiangLiu committed
3272
3273
                                            preload="auto" playsinline webkit-playsinline
                                            @mouseenter="playVideo($event)" @mouseleave="pauseVideo($event)"
LiangLiu's avatar
LiangLiu committed
3274
3275
3276
                                            @loadeddata="handleMasonryVideoLoaded($event)"
                                            @ended="handleMasonryVideoEnded($event)"
                                            @error="handleMasonryVideoError($event)"></video>
LiangLiu's avatar
LiangLiu committed
3277
                                    <!-- 图片缩略图 -->
3278
                                        <img v-else-if="item?.inputs?.input_image"
LiangLiu's avatar
LiangLiu committed
3279
3280
                                        :src="getTemplateFileUrl(item.inputs.input_image,'images')"
                                        :alt="item.params?.prompt || '模板图片'"
LiangLiu's avatar
LiangLiu committed
3281
                                        class="w-full h-auto object-contain group-hover:scale-[1.02] transition-transform duration-200"
LiangLiu's avatar
LiangLiu committed
3282
3283
                                        @load="handleMasonryImageLoaded"
                                        @error="handleMasonryImageError" />
3284
3285
3286
3287
                                        <!-- 如果没有图片显示占位符 -->
                                        <div v-else class="w-full h-[200px] flex items-center justify-center bg-[#f5f5f7] dark:bg-[#1c1c1e]">
                                            <i class="fas fa-image text-3xl text-[#86868b]/30 dark:text-[#98989d]/30"></i>
                                        </div>
LiangLiu's avatar
LiangLiu committed
3288
                                        <!-- 移动端播放按钮 - Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
3289
3290
                                        <button v-if="item?.outputs?.output_video"
                                            @click.stop="toggleVideoPlay($event)"
LiangLiu's avatar
LiangLiu committed
3291
                                            class="md:hidden absolute bottom-3 left-1/2 transform -translate-x-1/2 w-10 h-10 rounded-full bg-white/95 dark:bg-[#2c2c2e]/95 backdrop-blur-[20px] shadow-[0_2px_8px_rgba(0,0,0,0.2)] dark:shadow-[0_2px_8px_rgba(0,0,0,0.4)] flex items-center justify-center text-[#1d1d1f] dark:text-[#f5f5f7] hover:scale-105 transition-all duration-200 z-20">
LiangLiu's avatar
LiangLiu committed
3292
3293
                                            <i class="fas fa-play text-sm"></i>
                                        </button>
LiangLiu's avatar
LiangLiu committed
3294
                                    <!-- 悬浮操作按钮下方居中仅桌面端- Apple 风格 -->
LiangLiu's avatar
LiangLiu committed
3295
3296
                                    <div
                                        class="hidden md:flex absolute bottom-3 left-1/2 transform -translate-x-1/2 items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none z-10 w-full">
LiangLiu's avatar
LiangLiu committed
3297
                                        <div class="flex gap-2 pointer-events-auto">
LiangLiu's avatar
LiangLiu committed
3298
                                            <button @click.stop="applyTemplateImage(item)"
LiangLiu's avatar
LiangLiu committed
3299
                                                class="w-10 h-10 rounded-full bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] backdrop-blur-[20px] shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.3)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.4)] flex items-center justify-center text-white hover:scale-110 active:scale-100 transition-all duration-200"
LiangLiu's avatar
LiangLiu committed
3300
3301
3302
3303
                                                :title="t('applyImage')">
                                                <i class="fas fa-image text-sm"></i>
                                            </button>
                                            <button @click.stop="applyTemplateAudio(item)"
LiangLiu's avatar
LiangLiu committed
3304
                                                class="w-10 h-10 rounded-full bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] backdrop-blur-[20px] shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.3)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.4)] flex items-center justify-center text-white hover:scale-110 active:scale-100 transition-all duration-200"
LiangLiu's avatar
LiangLiu committed
3305
3306
3307
                                                :title="t('applyAudio')">
                                                <i class="fas fa-music text-sm"></i>
                                            </button>
LiangLiu's avatar
LiangLiu committed
3308
3309
                                            <button @click.stop="handleUseTemplate(item)"
                                                class="w-10 h-10 rounded-full bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] backdrop-blur-[20px] shadow-[0_2px_8px_rgba(var(--brand-primary-rgb),0.3)] dark:shadow-[0_2px_8px_rgba(var(--brand-primary-light-rgb),0.4)] flex items-center justify-center text-white hover:scale-110 active:scale-100 transition-all duration-200"
LiangLiu's avatar
LiangLiu committed
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
                                                :title="t('useTemplate')">
                                                <i class="fas fa-clone text-sm"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

3323
3324
3325
3326
3327
3328
3329
3330
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
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
            <!-- 脸部编辑模态框 - 显示放大图片和可拖拽的边界框 -->
            <div v-if="showFaceEditModal"
                class="fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 dark:bg-black/80 backdrop-blur-sm"
                @click="closeFaceEditModal">
                <div
                    @click.stop
                    class="relative bg-white/95 dark:bg-[#2c2c2e]/95 backdrop-blur-[20px] rounded-2xl p-6 max-w-4xl max-h-[90vh] overflow-auto shadow-[0_12px_32px_rgba(0,0,0,0.6)] dark:shadow-[0_12px_32px_rgba(0,0,0,0.8)]">
                    <!-- 关闭按钮 -->
                    <button
                        @click="closeFaceEditModal"
                        class="absolute top-4 right-4 w-10 h-10 flex items-center justify-center bg-white/80 dark:bg-[#2c2c2e]/80 border border-black/8 dark:border-white/8 text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-white dark:hover:bg-[#3a3a3c] rounded-full transition-all duration-200 z-10"
                        :title="t('close') || '关闭'">
                        <i class="fas fa-times text-sm"></i>
                    </button>

                    <!-- 标题 -->
                    <h3 class="text-xl font-semibold text-[#1d1d1f] dark:text-[#f5f5f7] mb-4 tracking-tight">
                        {{ isAddingNewFace ? (t('addNewRole') || '新增角色') : (t('adjustFaceBox') || '调整人脸边界框') }}
                    </h3>

                    <!-- 图片容器 -->
                    <div
                        ref="imageContainerRef"
                        class="relative inline-block max-w-full"
                        :style="imageNaturalSize.width > 0 && imageNaturalSize.height > 0 && !imageLoaded ? {
                            width: `${Math.min(imageNaturalSize.width, 800)}px`,
                            height: `${Math.min(imageNaturalSize.height, 600)}px`,
                            aspectRatio: `${imageNaturalSize.width} / ${imageNaturalSize.height}`
                        } : {}">
                        <!-- 占位符 - 图片加载前显示 -->
                        <div
                            v-show="!imageLoaded"
                            class="absolute inset-0 w-full h-full min-w-[400px] min-h-[300px] bg-[#f5f5f7] dark:bg-[#1e1e1e] rounded-xl flex items-center justify-center z-10">
                            <div class="flex flex-col items-center gap-3">
                                <i class="fas fa-spinner fa-spin text-2xl text-[#86868b] dark:text-[#98989d]"></i>
                                <span class="text-sm text-[#86868b] dark:text-[#98989d]">{{ t('loading') || '加载中...' }}</span>
                            </div>
                        </div>
                        <!-- 实际图片 - 始终渲染但加载完成后才显示 -->
                        <img
                            :src="originalImageUrl"
                            alt="Face Edit"
                            class="max-w-full max-h-[70vh] h-auto object-contain rounded-xl"
                            :class="{ 'opacity-0': !imageLoaded }"
                            @load="handleFaceEditImageLoad"
                            @error="handleFaceEditImageError">

                        <!-- 遮罩层 - 框外区域变暗 -->
                        <svg
                            v-if="editingFaceBbox.length === 4 && getBboxStyle.left"
                            class="absolute inset-0 pointer-events-none z-[5]"
                            :style="{
                                left: 0,
                                top: 0,
                                width: '100%',
                                height: '100%'
                            }">
                            <defs>
                                <mask id="bbox-mask">
                                    <rect width="100%" height="100%" fill="white"/>
                                    <rect
                                        :x="getBboxStyle.left"
                                        :y="getBboxStyle.top"
                                        :width="getBboxStyle.width"
                                        :height="getBboxStyle.height"
                                        fill="black"/>
                                </mask>
                            </defs>
                            <rect
                                width="100%"
                                height="100%"
                                fill="rgba(0,0,0,0.5)"
                                mask="url(#bbox-mask)"/>
                        </svg>

                        <!-- 角色名字标签 - 显示在边界框上方 -->
                        <div
                            v-if="editingFaceBbox.length === 4 && getBboxStyle.left && getRoleNameLabelStyle.roleName"
                            :style="{
                                left: getRoleNameLabelStyle.left,
                                top: getRoleNameLabelStyle.top,
                                transform: getRoleNameLabelStyle.transform
                            }"
                            class="absolute px-2 py-1 text-xs font-medium text-white bg-[color:var(--brand-primary)]/90 dark:bg-[color:var(--brand-primary-light)]/90 rounded-md shadow-lg whitespace-nowrap pointer-events-none z-10">
                            {{ getRoleNameLabelStyle.roleName }}
                        </div>

                        <!-- 边界框 -->
                        <div
                            v-if="editingFaceBbox.length === 4 && getBboxStyle.left"
                            :style="getBboxStyle"
                            @mousedown="(e) => startDragBbox(e, 'move')"
                            class="absolute border-2 border-[color:var(--brand-primary)] dark:border-[color:var(--brand-primary-light)] cursor-move bg-transparent hover:bg-[color:var(--brand-primary)]/5 dark:hover:bg-[color:var(--brand-primary-light)]/5 transition-colors duration-200"
                            :class="{ 'ring-2 ring-[color:var(--brand-primary)]/50 dark:ring-[color:var(--brand-primary-light)]/50 bg-[color:var(--brand-primary)]/10 dark:bg-[color:var(--brand-primary-light)]/10': isDraggingBbox }"
                            style="box-sizing: border-box;">

                            <!-- 四个角的拖拽手柄 -->
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-nw')"
                                :style="{
                                    width: `${getBboxStyle.indicatorSize || 16}px`,
                                    height: `${getBboxStyle.indicatorSize || 16}px`,
                                    left: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    top: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] rounded-full border-2 border-white dark:border-[#2c2c2e] shadow-lg cursor-nw-resize hover:scale-110 transition-transform z-20"></div>
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-ne')"
                                :style="{
                                    width: `${getBboxStyle.indicatorSize || 16}px`,
                                    height: `${getBboxStyle.indicatorSize || 16}px`,
                                    right: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    top: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] rounded-full border-2 border-white dark:border-[#2c2c2e] shadow-lg cursor-ne-resize hover:scale-110 transition-transform z-20"></div>
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-sw')"
                                :style="{
                                    width: `${getBboxStyle.indicatorSize || 16}px`,
                                    height: `${getBboxStyle.indicatorSize || 16}px`,
                                    left: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    bottom: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] rounded-full border-2 border-white dark:border-[#2c2c2e] shadow-lg cursor-sw-resize hover:scale-110 transition-transform z-20"></div>
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-se')"
                                :style="{
                                    width: `${getBboxStyle.indicatorSize || 16}px`,
                                    height: `${getBboxStyle.indicatorSize || 16}px`,
                                    right: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    bottom: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] rounded-full border-2 border-white dark:border-[#2c2c2e] shadow-lg cursor-se-resize hover:scale-110 transition-transform z-20"></div>

                            <!-- 四个边的拖拽手柄 -->
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-n')"
                                :style="{
                                    width: 'calc(100% + 16px)',
                                    height: `${getBboxStyle.indicatorSize || 16}px`,
                                    left: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    top: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute cursor-n-resize hover:bg-[color:var(--brand-primary)]/20 dark:hover:bg-[color:var(--brand-primary-light)]/20 transition-colors rounded-t z-10"></div>
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-s')"
                                :style="{
                                    width: 'calc(100% + 16px)',
                                    height: `${getBboxStyle.indicatorSize || 16}px`,
                                    left: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    bottom: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute cursor-s-resize hover:bg-[color:var(--brand-primary)]/20 dark:hover:bg-[color:var(--brand-primary-light)]/20 transition-colors rounded-b z-10"></div>
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-w')"
                                :style="{
                                    width: `${getBboxStyle.indicatorSize || 16}px`,
                                    height: 'calc(100% + 16px)',
                                    left: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    top: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute cursor-w-resize hover:bg-[color:var(--brand-primary)]/20 dark:hover:bg-[color:var(--brand-primary-light)]/20 transition-colors rounded-l z-10"></div>
                            <div
                                @mousedown.stop="(e) => startDragBbox(e, 'resize-e')"
                                :style="{
                                    width: `${getBboxStyle.indicatorSize || 16}px`,
                                    height: 'calc(100% + 16px)',
                                    right: `${-(getBboxStyle.indicatorSize || 16) / 2}px`,
                                    top: `${-(getBboxStyle.indicatorSize || 16) / 2}px`
                                }"
                                class="absolute cursor-e-resize hover:bg-[color:var(--brand-primary)]/20 dark:hover:bg-[color:var(--brand-primary-light)]/20 transition-colors rounded-r z-10"></div>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="flex items-center justify-end gap-3 mt-6">
                        <button
                            @click="closeFaceEditModal"
                            class="px-4 py-2 text-sm font-medium text-[#86868b] dark:text-[#98989d] hover:text-[#1d1d1f] dark:hover:text-[#f5f5f7] hover:bg-black/4 dark:hover:bg-white/6 rounded-lg transition-all duration-200 tracking-tight">
                            {{ t('cancel') || '取消' }}
                        </button>
                        <button
                            @click="saveFaceBbox"
                            class="px-4 py-2 text-sm font-medium text-white bg-[color:var(--brand-primary)] dark:bg-[color:var(--brand-primary-light)] hover:opacity-90 rounded-lg transition-all duration-200 tracking-tight">
                            {{ t('save') || '保存' }}
                        </button>
                    </div>
                </div>
            </div>
LiangLiu's avatar
LiangLiu committed
3512

LiangLiu's avatar
LiangLiu committed
3513
3514
3515
</template>

<style scoped>
LiangLiu's avatar
LiangLiu committed
3516
/* Apple 风格极简设计 - 所有样式已通过 Tailwind CSS 的 dark: 前缀在 template 中定义 */
LiangLiu's avatar
LiangLiu committed
3517
</style>