<template>
  <div class="prepare-mode-view">
    <!-- 顶部课程信息 -->
    <div class="course-header">
      <div class="header-left">
        <a-button type="text" @click="goBackToDetail" class="back-btn">
          <template #icon>
            <LeftOutlined />
          </template>
          返回
        </a-button>
        <div class="course-cover" v-if="course.coverImagePath">
          <img :src="getFileUrl(course.coverImagePath)" alt="封面" />
        </div>
        <div class="course-info">
          <h1 class="course-title">
            <BookOpen :size="24" :stroke-width="2" class="title-icon" />
            备课模式：{{ course.name || '备课模式' }}
          </h1>
          <div class="course-meta">
            <span v-if="course.pictureBookName" class="meta-item">
              <BookOutlined /> {{ course.pictureBookName }}
            </span>
            <span v-if="course.theme" class="meta-item">
              <TagOutlined /> {{ course.theme.name }}
            </span>
            <span class="meta-item">
              <ClockCircleOutlined /> 预计 {{ totalDuration }} 分钟
            </span>
            <a-tag v-for="tag in translatedGradeTags" :key="tag" class="grade-tag">
              {{ tag }}
            </a-tag>
          </div>
        </div>
      </div>
      <div class="header-right">
        <a-button @click="showScheduleModal" :disabled="!selectedClassId" class="schedule-btn">
          <template #icon>
            <CalendarOutlined />
          </template>
          预约上课
        </a-button>
        <a-button type="primary" @click="startTeaching" :disabled="!selectedClassId" class="start-btn">
          <template #icon>
            <PlayCircleOutlined />
          </template>
          开始上课
        </a-button>
        <a-button @click="handleExit" class="exit-btn">
          <template #icon>
            <CloseOutlined />
          </template>
          退出备课
        </a-button>
      </div>
    </div>

    <a-spin :spinning="loading">
      <div class="prepare-content">
        <a-row :gutter="20">
          <!-- 左侧：课程导航 -->
          <a-col :span="6">
            <PrepareNavigation :course="course" :lessons="lessons" :selected-section="selectedSection"
              :selected-lesson-id="selectedLessonId" :selected-item="selectedItem" @select-section="handleSelectSection"
              @select-lesson="handleSelectLesson" @select-item="handleSelectItem" />
          </a-col>

          <!-- 右侧：内容预览 -->
          <a-col :span="18">
            <PreparePreview :course="course" :selected-type="selectedSection" :selected-lesson="selectedLesson"
              :selected-item="selectedItem" :selected-step="selectedStep" @select-step="handleSelectStep"
              @preview-resource="handlePreviewResource" />
          </a-col>
        </a-row>
      </div>
    </a-spin>

    <!-- 文件预览弹窗 -->
    <FilePreviewModal v-model:open="previewModalVisible" :file-url="previewFileUrl" :file-name="previewFileName" />

    <!-- 预约上课弹窗（四步流程，与课表页一致） -->
    <TeacherCreateScheduleModal ref="scheduleModalRef" @success="onScheduleSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  LeftOutlined, BookOutlined, ClockCircleOutlined, TagOutlined,
  PlayCircleOutlined, CalendarOutlined, CloseOutlined,
} from '@ant-design/icons-vue';
import { BookOpen } from 'lucide-vue-next';
import { message, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';
import * as teacherApi from '@/api/teacher';
import { useUserStore } from '@/stores/user';
import { getTeacherSchoolCourseFullDetail } from '@/api/school-course';
import { translateGradeTags } from '@/utils/tagMaps';
import FilePreviewModal from '@/components/FilePreviewModal.vue';
import PrepareNavigation from './components/PrepareNavigation.vue';
import PreparePreview from './components/PreparePreview.vue';
import TeacherCreateScheduleModal from '@/views/teacher/schedule/components/TeacherCreateScheduleModal.vue';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const loading = ref(false);

// 导航状态
const selectedSection = ref<'overview' | 'lesson'>('overview');
const selectedLessonId = ref<number | string | null>(null);
const selectedItem = ref<string>('basic');
const selectedStep = ref<any>(null);

// 文件预览相关
const previewModalVisible = ref(false);
const previewFileUrl = ref('');
const previewFileName = ref('');

const courseId = ref<string>('');
const course = ref<any>({});
const lessons = ref<any[]>([]);
const classes = ref<any[]>([]);
const selectedClassId = ref<number>();

/** 预约上课时使用的 courseId（Course.id）和 packageId，从加载数据中解析 */
const scheduleCourseId = ref<number>();
const schedulePackageId = ref<number>();

// 预约上课相关
const scheduleModalRef = ref<InstanceType<typeof TeacherCreateScheduleModal>>();

// 解析标签（后端可能返回 JSON 字符串或数组）
const parseTags = (val: any): string[] => {
  if (!val) return [];
  if (Array.isArray(val)) return val;
  if (typeof val === 'string') {
    try {
      const parsed = JSON.parse(val);
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return [];
    }
  }
  return [];
};

const translatedGradeTags = computed(() => {
  return translateGradeTags(parseTags(course.value.gradeTags));
});

const totalDuration = computed(() => {
  return lessons.value.reduce((sum: number, l: any) => sum + (l.duration || 0), 0);
});

// 当前选中的课程
const selectedLesson = computed(() => {
  if (!selectedLessonId.value) return null;
  return lessons.value.find(l => l.id === selectedLessonId.value);
});

// 获取选中的班级信息
const selectedClassInfo = computed(() => {
  return classes.value.find(c => c.id === selectedClassId.value);
});

// 获取完整的文件 URL
const getFileUrl = (filePath: string | null | undefined): string => {
  if (!filePath) return '';
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath;
  }
  const SERVER_BASE = import.meta.env.VITE_SERVER_BASE_URL || 'http://localhost:3000';
  return `${SERVER_BASE}${filePath}`;
};

const loadCourseData = async () => {
  const id = route.params.id as string;
  // 校验 ID：无效时跳转回课程列表，避免请求 /courses/undefined
  if (!id || id === 'undefined' || id === 'null') {
    message.warning('课程 ID 无效，已返回课程列表');
    router.replace('/teacher/courses');
    return;
  }
  courseId.value = id;

  loading.value = true;
  try {
    // 检查是否是校本课程包
    const isSchoolCourse = route.query.type === 'school';

    let data: any;
    if (isSchoolCourse) {
      // 加载校本课程包（id 传 string 避免 Long 精度丢失）
      const res = await getTeacherSchoolCourseFullDetail(courseId.value as any);
      data = res.data || res;

      // 预约上课：校本课程使用 sourceCourseId 作为 courseId
      scheduleCourseId.value = data.sourceCourseId ?? data.sourceCourse?.id;
      schedulePackageId.value = data.id;

      // 转换校本课程包数据结构
      course.value = {
        id: data.id,
        name: data.name,
        pictureBookName: data.sourceCourse?.name || '',
        theme: data.themeId ? { id: data.themeId, name: '' } : null,
        coverImagePath: data.coverImagePath,
        gradeTags: Array.isArray(data.gradeTags) ? data.gradeTags : (data.gradeTags ? JSON.parse(data.gradeTags) : []),
        domainTags: data.domainTags ? JSON.parse(data.domainTags) : [],
        duration: data.duration || 25,
        coreContent: data.coreContent || '',
        introSummary: data.introSummary,
        introHighlights: data.introHighlights,
        introGoals: data.introGoals,
        introSchedule: data.introSchedule,
        introKeyPoints: data.introKeyPoints,
        introMethods: data.introMethods,
        introEvaluation: data.introEvaluation,
        introNotes: data.introNotes,
        scheduleRefData: data.scheduleRefData,
        environmentConstruction: data.environmentConstruction,
      };

      // 转换课程数据 - 解析 stepsData
      lessons.value = (data.lessons || []).map((lesson: any) => {
        const stepsData = lesson.stepsData ? JSON.parse(lesson.stepsData) : null;
        return {
          id: lesson.id,
          lessonType: lesson.lessonType,
          name: lesson.name,
          description: lesson.description,
          duration: lesson.duration || 25,
          objectives: lesson.objectives,
          preparation: lesson.preparation,
          extension: lesson.extension,
          reflection: lesson.reflection,
          videoPath: lesson.videoPath,
          videoName: lesson.videoName,
          pptPath: lesson.pptPath,
          pptName: lesson.pptName,
          pdfPath: lesson.pdfPath,
          pdfName: lesson.pdfName,
          // 从 stepsData 解析 steps 和资源
          steps: stepsData?.steps || [],
          images: stepsData?.resources?.images || [],
          videos: stepsData?.resources?.videos || [],
          audioList: stepsData?.resources?.audioList || [],
          pptFiles: stepsData?.resources?.pptFiles || [],
          documents: stepsData?.resources?.documents || [],
        };
      });
    } else {
      // 加载标准课程包（id 传 string 避免 Long 精度丢失）
      data = await teacherApi.getTeacherCourse(courseId.value);
      // 预约上课：标准课程包，data.id 为 Course.id，首课的 courseId 与之相同
      scheduleCourseId.value = data.courseLessons?.[0]?.courseId ?? data.id;
      schedulePackageId.value = data.id;

      course.value = {
        ...data,
        courseLessons: data.courseLessons || [],
        gradeTags: parseTags(data.gradeTags),
        domainTags: parseTags(data.domainTags),
      };

      // 转换课程数据格式以匹配前端组件期望
      lessons.value = (data.courseLessons || []).map((lesson: any) => {
        // 将资源路径转换为数组格式
        const videos = lesson.videoPath ? [{ path: lesson.videoPath, name: lesson.videoName || '视频' }] : [];
        const pptFiles = lesson.pptPath ? [{ path: lesson.pptPath, name: lesson.pptName || '课件' }] : [];
        const documents = lesson.pdfPath ? [{ path: lesson.pdfPath, name: lesson.pdfName || '文档' }] : [];

        // 转换steps数据格式：content -> description
        const steps = (lesson.steps || []).map((step: any) => ({
          ...step,
          description: step.content || step.description || '',
        }));

        return {
          ...lesson,
          steps,
          videos,
          pptFiles,
          documents,
          images: [],
          audioList: [],
        };
      });
    }

    // 加载教师班级
    const classesData = await teacherApi.getTeacherClasses();
    classes.value = classesData || [];
    if (classes.value.length > 0) {
      selectedClassId.value = classes.value[0].id;
    }

    // 如果有URL参数指定课程，自动选中
    const queryLessonId = route.query.lessonId ? parseInt(route.query.lessonId as string) : null;
    if (queryLessonId) {
      const lesson = lessons.value.find(l => l.id === queryLessonId);
      if (lesson) {
        handleSelectLesson(lesson);
      }
    } else {
      // 默认选中课程包概览
      selectedSection.value = 'overview';
      selectedItem.value = 'basic';
    }
  } catch (error: any) {
    message.error(error.message || '获取课程数据失败');
  } finally {
    loading.value = false;
  }
};

const handleSelectSection = (section: 'overview' | 'lesson') => {
  selectedSection.value = section;
  selectedLessonId.value = null;
  selectedItem.value = 'basic';
  selectedStep.value = null;
};

const handleSelectLesson = (lesson: any) => {
  selectedSection.value = 'lesson';
  selectedLessonId.value = lesson.id;
  selectedItem.value = 'objectives';
  selectedStep.value = null;
};

const handleSelectItem = (item: string) => {
  selectedItem.value = item;
};

const handleSelectStep = (step: any) => {
  selectedStep.value = step;
};

const handlePreviewResource = (_type: string, resource: any) => {
  previewFileUrl.value = resource.url;
  previewFileName.value = resource.name || '资源文件';
  previewModalVisible.value = true;
};

const startTeaching = async () => {
  if (!selectedClassId.value) {
    message.warning('请先选择班级');
    return;
  }

  Modal.confirm({
    title: '开始上课',
    content: '确认要开始上课吗？系统将创建一条新的授课记录。',
    okText: '确认开始',
    cancelText: '取消',
    onOk: async () => {
      try {
        const now = dayjs();
        const teacherId = userStore.user?.id;
        if (!teacherId) {
          message.error('未获取到教师信息，请重新登录');
          return;
        }
        // 创建授课记录（后端要求 teacherId、title、lessonDate）
        const lesson = await teacherApi.createLesson({
          courseId: courseId.value,
          classId: selectedClassId.value!,
          teacherId,
          title: course.value.name || '授课',
          lessonDate: now.format('YYYY-MM-DD'),
          startTime: now.format('HH:mm'),
        });

        // 开始上课
        await teacherApi.startLesson(lesson.id);

        message.success('正在进入课堂...');
        router.push(`/teacher/lessons/${lesson.id}`);
      } catch (error: any) {
        message.error(error.message || '创建授课记录失败');
      }
    },
  });
};

const showScheduleModal = () => {
  if (!selectedClassId.value) {
    message.warning('请先选择班级');
    return;
  }
  const firstLesson = lessons.value[0];
  if (!firstLesson) {
    message.warning('课程数据异常，暂无课程');
    return;
  }
  const pkgId = schedulePackageId.value ?? parseInt(courseId.value, 10);
  const cid = scheduleCourseId.value ?? firstLesson.courseId ?? firstLesson.id;
  if (!cid) {
    message.warning('课程数据异常，无法预约');
    return;
  }
  scheduleModalRef.value?.openWithPreset({
    packageId: pkgId,
    courseId: cid,
    lessonType: firstLesson.lessonType || 'INTRODUCTION',
    classId: selectedClassId.value,
  });
};

const onScheduleSuccess = () => {
  message.success('预约成功，可在"我的课表"中查看');
};

const handleExit = () => {
  goBackToDetail();
};

const goBackToDetail = () => {
  router.back();
};

onMounted(() => {
  loadCourseData();
});

// 路由变化时重新加载（如从课程 A 的备课页切换到课程 B 的备课页，组件复用时）
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      loadCourseData();
    }
  }
);
</script>

<style scoped>
.prepare-mode-view {
  min-height: 100vh;
  background: linear-gradient(135deg, #FFF5EB 0%, #FFF9F5 50%, #F0F7FF 100%);
  padding-bottom: 24px;
}

/* 顶部课程信息 */
.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.course-cover {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  overflow: hidden;
  flex-shrink: 0;
}

.course-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.course-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.course-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;

  .title-icon {
    color: #FF8C42;
    flex-shrink: 0;
  }
}

.course-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  color: #666;
  font-size: 13px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.grade-tag {
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
  color: #1976D2;
  border: none;
  padding: 2px 10px;
  font-size: 12px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.schedule-btn {
  border: 1px solid #FF8C42;
  color: #FF8C42;
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  background: white;
}

.schedule-btn:hover:not(:disabled) {
  background: #FFF5EB;
  border-color: #FF6B35;
  color: #FF6B35;
}

.start-btn {
  background: linear-gradient(135deg, #FF8C42 0%, #FF6B35 100%);
  border: none;
  height: 36px;
  padding: 0 24px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(255, 140, 66, 0.3);
}

.start-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #FF7A2A 0%, #FF5722 100%);
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(255, 140, 66, 0.4);
}

.exit-btn {
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
}

/* 内容区域 */
.prepare-content {
  padding: 20px 24px;
}
</style>
