import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { getPostSignature } from '@/api/files'

/**
 * 文件上传相关功能
 */
export function useFileUpload() {
  const userStore = useUserStore()
  
  // 课程封面相关
  const courseCoverFile = ref(null)
  const courseCoverPreviewUrl = ref('')
  
  // 每个视频的文件与封面input引用集合
  const videoFileInputs = ref({})
  const videoCoverInputs = ref({})
  
  // 获取用户ID
  const getUserId = () => {
    return userStore.getUserInfo?.id || ''
  }
  
  // 设置引用
  const setVideoFileInputRef = (cIndex, vIndex, el) => {
    const key = `${cIndex}-${vIndex}`
    if (el) videoFileInputs.value[key] = el
  }
  
  const setVideoCoverInputRef = (cIndex, vIndex, el) => {
    const key = `${cIndex}-${vIndex}`
    if (el) videoCoverInputs.value[key] = el
  }
  
  // 触发文件选择
  const triggerVideoFileSelect = (cIndex, vIndex) => {
    const key = `${cIndex}-${vIndex}`
    videoFileInputs.value[key]?.click()
  }
  
  const triggerVideoCoverSelect = (cIndex, vIndex) => {
    const key = `${cIndex}-${vIndex}`
    videoCoverInputs.value[key]?.click()
  }
  
  // 课程封面处理
  const handleCourseCoverSelect = (event) => {
    const file = event.target.files && event.target.files[0]
    if (!file) return
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择有效的图片文件')
      return
    }
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片文件大小不能超过5MB')
      return
    }
    courseCoverFile.value = file
    courseCoverPreviewUrl.value = URL.createObjectURL(file)
  }
  
  const clearCourseCover = () => {
    courseCoverFile.value = null
    if (courseCoverPreviewUrl.value) {
      URL.revokeObjectURL(courseCoverPreviewUrl.value)
      courseCoverPreviewUrl.value = ''
    }
  }
  
  // 视频封面处理
  const handleVideoCoverSelect = (cIndex, vIndex, event, chapters) => {
    const file = event.target.files && event.target.files[0]
    if (!file) return
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择有效的图片文件')
      return
    }
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片文件大小不能超过5MB')
      return
    }
    const chapter = chapters.value[cIndex]
    const video = chapter?.videos?.[vIndex]
    if (!video) return
    if (video.coverPreviewUrl) {
      try { URL.revokeObjectURL(video.coverPreviewUrl) } catch (e) {}
    }
    video.coverFile = file
    video.coverPreviewUrl = URL.createObjectURL(file)
  }
  
  const clearVideoCover = (cIndex, vIndex, chapters) => {
    const chapter = chapters.value[cIndex]
    const video = chapter?.videos?.[vIndex]
    if (!video) return
    if (video.coverPreviewUrl) {
      try { URL.revokeObjectURL(video.coverPreviewUrl) } catch (e) {}
    }
    video.coverFile = null
    video.coverPreviewUrl = ''
    const key = `${cIndex}-${vIndex}`
    const input = videoCoverInputs.value[key]
    if (input) input.value = ''
  }
  
  // 视频文件处理
  const handleVideoFileSelect = async (cIndex, vIndex, event, chapters, checkVideoCodec) => {
    const file = event.target.files && event.target.files[0]
    if (!file) return
    if (!file.type.startsWith('video/')) {
      ElMessage.error('请选择有效的视频文件')
      return
    }
    if (file.size > 1.5 * 1024 * 1024 * 1024) {
      ElMessage.error('视频文件大小不能超过1.5GB')
      return
    }
    
    // 检测视频编码
    const isH264 = await checkVideoCodec(file)
    if (!isH264) {
      ElMessage.error('当前视频文件编码不是H.264，在部分浏览器上可能出现黑屏问题。请重新导出视频并设置编码为H.264。')
      return
    }
    
    const chapter = chapters.value[cIndex]
    const video = chapter?.videos?.[vIndex]
    if (!video) return
    video.file = file
    // 生成预览URL
    try { if (video.previewUrl) URL.revokeObjectURL(video.previewUrl) } catch (_) {}
    video.previewUrl = URL.createObjectURL(file)
  }
  
  // 支持拖拽选择视频文件
  const handleVideoFileDrop = async (cIndex, vIndex, event, chapters, checkVideoCodec) => {
    const file = event.dataTransfer?.files?.[0]
    if (!file) return
    if (!file.type.startsWith('video/')) {
      ElMessage.error('请选择有效的视频文件')
      return
    }
    if (file.size > 1.5 * 1024 * 1024 * 1024) {
      ElMessage.error('视频文件大小不能超过1.5GB')
      return
    }
    
    // 检测视频编码
    const isH264 = await checkVideoCodec(file)
    if (!isH264) {
      ElMessage.error('当前视频文件编码不是H.264，在部分浏览器上可能出现黑屏问题。请重新导出视频并设置编码为H.264。')
      return
    }
    
    const chapter = chapters.value[cIndex]
    const video = chapter?.videos?.[vIndex]
    if (!video) return
    video.file = file
    // 生成预览URL  
    try { if (video.previewUrl) URL.revokeObjectURL(video.previewUrl) } catch (_) {}
    video.previewUrl = URL.createObjectURL(file)
  }
  
  const clearVideoFile = (cIndex, vIndex, chapters) => {
    const chapter = chapters.value[cIndex]
    const video = chapter?.videos?.[vIndex]
    if (!video) return
    if (video.previewUrl) {
      try { URL.revokeObjectURL(video.previewUrl) } catch (_) {}
    }
    video.file = null
    video.previewUrl = ''
    const key = `${cIndex}-${vIndex}`
    const input = videoFileInputs.value[key]
    if (input) input.value = ''
  }
  
  // 上传图片到COS
  const uploadImageToOss = async (file) => {
    try {
      const postSignatureResult = await getPostSignature({
        fileName: file.name,
        userId: getUserId()
      })
      if (postSignatureResult.code !== 200) {
        throw new Error(postSignatureResult.message || '获取上传签名失败')
      }
      const signatureData = postSignatureResult.data
      
      const formData = new FormData()
      const fileKey = signatureData.dir + Date.now() + '_' + file.name
      
      // COS POST 表单上传必需字段
      formData.append('key', fileKey)
      formData.append('policy', signatureData.policy)
      formData.append('q-sign-algorithm', signatureData['q-sign-algorithm'])
      formData.append('q-ak', signatureData['q-ak'])
      formData.append('q-key-time', signatureData['q-key-time'])
      formData.append('q-signature', signatureData['q-signature'])
      formData.append('file', file)
      
      const uploadResponse = await fetch(signatureData.host, { method: 'POST', body: formData })
      if (!uploadResponse.ok) {
        const errorText = await uploadResponse.text()
        throw new Error(`封面上传失败: HTTP ${uploadResponse.status} - ${errorText}`)
      }
      // 使用后端返回的host构建文件URL
      const fileUrl = `${signatureData.host}/${fileKey}`
      return fileUrl
    } catch (error) {
      console.error('COS 封面上传失败:', error)
      throw error
    }
  }
  
  // 工具函数
  const formatFileSize = (bytes) => {
    if (!bytes || bytes <= 0 || isNaN(bytes) || !isFinite(bytes)) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    if (i < 0 || i >= sizes.length) return '0 B'
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }
  
  return {
    courseCoverFile,
    courseCoverPreviewUrl,
    videoFileInputs,
    videoCoverInputs,
    setVideoFileInputRef,
    setVideoCoverInputRef,
    triggerVideoFileSelect,
    triggerVideoCoverSelect,
    handleCourseCoverSelect,
    clearCourseCover,
    handleVideoCoverSelect,
    clearVideoCover,
    handleVideoFileSelect,
    handleVideoFileDrop,
    clearVideoFile,
    uploadImageToOss,
    formatFileSize
  }
}
