lrj
1 天以前 9f8395fab13ca4b230a0f7d62636e209745c91d4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
197
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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
<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑新闻' : '新增新闻'"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <!-- 基本信息 -->
      <el-form-item label="新闻标题" prop="title">
        <el-input 
          v-model="form.title" 
          placeholder="请输入新闻标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
 
      <el-form-item label="排序字段" prop="sortOrder">
        <el-input-number 
          v-model="form.sortOrder" 
          :min="0"
          :max="9999"
          placeholder="请输入排序数字,数字越小越靠前"
          style="width: 200px"
        />
        <span class="form-tip">数字越小越靠前显示,0表示最优先</span>
      </el-form-item>
 
      <el-form-item label="新闻内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="6"
          placeholder="请输入新闻内容"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>
 
      <!-- 媒体文件上传 -->
      <el-form-item label="媒体文件">
        <div class="media-upload-container">
          <!-- 现有媒体文件显示 -->
          <div v-if="form.mediaFiles.length > 0" class="media-list">
            <div 
              v-for="(media, index) in form.mediaFiles" 
              :key="media.id || index"
              class="media-item"
            >
              <!-- 图片预览 -->
              <div v-if="isImage(media)" class="media-preview">
                <img :src="media.url" class="media-image" />
                <div class="media-info">
                  <div class="media-name">{{ media.name }}</div>
                  <div class="media-actions">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="handleDeleteMedia(media, index)"
                      :loading="media.deleting"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
              
              <!-- 视频预览 -->
              <div v-else-if="isVideo(media)" class="media-preview">
                <div class="video-thumbnail-container" @click="playVideo(media)">
                  <img 
                    v-if="media.thumbUrl || media.fullThumbUrl" 
                    :src="media.thumbUrl || media.fullThumbUrl" 
                    class="video-thumbnail" 
                  />
                  <div v-else class="video-placeholder">
                    <span>视频缩略图</span>
                  </div>
                  <div class="video-play-overlay">
                    <div class="video-play-button">
                      <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M8 5v14l11-7z"/>
                      </svg>
                    </div>
                  </div>
                </div>
                <div class="media-info">
                  <div class="media-name">{{ media.name }}</div>
                  <div class="media-actions">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="handleDeleteMedia(media, index)"
                      :loading="media.deleting"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
              
              <!-- 其他文件 -->
              <div v-else class="media-preview">
                <div class="file-icon">📄</div>
                <div class="media-info">
                  <div class="media-name">{{ media.name }}</div>
                  <div class="media-actions">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="handleDeleteMedia(media, index)"
                      :loading="media.deleting"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 上传按钮 -->
          <el-upload
            class="media-uploader"
            :show-file-list="false"
            :before-upload="beforeMediaUpload"
            :http-request="handleMediaUpload"
            accept="image/*,video/*"
            multiple
          >
            <div class="upload-area">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">选择媒体文件</div>
              <div class="upload-hint">支持图片、视频格式,图片≤10MB,视频≤500MB</div>
            </div>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>
 
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
 
<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { CarouselApi } from '@/api/carousel'
import { getMediasByTarget, deleteMedia, uploadFile, uploadVideoWithThumbnail } from '@/api/media'
import { isVideoFile } from '@/utils/video.js'
import { MediaTargetType } from '@/constants/mediaTargetType'
 
const props = defineProps({
  modelValue: Boolean,
  carouselData: Object
})
 
const emit = defineEmits(['update:modelValue', 'success'])
 
const formRef = ref()
const loading = ref(false)
 
// 控制弹窗显示
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})
 
// 是否为编辑模式
const isEdit = computed(() => !!props.carouselData?.id)
 
// 表单数据
const form = reactive({
  id: undefined,
  title: '',
  content: '',
  sortOrder: null,
  mediaFiles: []
})
 
// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}
 
// 监听轮播图数据变化,填充表单
watch(() => props.carouselData, (data) => {
  nextTick(async () => {
    if (data && data.id) {
      form.id = data.id
      form.title = data.title || ''
      form.content = data.content || ''
      form.sortOrder = data.sortOrder
      
      // 加载轮播图媒体文件(targetType=4 表示轮播图)
      try {
        console.log('=== 加载轮播图媒体 ===');
        console.log('轮播图ID:', data.id);
        const medias = await getMediasByTarget(MediaTargetType.CAROUSEL, parseInt(data.id))
        console.log('获取到的媒体列表:', medias);
        
        // 转换媒体数据格式,标记为已存在的文件
        form.mediaFiles = (medias || []).map(media => ({
          ...media,
          file: null,
          uploaded: true,
          isExisting: true,
          url: media.fullUrl
        }));
        
        console.log('转换后的媒体项:', form.mediaFiles);
      } catch (e) {
        console.warn('加载轮播图媒体失败:', e)
      }
    } else {
      resetForm()
    }
  })
}, { immediate: true })
 
// 重置表单
const resetForm = () => {
  form.id = undefined
  form.title = ''
  form.content = ''
  form.sortOrder = null
  form.mediaFiles = []
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
 
// 判断是否为图片
const isImage = (media) => {
  if (media.mediaType === 1) return true
  if (media.fileExt) {
    return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(media.fileExt.toLowerCase())
  }
  if (media.name) {
    const ext = media.name.split('.').pop()?.toLowerCase()
    return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(ext)
  }
  return false
}
 
// 判断是否为视频
const isVideo = (media) => {
  if (media.mediaType === 2) return true
  if (media.fileExt) {
    return ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'].includes(media.fileExt.toLowerCase())
  }
  if (media.name) {
    const ext = media.name.split('.').pop()?.toLowerCase()
    return ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'].includes(ext)
  }
  return false
}
 
// 播放视频
const playVideo = (media) => {
  const videoUrl = media.url || media.fullUrl
  if (videoUrl) {
    // 在新窗口中打开视频
    window.open(videoUrl, '_blank')
  } else {
    ElMessage.warning('视频文件不存在')
  }
}
 
// 处理媒体文件上传
const handleMediaFileUpload = async (carouselId) => {
  console.log('=== 开始上传媒体文件 ===');
  console.log('轮播图ID:', carouselId);
  console.log('待上传的文件:', form.mediaFiles.filter(m => !m.uploaded));
  
  // 只处理未上传的文件
  const filesToUpload = form.mediaFiles.filter(media => !media.uploaded && media.file);
  
  for (const media of filesToUpload) {
    try {
      console.log('上传文件:', media.name);
      
      let uploadResult;
      let thumbnailPath = null;
      
      // 检查是否为视频文件
      if (isVideoFile(media.file)) {
        console.log('检测到视频文件,开始处理视频和缩略图...');
        
        // 使用视频专用上传函数
        const videoResult = await uploadVideoWithThumbnail(media.file);
        uploadResult = videoResult.video;
        thumbnailPath = videoResult.thumbnail.path;
        
        console.log('视频和缩略图上传完成:', {
          video: uploadResult,
          thumbnail: videoResult.thumbnail
        });
      } else {
        // 普通文件上传
        uploadResult = await uploadFile(media.file);
        console.log('文件上传结果:', uploadResult);
      }
      
      if (uploadResult.success) {
        // 保存媒体信息到数据库
        const mediaData = {
          name: uploadResult.fileName,
          path: uploadResult.path,
          fileSize: uploadResult.fileSize,
          fileExt: uploadResult.fileName.split('.').pop() || 'jpg',
          mediaType: isVideo(media) ? 2 : 1, // 1表示图片,2表示视频
          targetType: MediaTargetType.CAROUSEL, // 轮播图
          targetId: parseInt(carouselId)
        };
        
        // 如果是视频文件,添加缩略图路径
        if (thumbnailPath) {
          mediaData.thumbPath = thumbnailPath;
          console.log('添加缩略图路径:', thumbnailPath);
        }
        
        await CarouselApi.saveMedia(mediaData);
        
        // 标记为已上传
        media.uploaded = true;
        media.url = uploadResult.fullUrl;
        if (thumbnailPath) {
          media.thumbnailUrl = thumbnailPath;
        }
        console.log('文件上传并保存成功:', media.name);
      }
    } catch (error) {
      console.error('文件上传失败:', media.name, error);
      ElMessage.error(`文件 ${media.name} 上传失败: ${error.message}`);
    }
  }
}
 
// 删除媒体文件
const handleDeleteMedia = async (media, index) => {
  try {
    await ElMessageBox.confirm('确定要删除这个媒体文件吗?', '确认删除', {
      type: 'warning'
    });
    
    media.deleting = true;
    
    if (media.isExisting && media.id) {
      // 删除已存在的媒体文件
      console.log('删除已存在的媒体文件:', media.id);
      const result = await deleteMedia(media.id);
      console.log('删除结果:', result);
      
      if (result) {
        form.mediaFiles.splice(index, 1);
        ElMessage.success('媒体文件删除成功');
      } else {
        throw new Error('删除失败');
      }
    } else {
      // 删除新选择但未上传的文件
      form.mediaFiles.splice(index, 1);
      ElMessage.success('已取消选择的媒体文件');
    }
  } catch (error) {
    console.error('删除媒体失败:', error);
    if (error !== 'cancel') {
      ElMessage.error('媒体删除失败: ' + error.message);
    }
  } finally {
    media.deleting = false;
  }
}
 
// 媒体文件上传前验证
const beforeMediaUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isVideo = file.type.startsWith('video/')
  
  if (!isImage && !isVideo) {
    ElMessage.error('只能上传图片或视频文件!')
    return false
  }
  
  if (isImage && file.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  
  if (isVideo && file.size / 1024 / 1024 > 500) {
    ElMessage.error('视频大小不能超过 500MB!')
    return false
  }
  
  return true
}
 
// 处理媒体文件上传
const handleMediaUpload = async (options) => {
  const { file } = options
  try {
    // 不立即上传,只添加到待上传列表
    const mediaItem = {
      file: file,
      name: file.name,
      type: file.type.startsWith('video/') ? 'video' : 'image',
      uploaded: false,
      isExisting: false,
      url: URL.createObjectURL(file) // 本地预览
    };
    
    form.mediaFiles.push(mediaItem);
    ElMessage.success('媒体文件已选择,点击更新按钮时将上传');
  } catch (error) {
    console.error('媒体文件处理失败:', error)
    ElMessage.error('媒体文件处理失败: ' + error.message)
  }
}
 
// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
 
  try {
    await formRef.value.validate()
    loading.value = true
 
    // 1. 先保存轮播图基本信息
    const submitData = {
      id: form.id,
      title: form.title,
      content: form.content || undefined,
      sortOrder: form.sortOrder
    }
 
    const savedCarousel = await CarouselApi.saveCarousel(submitData)
    console.log('轮播图保存成功:', savedCarousel);
    
    // 2. 上传新选择的媒体文件
    if (savedCarousel.id) {
      await handleMediaFileUpload(savedCarousel.id);
    }
    
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败: ' + error.message)
  } finally {
    loading.value = false
  }
}
 
// 关闭弹窗
const handleClose = () => {
  visible.value = false
  resetForm()
}
</script>
 
<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
 
.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}
 
.media-upload-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
 
.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
 
.media-item {
  position: relative;
  display: inline-block;
}
 
.media-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  padding: 8px;
  background: #fafafa;
}
 
.media-image {
  width: 150px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}
 
.media-video {
  width: 200px;
  height: 120px;
  border-radius: 4px;
}
 
.video-thumbnail-container {
  position: relative;
  width: 200px;
  height: 120px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
}
 
.video-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}
 
.video-placeholder {
  width: 100%;
  height: 100%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  color: #999;
  font-size: 14px;
}
 
.video-play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: opacity 0.3s ease;
}
 
.video-thumbnail-container:hover .video-play-overlay {
  opacity: 1;
}
 
.video-play-button {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  transition: all 0.3s ease;
}
 
.video-play-button:hover {
  background: rgba(255, 255, 255, 1);
  transform: scale(1.1);
}
 
.file-icon {
  font-size: 48px;
  margin-bottom: 8px;
}
 
.media-info {
  margin-top: 8px;
  text-align: center;
}
 
.media-name {
  font-size: 12px;
  color: #606266;
  margin-bottom: 8px;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 120px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  transition: var(--el-transition-duration-fast);
  text-align: center;
  
  &:hover {
    border-color: var(--el-color-primary);
  }
}
 
.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}
 
.upload-text {
  font-size: 14px;
  color: #8c939d;
  margin-bottom: 4px;
}
 
.upload-hint {
  font-size: 12px;
  color: #999;
  line-height: 1.2;
}
</style>