import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getCurrentUser } from '@/api/user'
import { createUploadAuth, refreshUploadAuth } from '@/api/vod'
import { submitCourseCollectionReviewV2 } from '@/api/review'

/**
 * 提交审核相关逻辑
 */
export function useSubmit() {
  const router = useRouter()
  const userStore = useUserStore()
  
  // 上传状态
  const isUploading = ref(false)
  const uploadProgress = ref(0) // 总进度（0-100）
  const uploadStatus = ref('')
  const uploadResult = ref(null)
  const errorMessage = ref('')
  const currentUploadIndex = ref(0) // 从0开始
  
  // 获取用户ID
  const getUserId = () => {
    return userStore.getUserInfo?.id || ''
  }
  
  // 更新用户信息
  const updateUserInfo = async () => {
    try {
      const res = await getCurrentUser()
      if (res && res.code === 200) {
        userStore.updateUserInfo(res.data)
      }
    } catch (e) {
      console.warn('获取用户信息失败：', e)
    }
  }
  
  // 进度条颜色
  const getProgressColor = (progress) => {
    if (!progress || progress <= 0) return '#f56c6c'
    if (progress < 30) return '#f56c6c'
    if (progress < 70) return '#e6a23c'
    return '#67c23a'
  }
  
  // 清理上传状态
  const clearUploadState = () => {
    isUploading.value = false
    uploadProgress.value = 0
    uploadStatus.value = ''
    uploadResult.value = null
    errorMessage.value = ''
    currentUploadIndex.value = 0
  }
  
  // 创建并上传单个视频到VOD，返回videoId
  const uploadSingleVideoToVod = async (videoFile, meta, uploadTotalCount, uploadImageToOss) => {
    if (typeof window.AliyunUpload === 'undefined') {
      throw new Error('阿里云上传SDK未加载，请刷新页面重试')
    }
    if (typeof window.AliyunUpload.Vod !== 'function') {
      throw new Error('阿里云上传SDK初始化失败，请刷新页面重试')
    }
    
    return new Promise((resolve, reject) => {
      let uploader = null
      try {
        uploader = new window.AliyunUpload.Vod({
          userId: getUserId(),
          region: 'cn-shanghai',
          partSize: 1024 * 1024,
          parallel: 5,
          retryCount: 3,
          retryDuration: 2,
          onUploadstarted: async (uploadInfo) => {
            try {
              // 上传前准备封面（如果有）
              let coverUrl = ''
              if (meta.coverFile) {
                coverUrl = await uploadImageToOss(meta.coverFile)
              }
              const auth = await createUploadAuth({
                userId: getUserId(),
                title: meta.title || videoFile.name,
                description: meta.description || '',
                cateId: meta.cateId || '',
                coverUrl,
                isFree: meta.isFree,
                fileName: videoFile.name,
                fileSize: videoFile.size
              })
              const { uploadAuth, uploadAddress, videoId } = auth || {}
              if (!uploadAuth || !uploadAddress || !videoId) {
                throw new Error('上传凭证缺少必要字段')
              }
              uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
              uploadStatus.value = '开始上传文件...'
            } catch (e) {
              reject(e)
            }
          },
          onUploadProgress: (uploadInfo, totalSize, progress) => {
            // progress: 0-1
            const perFilePercent = Math.max(0, Math.min(100, Math.round((progress || 0) * 100)))
            const total = uploadTotalCount.value || 1
            const base = (currentUploadIndex.value / total) * 100
            uploadProgress.value = Math.min(100, Math.round(base + perFilePercent / total))
            uploadStatus.value = `正在上传：${videoFile.name}（${perFilePercent}%）`
          },
          onUploadSucceed: (uploadInfo) => {
            uploadStatus.value = `文件上传完成：${videoFile.name}`
            resolve(uploadInfo.videoId)
          },
          onUploadFailed: (uploadInfo, code, message) => {
            reject(new Error(message || '上传失败'))
          },
          onUploadTokenExpired: async (uploadInfo) => {
            try {
              const refreshed = await refreshUploadAuth({ videoId: uploadInfo.videoId })
              const { uploadAuth } = refreshed || {}
              if (!uploadAuth) throw new Error('刷新上传凭证失败')
              uploader.resumeUploadWithAuth(uploadAuth)
            } catch (e) {
              reject(e)
            }
          },
          onUploadCanceled: () => {
            reject(new Error('上传已取消'))
          }
        })
        uploader.addFile(videoFile, null, null, null, null)
        uploader.startUpload()
      } catch (e) {
        reject(e)
      }
    })
  }
  
  // 主提交函数
  const startSubmit = async (courseForm, chapters, courseCoverFile, uploadImageToOss, processDescriptionImages, uploadTotalCount) => {
    if (isUploading.value) return
    
    clearUploadState()
    isUploading.value = true
    uploadStatus.value = '准备上传...'
    
    try {
      // 课程封面上传（可选，v2需要传入courseCoverUrl）
      let courseCoverUrl = ''
      if (courseCoverFile.value) {
        try { 
          courseCoverUrl = await uploadImageToOss(courseCoverFile.value) 
        } catch (_) { 
          courseCoverUrl = '' 
        }
      }
      
      // 处理富文本中的base64图片，上传到OSS并替换链接
      uploadStatus.value = '正在处理富文本中的图片...'
      const processedDescription = await processDescriptionImages(courseForm.description, uploadImageToOss)
      courseForm.description = processedDescription
      
      // 扁平化视频列表，按章节顺序逐个上传
      const flatVideos = []
      chapters.value.forEach((ch, cIndex) => {
        ch.videos?.forEach((v, vIndex) => {
          if (v.file) flatVideos.push({ cIndex, vIndex, video: v, chapter: ch })
        })
      })
      
      const uploadedItems = [] // { cIndex, vIndex, videoId, coverUrl, title }
      const total = flatVideos.length || 1
      
      for (let i = 0; i < flatVideos.length; i++) {
        currentUploadIndex.value = i
        const { cIndex, vIndex, video } = flatVideos[i]
        // 构造元信息
        const meta = {
          title: video.title || courseForm.title,
          description: courseForm.description || '',
          cateId: courseForm.cateId || '',
          isFree: courseForm.isFree,
          coverFile: video.coverFile || null
        }
        const videoId = await uploadSingleVideoToVod(video.file, meta, uploadTotalCount, uploadImageToOss)
        let videoCoverUrl = ''
        if (video.coverFile) {
          // 已在onUploadstarted上传；这里为保险再次保证有值
          try { 
            videoCoverUrl = await uploadImageToOss(video.coverFile) 
          } catch (e) {}
        }
        uploadedItems.push({ cIndex, vIndex, videoId, coverUrl: videoCoverUrl, title: meta.title })
        // 更新整体进度（当前文件完成）
        uploadProgress.value = Math.min(100, Math.round(((i + 1) / total) * 100))
      }
      
      uploadStatus.value = '视频上传完成，正在提交审核...'
      
      // 组装chapters数据（v2 嵌套结构）
      const chapterPayload = chapters.value.map((ch, cIndex) => {
        const itemsOfChapter = uploadedItems.filter(it => it.cIndex === cIndex)
        return {
          chapterTitle: ch.title || courseForm.title,
          chapterDescription: courseForm.description || '',
          orderNum: cIndex + 1,
          videos: itemsOfChapter.map(it => ({
            videoId: it.videoId,
            videoTitle: ch.videos[it.vIndex]?.title || courseForm.title,
            videoDescription: courseForm.description || '',
            videoCoverUrl: it.coverUrl || '',
            videoCategory: courseForm.cateId || '',
            videoDuration: 0,
            orderNum: (it.vIndex || 0) + 1
          }))
        }
      })
      
      const reviewData = {
        courseCollectionId: `course-collection-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
        courseTitle: courseForm.title,
        courseDescription: courseForm.description || '',
        courseCategory: courseForm.cateId,
        courseCoverUrl,
        courseIsFree: courseForm.isFree ? 0 : 1,
        courseLevel: courseForm.courseLevel,
        chapters: chapterPayload
      }
      
      const reviewResult = await submitCourseCollectionReviewV2(reviewData)
      if (reviewResult && (reviewResult.courseCollectionId || reviewResult.courseId)) {
        uploadResult.value = reviewResult
        ElMessage.success('课程集合提交审核成功')
        uploadStatus.value = '完成'
        
        // 提交成功后跳转到作品管理页面
        setTimeout(() => {
          router.push('/personal-center/publish?tab=manage')
        }, 2000) // 延迟2秒跳转，让用户看到成功消息
      } else {
        throw new Error(reviewResult?.message || '提交审核失败')
      }
    } catch (e) {
      console.error('提交失败：', e)
      errorMessage.value = e.message || '提交失败，请重试'
      ElMessage.error(errorMessage.value)
    } finally {
      isUploading.value = false
    }
  }
  
  return {
    isUploading,
    uploadProgress,
    uploadStatus,
    uploadResult,
    errorMessage,
    currentUploadIndex,
    updateUserInfo,
    getProgressColor,
    clearUploadState,
    startSubmit
  }
}
