<template>
  <div class="course-add">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button @click="handleCancel" :icon="ArrowLeft">返回</el-button>
      <h2 class="page-title">{{ props.courseID ? '编辑课程' : '新增课程' }}</h2>
    </div>

    <el-form
      ref="formRef"
      :model="currentCourseItemVO"
      :rules="rules"
      label-width="120px"
    >
      <!-- 基本信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <span class="card-header">基本信息</span>
        </template>
        
        <el-form-item label="课程名称" prop="name">
          <el-input 
            id="course-name"
            v-model="currentCourseItemVO.name" 
            placeholder="请输入课程名称"
            :disabled="!editMode"
          />
        </el-form-item>

        <!-- 课程封面 - 移除 label 关联 -->
        <el-form-item prop="coverImage">
          <template #label>
            <span>课程封面</span>
          </template>
          <FileUpload
            v-if="editMode"
            :as-dialog="false"
            list-type="cover"
            v-model:cover-url="currentCourseItemVO.coverImage"
            accept="image/*"
            :max-size="2"
            module="course"
            tip="建议尺寸 800x600"
            @success="handleCoverUploadSuccess"
            @remove="handleCoverRemove"
          />
          <div v-else class="cover-preview">
            <img v-if="currentCourseItemVO.coverImage" :src="FILE_DOWNLOAD_URL + currentCourseItemVO.coverImage" alt="课程封面" />
            <span v-else class="no-cover">暂无封面</span>
          </div>
        </el-form-item>

        <el-form-item label="授课老师" prop="teacher">
          <div style="display: flex; gap: 8px; align-items: flex-start;">
            <el-select
              id="course-teacher"
              v-model="currentCourseItemVO.teacher"
              filterable
              placeholder="选择授课老师"
              :loading="teachersLoading"
              :disabled="!editMode"
              clearable
              style="flex: 1"
              @focus="handleTeacherSelectFocus"
            >
              <el-option
                v-for="user in teacherList"
                :key="user.id"
                :label="user.username || user.fullName || user.id"
                :value="user.username || user.fullName || user.id"
              >
                <span>{{ user.username }}</span>
                <span v-if="user.fullName" style="color: #8492a6; font-size: 12px; margin-left: 8px;">
                  ({{ user.fullName }})
                </span>
              </el-option>
            </el-select>
            <el-tooltip content="刷新教师列表" placement="top">
              <el-button 
                :icon="Refresh" 
                @click="loadTeacherList"
                :loading="teachersLoading"
                :disabled="!editMode"
              />
            </el-tooltip>
          </div>
        </el-form-item>

        <el-form-item label="课程时长" prop="duration">
          <el-input-number
            id="course-duration"
            v-model="currentCourseItemVO.duration"
            :min="0"
            placeholder="分钟"
            :disabled="!editMode"
          />
          <span class="ml-2">分钟</span>
        </el-form-item>

        <el-form-item label="课程描述" prop="description">
          <el-input
            id="course-description"
            v-model="currentCourseItemVO.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
            :disabled="!editMode"
          />
        </el-form-item>

        <el-form-item label="排序号" prop="orderNum">
          <el-input-number 
            id="course-orderNum"
            v-model="currentCourseItemVO.orderNum" 
            :min="0"
            :disabled="!editMode"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group 
            id="course-status"
            v-model="currentCourseItemVO.status"
            disabled
          >
            <el-radio :label="0">未上线</el-radio>
            <el-radio :label="1">已上线</el-radio>
            <el-radio :label="2">已下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>

      <!-- 章节管理 -->
      <el-card class="chapter-card" shadow="never">
        <template #header>
          <div class="card-header-flex">
            <span class="card-header">章节管理</span>
            <el-button v-if="editMode" type="primary" size="small" @click="addChapter">
              <el-icon><Plus /></el-icon>
              添加章节
            </el-button>
          </div>
        </template>

        <div v-if="!currentCourseItemVO.chapters || currentCourseItemVO.chapters.length === 0" class="empty-tip">
          暂无章节，请点击"添加章节"按钮添加
        </div>

        <el-collapse v-model="activeChapters">
          <el-collapse-item
            v-for="(chapterVO, chapterIndex) in currentCourseItemVO.chapters"
            :key="chapterIndex"
            :name="chapterIndex"
          >
            <template #title>
              <div class="chapter-title">
                <span>章节 {{ chapterIndex + 1 }}: {{ chapterVO.name || '未命名章节' }}</span>
                <div v-if="editMode" class="chapter-actions" @click.stop>
                  <el-button
                    type="danger"
                    size="small"
                    link
                    @click="removeChapter(chapterIndex)"
                  >
                    删除章节
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 章节信息 -->
            <el-form-item 
              :label="`章节${chapterIndex + 1}名称`" 
              :prop="`chapters.${chapterIndex}.name`"
              :rules="[{ required: true, message: '请输入章节名称', trigger: 'blur' }]"
            >
              <el-input 
                :id="`chapter-${chapterIndex}-name`"
                v-model="chapterVO.name" 
                placeholder="请输入章节名称"
                :disabled="!editMode"
              />
            </el-form-item>

            <el-form-item 
              :label="`章节${chapterIndex + 1}排序`" 
              :prop="`chapters.${chapterIndex}.orderNum`"
            >
              <el-input-number 
                :id="`chapter-${chapterIndex}-orderNum`"
                v-model="chapterVO.orderNum" 
                :min="0"
                :disabled="!editMode"
              />
            </el-form-item>

            <!-- 学习节点 -->
            <div class="nodes-section">
              <div class="nodes-header">
                <span class="nodes-title">学习节点</span>
                <el-button v-if="editMode" type="primary" size="small" @click="addNode(chapterIndex)">
                  <el-icon><Plus /></el-icon>
                  添加节点
                </el-button>
              </div>

              <div v-if="!chapterVO.chapters || chapterVO.chapters.length === 0" class="empty-tip">
                暂无学习节点
              </div>

              <div v-else class="nodes-list">
                <el-card
                  v-for="(node, nodeIndex) in chapterVO.chapters"
                  :key="nodeIndex"
                  class="node-card"
                  shadow="hover"
                >
                  <template #header>
                    <div class="node-header">
                      <span>节点 {{ nodeIndex + 1 }}: {{ node.name || '未命名节点' }}</span>
                      <el-button
                        v-if="editMode"
                        type="danger"
                        size="small"
                        link
                        @click="removeNode(chapterIndex, nodeIndex)"
                      >
                        删除
                      </el-button>
                    </div>
                  </template>

                  <el-form-item 
                    label="节点名称"
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.name`"
                  >
                    <el-input 
                      :id="`node-${chapterIndex}-${nodeIndex}-name`"
                      v-model="node.name" 
                      placeholder="请输入节点名称"
                      :disabled="!editMode"
                    />
                  </el-form-item>

                  <el-form-item 
                    label="节点类型"
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.nodeType`"
                  >
                    <el-radio-group 
                      :id="`node-${chapterIndex}-${nodeIndex}-nodeType`"
                      v-model="node.nodeType"
                      :disabled="!editMode"
                      @change="handleNodeTypeChange(chapterIndex, nodeIndex)"
                    >
                      <el-radio :label="0">文章资源</el-radio>
                      <el-radio :label="1">富文本</el-radio>
                      <el-radio :label="2">上传文件</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 文章资源选择 -->
                  <el-form-item 
                    v-if="node.nodeType === 0" 
                    label="选择文章"
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.resourceID`"
                  >
                    <div style="display: flex; gap: 8px; align-items: flex-start;">
                      <el-select
                        :id="`node-${chapterIndex}-${nodeIndex}-resourceID`"
                        v-model="node.resourceID"
                        filterable
                        placeholder="选择文章（可输入标题搜索）"
                        :loading="getNodeLoading(chapterIndex, nodeIndex)"
                        :disabled="!editMode"
                        clearable
                        style="flex: 1"
                        @focus="handleSelectFocus(chapterIndex, nodeIndex)"
                      >
                        <el-option
                          v-for="article in getNodeArticleOptions(chapterIndex, nodeIndex)"
                          :key="article.resourceID"
                          :label="article.title"
                          :value="article.resourceID"
                        />
                      </el-select>
                      <el-tooltip content="加载更多文章" placement="top">
                        <el-button 
                          :icon="Refresh" 
                          @click="loadArticlesForNode(chapterIndex, nodeIndex)"
                          :loading="getNodeLoading(chapterIndex, nodeIndex)"
                          :disabled="!editMode"
                        />
                      </el-tooltip>
                    </div>
                  </el-form-item>

                  <!-- 富文本编辑 - 移除 label 关联 -->
                  <el-form-item 
                    v-if="node.nodeType === 1" 
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.content`"
                  >
                    <template #label>
                      <span>内容编辑</span>
                    </template>
                    <RichTextComponent v-model="node.content" :disabled="!editMode" />
                  </el-form-item>

                  <!-- 文件上传 - 移除 label 关联 -->
                  <el-form-item 
                    v-if="node.nodeType === 2" 
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.videoUrl`"
                  >
                    <template #label>
                      <span>上传文件</span>
                    </template>
                    <FileUpload
                      v-if="editMode"
                      :as-dialog="false"
                      :multiple="false"
                      module="course-node"
                      :max-size="100"
                      tip="支持上传视频、音频、文档等文件，单个文件不超过100MB"
                      @success="(files) => handleNodeFileUploadSuccess(files, chapterIndex, nodeIndex)"
                    />
                    <div v-if="node.videoUrl" class="file-info-display">
                      <span>已上传文件: {{ node.videoUrl }}</span>
                      <el-button v-if="editMode" type="text" @click="node.videoUrl = ''">删除</el-button>
                    </div>
                    <div v-else-if="!editMode" class="file-info-display">
                      <span class="no-file">暂无文件</span>
                    </div>
                  </el-form-item>

                  <el-form-item 
                    label="节点时长"
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.duration`"
                  >
                    <el-input-number 
                      :id="`node-${chapterIndex}-${nodeIndex}-duration`"
                      v-model="node.duration" 
                      :min="0"
                      :disabled="!editMode"
                    />
                    <span class="ml-2">分钟</span>
                  </el-form-item>

                  <!-- 是否必修 - 使用 template #label -->
                  <el-form-item 
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.isRequired`"
                  >
                    <template #label>
                      <span>是否必修</span>
                    </template>
                    <el-switch
                      :id="`node-${chapterIndex}-${nodeIndex}-isRequired`"
                      v-model="node.isRequired"
                      :active-value="1"
                      :inactive-value="0"
                      :disabled="!editMode"
                    />
                  </el-form-item>

                  <el-form-item 
                    label="排序号"
                    :prop="`chapters.${chapterIndex}.chapters.${nodeIndex}.orderNum`"
                  >
                    <el-input-number 
                      :id="`node-${chapterIndex}-${nodeIndex}-orderNum`"
                      v-model="node.orderNum" 
                      :min="0"
                      :disabled="!editMode"
                    />
                  </el-form-item>
                </el-card>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-card>

      <!-- 操作按钮 -->
      <el-form-item class="action-buttons">
        <el-button v-if="editMode" type="primary" @click="handleSubmit" :loading="submitting">
          {{ courseID ? '更新课程' : '创建课程' }}
        </el-button>
        <el-button v-if="editMode" @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, ArrowLeft, Refresh } from '@element-plus/icons-vue';
import { FileUpload } from '@/components/file';
import { RichTextComponent } from '@/components/text';
import { courseApi } from '@/apis/study';
import { resourceApi } from '@/apis/resource';
import { userApi } from '@/apis/system';
import type { CourseItemVO } from '@/types/study';
import type { Resource } from '@/types/resource';
import type { SysFile, UserVO } from '@/types';
import { FILE_DOWNLOAD_URL } from '@/config';
defineOptions({
  name: 'CourseAdd'
});

interface Props {
  courseID?: string;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  success: [];
  cancel: [];
}>();

// 定义节点扩展类型（用于添加运行时属性）
type NodeWithExtras = CourseItemVO & { loading?: boolean; articleOptions?: Resource[] };

const formRef = ref();
const submitting = ref(false);
const activeChapters = ref<number[]>([]);
const editMode = ref(true);

// 教师列表
const teacherList = ref<UserVO[]>([]);
const teachersLoading = ref(false);

// 原始数据（用于比对）
const originalCourseItemVO = ref<CourseItemVO>();
// 当前编辑的数据
const currentCourseItemVO = ref<CourseItemVO>({
  name: '',
  coverImage: '',
  description: '',
  teacher: '',
  duration: 0,
  status: 0,
  orderNum: 0,
  chapters: []
});

// 表单验证规则
const rules = {
  'name': [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  'teacher': [{ required: true, message: '请输入授课老师', trigger: 'blur' }]
};

onMounted(() => {
  // 加载教师列表
  loadTeacherList();
  
  if (props.courseID) {
    loadCourse();
  }
});

// 加载课程数据
async function loadCourse() {
  try {
    const res = await courseApi.getCourseById(props.courseID!);
    if (res.success && res.data) {
      // 确保数据结构完整，处理 null 值
      const courseData = res.data;
      
      // 确保 chapters 是数组（章节列表）
      if (!courseData.chapters) {
        courseData.chapters = [];
      }
      
      // 确保每个章节的 chapters 是数组（节点列表），并初始化扩展属性
      courseData.chapters.forEach((chapterVO: CourseItemVO) => {
        if (!chapterVO.chapters) {
          chapterVO.chapters = [];
        }
        
        // 为每个节点添加扩展属性
        chapterVO.chapters.forEach((node: CourseItemVO) => {
          const nodeWithExtras = node as NodeWithExtras;
          nodeWithExtras.loading = false;
          nodeWithExtras.articleOptions = [];
        });
      });
      
      if (courseData.status === 1) {
        editMode.value = false;
      }
      // 保存原始数据
      originalCourseItemVO.value = JSON.parse(JSON.stringify(courseData));
      // 设置当前编辑数据
      currentCourseItemVO.value = JSON.parse(JSON.stringify(courseData));
      console.log(currentCourseItemVO.value);
      
      // 加载所有文章资源节点的文章列表
      await loadArticlesForAllNodes();
    }
  } catch (error) {
    console.error('加载课程失败:', error);
    ElMessage.error('加载课程失败');
  }
}

// 为所有文章资源类型的节点加载文章列表
async function loadArticlesForAllNodes() {
  if (!currentCourseItemVO.value.chapters) return;
  
  for (let chapterIndex = 0; chapterIndex < currentCourseItemVO.value.chapters.length; chapterIndex++) {
    const chapter = currentCourseItemVO.value.chapters[chapterIndex];
    if (!chapter.chapters) continue;
    
    for (let nodeIndex = 0; nodeIndex < chapter.chapters.length; nodeIndex++) {
      const node = chapter.chapters[nodeIndex] as NodeWithExtras;
      // 只为文章资源类型的节点加载文章列表
      if (node.nodeType === 0) {
        await loadArticlesForNode(chapterIndex, nodeIndex);
      }
    }
  }
}

// 添加章节
function addChapter() {
  const newChapterVO: CourseItemVO = {
    chapterID: currentCourseItemVO.value.courseID,
    name: '',
    orderNum: currentCourseItemVO.value.chapters!.length,
    chapters: []
  };
  currentCourseItemVO.value.chapters!.push(newChapterVO);
  activeChapters.value.push(currentCourseItemVO.value.chapters!.length - 1);
}

// 删除章节
function removeChapter(index: number) {
  currentCourseItemVO.value.chapters!.splice(index, 1);
  // 更新激活的章节索引
  activeChapters.value = activeChapters.value
    .filter(i => i !== index)
    .map(i => i > index ? i - 1 : i);
}

// 添加节点
function addNode(chapterIndex: number) {
  const nodeIndex = currentCourseItemVO.value.chapters![chapterIndex].chapters!.length;
  const newNode: NodeWithExtras = {
    nodeID: '',
    chapterID: currentCourseItemVO.value.chapters![chapterIndex].chapterID,
    name: '',
    nodeType: 0,
    content: '',
    duration: 0,
    isRequired: 1,
    orderNum: nodeIndex,
    loading: false,
    articleOptions: []
  };
  currentCourseItemVO.value.chapters![chapterIndex].chapters!.push(newNode);
  
  // 默认是文章资源类型，立即加载文章列表
  loadArticlesForNode(chapterIndex, nodeIndex);
}

// 删除节点
function removeNode(chapterIndex: number, nodeIndex: number) {
  currentCourseItemVO.value.chapters![chapterIndex].chapters!.splice(nodeIndex, 1);
}

// 处理节点类型变化
function handleNodeTypeChange(chapterIndex: number, nodeIndex: number) {
  const node = currentCourseItemVO.value.chapters![chapterIndex].chapters![nodeIndex] as NodeWithExtras;
  
  // 如果切换为文章资源类型，加载文章列表
  if (node.nodeType === 0) {
    loadArticlesForNode(chapterIndex, nodeIndex);
  }
}

// 为节点加载文章列表
async function loadArticlesForNode(chapterIndex: number, nodeIndex: number) {
  const node = currentCourseItemVO.value.chapters![chapterIndex].chapters![nodeIndex] as NodeWithExtras;
  
  node.loading = true;
  try {
    const res = await resourceApi.getResourcePage({
      pageNumber: 1,
      pageSize: 100 // 加载前100条文章供选择
    });
    if (res.success && res.dataList) {
      node.articleOptions = res.dataList;
      console.log(`✅ 已为节点加载 ${res.dataList.length} 篇文章`);
    }
  } catch (error) {
    console.error('加载文章列表失败:', error);
    ElMessage.error('加载文章列表失败');
  } finally {
    node.loading = false;
  }
}

// 辅助函数：获取节点的 loading 状态
function getNodeLoading(chapterIndex: number, nodeIndex: number) {
  const node = currentCourseItemVO.value.chapters![chapterIndex].chapters![nodeIndex] as NodeWithExtras;
  return node.loading || false;
}

// 辅助函数：获取节点的 articleOptions
function getNodeArticleOptions(chapterIndex: number, nodeIndex: number) {
  const node = currentCourseItemVO.value.chapters![chapterIndex].chapters![nodeIndex] as NodeWithExtras;
  return node.articleOptions || [];
}

// 处理下拉框获得焦点事件
function handleSelectFocus(chapterIndex: number, nodeIndex: number) {
  const node = currentCourseItemVO.value.chapters![chapterIndex].chapters![nodeIndex] as NodeWithExtras;
  
  // 如果还没有加载文章列表，则加载
  if (!node.articleOptions || node.articleOptions.length === 0) {
    loadArticlesForNode(chapterIndex, nodeIndex);
  }
}

// 加载教师列表
async function loadTeacherList() {
  teachersLoading.value = true;
  try {
    const res = await userApi.getUserPage({
      pageNumber: 1,
      pageSize: 100
    });
    if (res.success && res.dataList) {
      teacherList.value = res.dataList;
      console.log(`✅ 已加载 ${res.dataList.length} 位教师`);
    }
  } catch (error) {
    console.error('加载教师列表失败:', error);
    ElMessage.error('加载教师列表失败');
  } finally {
    teachersLoading.value = false;
  }
}

// 处理教师选择框获得焦点
function handleTeacherSelectFocus() {
  // 如果还没有加载教师列表，则加载
  if (teacherList.value.length === 0) {
    loadTeacherList();
  }
}

// 处理封面上传成功
function handleCoverUploadSuccess(files: SysFile[]) {
  if (files && files.length > 0) {
    // coverUrl已经通过v-model:cover-url自动更新了
    // 这里可以做一些额外的处理，比如记录fileID
    console.log('封面上传成功:', files[0]);
  }
}

// 处理封面删除
function handleCoverRemove() {
  currentCourseItemVO.value.coverImage = '';
}

// 处理节点文件上传成功
function handleNodeFileUploadSuccess(files: SysFile[], chapterIndex: number, nodeIndex: number) {
  if (files && files.length > 0) {
    currentCourseItemVO.value.chapters![chapterIndex].chapters![nodeIndex].videoUrl = files[0].filePath || '';
  }
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate();
    
    submitting.value = true;
    
    // 先创建/更新课程
    let courseID = props.courseID;
    if (courseID) {
      const res = await courseApi.updateCourse(currentCourseItemVO.value);
      if (!res.success) {
        throw new Error('更新课程失败');
      }
    } else {
      const res = await courseApi.createCourse(currentCourseItemVO.value);
      if (!res.success || !res.data?.courseID) {
        throw new Error('创建课程失败');
      }
      courseID = res.data.courseID;
    }    
    ElMessage.success(props.courseID ? '课程更新成功' : '课程创建成功');
    emit('success');
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  } finally {
    submitting.value = false;
  }
}

// 取消
function handleCancel() {
  emit('cancel');
}
</script>

<style lang="scss" scoped>
.course-add {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
}

.info-card,
.chapter-card {
  margin-bottom: 20px;
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ml-2 {
  margin-left: 8px;
}

.chapter-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 20px;
}

.chapter-actions {
  margin-left: auto;
}

.nodes-section {
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.nodes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.nodes-title {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.nodes-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.node-card {
  :deep(.el-card__header) {
    padding: 12px 15px;
    background: #fafafa;
  }
  
  :deep(.el-card__body) {
    padding: 15px;
  }
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.empty-tip {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

.file-info-display {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    color: #606266;
    font-size: 14px;
  }
  
  .no-file {
    color: #909399;
    font-style: italic;
  }
}

.cover-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 4px;
  
  img {
    max-width: 100%;
    max-height: 100px;
    border-radius: 4px;
  }
  
  .no-cover {
    color: #909399;
    font-size: 14px;
    font-style: italic;
  }
}
</style>
