<template>
  <div class="video-upload-container">
    <!-- 上传区域 -->
    <el-upload
      ref="uploadRef"
      action="#"
      :before-upload="beforeUpload"
      :on-change="handleFileChange"
      :show-file-list="false"
      :auto-upload="false"
      drag
      accept="video/*"
      class="upload-area"
    >
      <div v-if="!uploading && !videoInfo" class="upload-placeholder">
        <el-icon class="upload-icon"><IEpVideoCamera /></el-icon>
        <div class="upload-text">
          <p>拖拽视频文件到此处，或点击选择文件</p>
          <p class="upload-hint">支持 MP4、AVI、MOV 格式，文件大小不超过 {{ maxSize }}MB</p>
        </div>
      </div>

      <!-- 上传进度 -->
      <div v-if="uploading" class="upload-progress">
        <div class="progress-info">
          <el-icon class="progress-icon"><IEpVideoPlay /></el-icon>
          <div class="progress-details">
            <p class="file-name">{{ currentFile?.name }}</p>
            <p class="progress-text">正在上传...</p>
          </div>
        </div>
        <el-progress :percentage="uploadProgress" :stroke-width="8" class="progress-bar" />
        <el-button type="danger" size="small" @click.stop="cancelUpload" class="cancel-btn">
          取消上传
        </el-button>
      </div>

      <!-- 上传完成 -->
      <div v-if="videoInfo && !uploading" class="upload-success-optimized">
        <div class="video-info-display">
          <div class="video-icon-wrapper">
            <el-icon class="video-preview-icon"><IEpVideoCamera /></el-icon>
          </div>
          <div class="video-details-text">
            <p class="video-name">{{ videoInfo.name }}</p>
            <p class="video-meta">
              <span v-if="videoInfo.size"> {{ formatFileSize(videoInfo.size) }} </span> ·
              <span v-if="videoInfo.duration"> {{ videoInfo.duration }} </span> ·
              <span v-if="videoInfo.resolution"> {{ videoInfo.resolution }} </span>
            </p>
          </div>
        </div>
        <div class="video-actions" :class="btnClass">
          <el-button type="primary" @click="replaceVideo">
            <el-icon class="mr-2"><IEpRefresh /></el-icon> 重新选择
          </el-button>
          <span></span>
          <el-button type="success" @click="previewVideo">
            <el-icon class="mr-2"><IEpView /></el-icon> 预览播放
          </el-button>
        </div>
      </div>
    </el-upload>

    <!-- 错误提示 -->
    <div v-if="uploadError" class="upload-error">
      <el-icon class="error-icon"><IEpWarning /></el-icon>
      <span>{{ uploadError }}</span>
      <el-button type="text" @click="retryUpload">重试</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { uploadFile as uploadFileApi } from '@/api/common'
import type { UploadFile } from 'element-plus'
import type { UploadVideoProps } from './types'
import { getVideoMetadata } from '@/utils'
import { push } from 'notivue'

interface VideoInfo {
  url: string
  name: string
  size: number
  duration: string
  resolution: string
  poster?: string
  fileId?: string
}

const {
  maxSize = 1000,
  acceptFormats = ['mp4', 'avi', 'mov', 'wmv', 'flv'],
  btnClass = '',
} = defineProps<UploadVideoProps>()
const modelValue = defineModel<string>('modelValue', { required: true })
const videoInfo = defineModel<VideoInfo | null>('videoInfo', { required: false, default: null })

const emit = defineEmits<{
  uploadSuccess: [{ file: File; url: string; videoDuration: string }]
}>()

// 响应式数据
const uploadRef = ref()
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadError = ref('')
const currentFile = ref<File | null>(null)

// 文件大小格式化
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 上传前验证
const beforeUpload = (file: File): boolean => {
  uploadError.value = ''
  uploadProgress.value = 0

  // 文件类型验证
  const fileExtension = file.name.split('.').pop()?.toLowerCase()
  if (!fileExtension || !acceptFormats.includes(fileExtension)) {
    uploadError.value = `不支持的文件格式，请上传 ${acceptFormats.join('、')} 格式的视频`
    return false
  }

  // 文件大小验证
  const fileSizeMB = file.size / 1024 / 1024
  if (fileSizeMB > maxSize) {
    uploadError.value = `文件大小不能超过 ${maxSize}MB`
    return false
  }

  return true
}

// 文件选择处理 - 选择后自动上传
const handleFileChange = async (file: UploadFile) => {
  if (!file.raw) return

  currentFile.value = file.raw

  await startUpload()
}

let cancelUploadController = () => {}
// 开始上传
const startUpload = async () => {
  if (!currentFile.value) return

  try {
    uploading.value = true
    uploadError.value = ''
    uploadProgress.value = 0

    // 先提案获取视频的原信息 用本地blob
    const blob = URL.createObjectURL(currentFile.value)
    const metadataPromise = getVideoMetadata(blob)
    const { promise, cancel } = uploadFileApi(currentFile.value, {
      onProgress: (progress) => {
        uploadProgress.value = progress
      },
    })
    cancelUploadController = cancel
    // 并行等待
    const [data, metadata] = await Promise.all([promise, metadataPromise])

    // 根据你的 API 返回结构调整
    const videoData: VideoInfo = {
      url: data.filePath || '',
      // 暂时写死
      // url: 'https://soundasia.oss-cn-shenzhen.aliyuncs.com/OA/readName/mp4/2025/11/12/Common/1762918987602.mp4',
      name: currentFile.value.name,
      size: currentFile.value.size,
      duration: metadata.duration,
      resolution: metadata.resolution,
      poster: data.filePath || '',
      fileId: data.fileId || '',
    }

    videoInfo.value = videoData
    uploading.value = false

    // 设置url
    modelValue.value = videoData.url
    // 把 二进制源文件传出来
    emit('uploadSuccess', {
      file: currentFile.value,
      url: videoData.url,
      videoDuration: videoData.duration,
    })
    push.success('视频上传成功！')
  } catch (error) {
    uploading.value = false
    uploadError.value = error instanceof Error ? error.message : '上传失败，请重试'
    push.error(uploadError.value)
  }
}

// 取消上传
const cancelUpload = () => {
  cancelUploadController()
  uploading.value = false
  uploadProgress.value = 0
  push.info('已取消上传')
}

// 编辑回显：当 modelValue 有值（父组件赋值）时，通过 getVideoMetadata 拉取元信息并展示
async function syncVideoInfoFromModel() {
  const url = modelValue.value
  if (!url || uploading.value) return
  // 下面这种直接限制 新增视频 或者 编辑视频的二次上传
  if (videoInfo.value?.url === url) return

  let duration = '--'
  let resolution = '--'
  try {
    const metadata = await getVideoMetadata(url)
    duration = metadata.duration
    resolution = metadata.resolution
  } catch {
    // 跨域或加载失败时使用占位
  }
  if (modelValue.value !== url) return
  // 手动回显视频信息
  videoInfo.value = {
    url,
    name: '已上传视频',
    size: 0,
    duration,
    resolution,
  }
}
watch(() => modelValue.value, syncVideoInfoFromModel, { immediate: true })

// 重新选择视频
const replaceVideo = () => {
  videoInfo.value = null
  modelValue.value = ''
  uploadError.value = ''
  uploadProgress.value = 0
  currentFile.value = null
}

// 预览播放
const previewVideo = () => {
  window.open(videoInfo.value?.url, '_blank')
}

// 重试上传
const retryUpload = () => {
  uploadError.value = ''
  startUpload()
}

// reset
const reset = () => {
  uploadRef.value = null
  uploading.value = false
  uploadProgress.value = 0
  uploadError.value = ''
  currentFile.value = null
  videoInfo.value = null
  modelValue.value = ''
}
defineExpose({
  reset,
})
</script>

<style scoped>
.video-upload-container {
  width: 100%;
}

.upload-area {
  width: 100%;
}

.upload-area :deep(.el-upload) {
  width: 100%;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  transition: all 0.3s ease;
}

.upload-area :deep(.el-upload-dragger:hover) {
  border-color: #6366f1;
  background: linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
}

.upload-icon {
  font-size: 48px;
  color: #6366f1;
  margin-bottom: 16px;
}

.upload-text p {
  margin: 0;
  color: #374151;
  font-size: 16px;
}

.upload-hint {
  font-size: 14px !important;
  color: #6b7280 !important;
  margin-top: 8px !important;
}

.upload-progress {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.progress-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.progress-icon {
  font-size: 24px;
  color: #6366f1;
  margin-right: 12px;
}

.progress-details {
  flex: 1;
}

.file-name {
  margin: 0 0 4px 0;
  font-weight: 600;
  color: #111827;
  font-size: 14px;
}

.progress-text {
  margin: 0;
  color: #6b7280;
  font-size: 12px;
}

.progress-bar {
  margin-bottom: 12px;
}

.progress-bar :deep(.el-progress-bar__outer) {
  background-color: #e5e7eb;
  border-radius: 8px;
}

.progress-bar :deep(.el-progress-bar__inner) {
  background: linear-gradient(90deg, #6366f1 0%, #8b5cf6 100%);
  border-radius: 8px;
}

.cancel-btn {
  align-self: center;
}

.upload-success {
  padding: 20px;
  height: 100%;
  display: flex;
  align-items: center;
  gap: 16px;
}

.video-preview {
  position: relative;
  width: 120px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  /* background: #000; */
}

.video-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.video-preview:hover .video-overlay {
  opacity: 1;
}

.video-details {
  flex: 1;
}

.video-name {
  margin: 0 0 8px 0;
  font-weight: 600;
  color: #111827;
  font-size: 14px;
}

.video-meta {
  margin: 0;
  color: #6b7280;
  font-size: 12px;
}

.upload-error {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  margin-top: 12px;
  color: #dc2626;
  font-size: 14px;
}

.error-icon {
  color: #dc2626;
}

@media (max-width: 640px) {
  .upload-area :deep(.el-upload-dragger) {
    height: 160px;
  }

  .upload-placeholder {
    padding: 16px;
  }

  .upload-icon {
    font-size: 36px;
    margin-bottom: 12px;
  }

  .upload-text p {
    font-size: 14px;
  }

  .upload-hint {
    font-size: 12px !important;
  }

  .upload-success {
    flex-direction: column;
    text-align: center;
  }

  .video-preview {
    width: 160px;
    height: 90px;
  }
}

.upload-success-optimized {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  height: 100%;
  gap: 15px;
  justify-content: space-between;
}

.video-info-display {
  display: flex;
  align-items: center;
  gap: 15px;
}

.video-icon-wrapper {
  font-size: 48px;
  color: #6366f1;
}

.video-details-text {
  text-align: left;
}

.video-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
  word-break: break-all;
}

.video-meta {
  font-size: 13px;
  color: #909399;
}

.video-actions {
  display: flex;
  gap: 5px;
  margin-top: 10px;
  /* flex-direction: column; */
}
</style>
