<template>
  <div class="course-upload-container">
    <!-- 步骤指示器 -->
    <StepIndicator :current-step="currentStep" />

    <!-- 第一步：课程基本信息 -->
    <div v-if="isStep(1)" class="step-content">
      <CourseBasicInfo 
        :course-form="courseForm"
        :course-categories="courseCategories"
        :course-cover-file="courseCoverFile"
        :course-cover-preview-url="courseCoverPreviewUrl"
        :editor-options="editorOptions"
        @clear-course-cover="clearCourseCover"
        @handle-course-cover-select="handleCourseCoverSelect"
        @handle-content-update="handleContentUpdateWrapper"
      />

      <StepActions
        :current-step="currentStep"
        :show-prev-btn="false"
        :show-next-btn="true"
        :show-submit-btn="false"
        :next-btn-disabled="!canGoNextFromStep1"
        @next-step="handleNextStep"
        @reset-all="resetAll"
      />
    </div>

    <!-- 第二步：章节与视频 -->
    <div v-if="isStep(2)" class="step-content">
      <ChapterVideoManagement
        :chapters="chapters"
        :active-chapter-panels="activeChapterPanels"
        :is-chapter-expanded="isChapterExpanded"
        @add-chapter="handleAddChapter"
        @remove-chapter="removeChapter"
        @edit-chapter="handleEditChapter"
        @edit-chapter-title="handleEditChapterTitle"
        @add-video="addVideo"
        @edit-video="handleEditVideo"
        @remove-video="removeVideo"
        @expand-all-chapters="expandAllChapters"
        @collapse-all-chapters="collapseAllChapters"
        @toggle-chapter="toggleChapter"
        @update-active-chapter-panels="updateActiveChapterPanels"
        @trigger-video-cover-select="triggerVideoCoverSelect"
        @clear-video-cover="clearVideoCoverWrapper"
        @trigger-video-file-select="triggerVideoFileSelect"
        @handle-video-file-drop="handleVideoFileDropWrapper"
        @clear-video-file="clearVideoFileWrapper"
        @set-video-cover-input-ref="setVideoCoverInputRef"
        @set-video-file-input-ref="setVideoFileInputRef"
        @handle-video-cover-select="handleVideoCoverSelectWrapper"
        @handle-video-file-select="handleVideoFileSelectWrapper"
      />

      <StepActions
        :current-step="currentStep"
        :show-prev-btn="true"
        :show-next-btn="true"
        :show-submit-btn="false"
        :next-btn-disabled="!canGoNextFromStep2"
        @prev-step="prevStep"
        @next-step="handleNextStep"
        @reset-all="resetAll"
      />
    </div>

    <!-- 第三步：预览与提交 -->
    <div v-if="isStep(3)" class="step-content">
      <PreviewSubmit
        :course-form="courseForm"
        :chapters="chapters"
        :course-cover-preview-url="courseCoverPreviewUrl"
        :level-text="levelText"
        :total-videos="totalVideos"
        :format-file-size="formatFileSize"
        :is-uploading="isUploading"
        :upload-progress="uploadProgress"
        :upload-status="uploadStatus"
        :upload-result="uploadResult"
        :error-message="errorMessage"
        :current-upload-index="currentUploadIndex"
        :upload-total-count="uploadTotalCount"
        :get-progress-color="getProgressColor"
      />

      <StepActions
        :current-step="currentStep"
        :show-prev-btn="true"
        :show-next-btn="false"
        :show-submit-btn="true"
        :disabled="isUploading"
        :submit-btn-disabled="!canSubmit"
        @prev-step="prevStep"
        @reset-all="resetAll"
        @start-submit="handleSubmit"
      />
          </div>
        </div>
</template>

<script setup>
import { onMounted, onUnmounted, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'

// 子组件
import StepIndicator from './StepIndicator.vue'
import CourseBasicInfo from './CourseBasicInfo.vue'
import ChapterVideoManagement from './ChapterVideoManagement.vue'
import PreviewSubmit from './PreviewSubmit.vue'
import StepActions from './StepActions.vue'

// Composables
import { useSteps } from '@/composables/useSteps'
import { useCourseForm } from '@/composables/useCourseForm'
import { useChapters } from '@/composables/useChapters'
import { useFileUpload } from '@/composables/useFileUpload'
import { useVideoCodec } from '@/composables/useVideoCodec'
import { useRichTextEditor } from '@/composables/useRichTextEditor'
import { useSubmit } from '@/composables/useSubmit'

// 步骤控制
const { currentStep, nextStep, prevStep, resetStep, isStep } = useSteps()

// 课程基本信息
const { 
  courseForm, 
  courseCategories, 
  levelText, 
  canGoNextFromStep1, 
  loadCategories, 
  validateStep1, 
  resetForm 
} = useCourseForm()

// 章节管理
const {
  chapters,
  activeChapterPanels,
  totalVideos,
  uploadTotalCount,
  addChapter,
  removeChapter,
  addVideo,
  removeVideo,
  expandAllChapters,
  collapseAllChapters,
  isChapterExpanded,
  toggleChapter,
  clearAllChaptersAndVideos,
  resetChapters
} = useChapters()

// 文件上传
const {
  courseCoverFile,
  courseCoverPreviewUrl,
  videoFileInputs,
  videoCoverInputs,
  setVideoFileInputRef,
  setVideoCoverInputRef,
  triggerVideoFileSelect,
  triggerVideoCoverSelect,
  handleCourseCoverSelect,
  clearCourseCover,
  handleVideoCoverSelect,
  clearVideoCover,
  handleVideoFileSelect,
  handleVideoFileDrop,
  clearVideoFile,
  uploadImageToOss,
  formatFileSize
} = useFileUpload()

// 视频编码检测
const { checkVideoCodec } = useVideoCodec()

// 富文本编辑器
const { editorOptions, handleContentUpdate, processDescriptionImages } = useRichTextEditor()

// 提交相关
const {
  isUploading,
  uploadProgress,
  uploadStatus,
  uploadResult,
  errorMessage,
  currentUploadIndex,
  updateUserInfo,
  getProgressColor,
  clearUploadState,
  startSubmit
} = useSubmit()

// 组合计算属性
// 检查是否可以从第二步进入下一步
const canGoNextFromStep2 = computed(() => {
  if (!chapters.value || chapters.value.length === 0) {
    return false
  }

  // 检查每个章节是否完整
  for (const chapter of chapters.value) {
    if (!chapter.videos || chapter.videos.length === 0) {
      return false
    }

    // 检查每个视频是否完整
    for (const video of chapter.videos) {
      if (!video.title?.trim() || !video.file || !video.coverPreviewUrl) {
        return false
      }
    }
  }

  return true
})

const canSubmit = computed(() => {
  const hasTitle = !!courseForm.title.trim()
  const hasAnyFile = uploadTotalCount.value > 0
  return hasTitle && hasAnyFile && !isUploading.value
})

// 验证第二步（章节阶段）
const validateStep2 = () => {
  // 检查是否有章节
  if (!chapters.value || chapters.value.length === 0) {
    ElMessage.error('请至少创建一个章节')
    return false
  }

  // 检查每个章节是否有视频
  for (let i = 0; i < chapters.value.length; i++) {
    const chapter = chapters.value[i]
    
    if (!chapter.videos || chapter.videos.length === 0) {
      ElMessage.error(`第 ${i + 1} 章节还没有添加视频，请添加至少一个视频`)
      return false
    }

    // 检查每个视频是否有文件和封面
    for (let j = 0; j < chapter.videos.length; j++) {
      const video = chapter.videos[j]
      
      if (!video.title || !video.title.trim()) {
        ElMessage.error(`第 ${i + 1} 章节的第 ${j + 1} 个视频缺少标题`)
        return false
      }
      
      if (!video.file) {
        ElMessage.error(`第 ${i + 1} 章节的第 ${j + 1} 个视频还没有上传视频文件`)
        return false
      }
      
      if (!video.coverPreviewUrl) {
        ElMessage.error(`第 ${i + 1} 章节的第 ${j + 1} 个视频还没有上传封面图片`)
        return false
      }
    }
  }

  return true
}

// 处理步骤跳转
const handleNextStep = () => {
  if (currentStep.value === 1) {
    if (!validateStep1(courseCoverFile.value)) return
  } else if (currentStep.value === 2) {
    if (!validateStep2()) return
  }
  nextStep()
}

// 封装文件选择处理函数，传入依赖
const handleVideoFileSelectWrapper = async (cIndex, vIndex, event) => {
  await handleVideoFileSelect(cIndex, vIndex, event, chapters, checkVideoCodec)
}

const handleVideoFileDropWrapper = async (cIndex, vIndex, event) => {
  await handleVideoFileDrop(cIndex, vIndex, event, chapters, checkVideoCodec)
}

const handleVideoCoverSelectWrapper = (cIndex, vIndex, event) => {
  handleVideoCoverSelect(cIndex, vIndex, event, chapters)
}

const clearVideoCoverWrapper = (cIndex, vIndex) => {
  clearVideoCover(cIndex, vIndex, chapters)
}

const clearVideoFileWrapper = (cIndex, vIndex) => {
  clearVideoFile(cIndex, vIndex, chapters)
}

// 处理富文本内容更新
const handleContentUpdateWrapper = (content) => {
  handleContentUpdate(content, courseForm)
}

// 处理章节面板状态更新
const updateActiveChapterPanels = (value) => {
  activeChapterPanels.value = value
}

// 处理添加章节（带标题）
const handleAddChapter = (title) => {
  // 调用原有的addChapter方法
  addChapter()
  // 如果有标题，更新最新添加的章节标题
  if (title && chapters.value.length > 0) {
    const lastChapter = chapters.value[chapters.value.length - 1]
    lastChapter.title = title
  }
}

// 处理编辑章节
const handleEditChapter = (cIndex) => {
  // 这里可以添加编辑章节的逻辑，比如弹出编辑弹窗
  // 暂时只是一个占位符
  console.log('编辑章节', cIndex)
}

// 处理编辑章节标题
const handleEditChapterTitle = (cIndex, newTitle) => {
  if (cIndex >= 0 && cIndex < chapters.value.length && newTitle.trim()) {
    chapters.value[cIndex].title = newTitle.trim()
    console.log(`章节 ${cIndex + 1} 标题已更新为: ${newTitle}`)
  }
}

// 处理编辑视频
const handleEditVideo = (cIndex, vIndex, videoData) => {
  const chapter = chapters.value[cIndex]
  if (!chapter || !chapter.videos || vIndex < 0 || vIndex >= chapter.videos.length) return

  const video = chapter.videos[vIndex]
  // 更新视频数据
  video.title = videoData.title
  video.coverPreviewUrl = videoData.coverPreview
  video.file = videoData.videoFile.file
  video.previewUrl = videoData.previewUrl
  
  console.log(`视频 ${cIndex + 1}-${vIndex + 1} 已更新: ${videoData.title}`)
}

// 处理提交
const handleSubmit = async () => {
  await startSubmit(
    courseForm, 
    chapters, 
    courseCoverFile, 
    uploadImageToOss, 
    processDescriptionImages, 
    uploadTotalCount
  )
}

// 重置所有数据
const resetAll = () => {
  ElMessageBox.confirm(
    '确定要重置所有内容吗？这将清除所有已填写的信息和上传的文件。',
    '确认重置',
    {
      confirmButtonText: '确定重置',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  ).then(() => {
    // 重置各个模块
    resetForm()
    clearCourseCover()
    clearAllChaptersAndVideos()
    resetChapters()
    clearUploadState()
    resetStep()
    
    ElMessage.success('已重置所有内容')
  }).catch(() => {
    // 用户取消，不做任何操作
  })
}

// 生命周期
onMounted(async () => {
  await updateUserInfo()
  await loadCategories()
  if (typeof window.AliyunUpload === 'undefined') {
    console.warn('阿里云上传SDK未加载，请确保已引入相关脚本')
  }
})

onUnmounted(() => {
  clearUploadState()
  if (courseCoverPreviewUrl.value) {
    try { URL.revokeObjectURL(courseCoverPreviewUrl.value) } catch (e) {}
  }
})
</script>

<style scoped>
.course-upload-container {
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  box-sizing: border-box;
  width: 100%;
}

/* 内容过渡与基础布局 */
.step-content { 
  animation: fadeIn 0.3s ease-in-out; 
  padding: 20px; 
  box-sizing: border-box;
}

@keyframes fadeIn { 
  from { 
    opacity: 0; 
    transform: translateY(10px); 
  } 
  to { 
    opacity: 1; 
    transform: translateY(0); 
  } 
}

/* 响应式 */
@media (max-width: 768px) {
  .course-upload-container { 
  padding: 15px;
    margin: 10px; 
  }
}

@media (max-width: 480px) {
  .course-upload-container { 
    padding: 10px; 
    margin: 5px; 
  } 
}
</style>