<template>
  <div class="school-course-edit-page">
    <a-page-header
      :title="isEdit ? '编辑校本课程包' : '创建校本课程包'"
      @back="() => router.back()"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleSaveDraft" :loading="saving">保存草稿</a-button>
          <a-button type="primary" @click="showSaveModal = true">
            {{ isEdit ? '保存' : '创建' }}
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-spin :spinning="loading" tip="正在加载数据...">
      <a-card :bordered="false" style="margin-top: 16px;">
        <!-- 源课程信息 -->
        <div v-if="sourceCourse" class="source-info">
          <BookOutlined />
          <span>基于：{{ sourceCourse.name }}</span>
          <a-tag color="blue">源课程包</a-tag>
        </div>

        <!-- 步骤导航 -->
        <a-steps :current="currentStep" size="small" @change="onStepChange" class="steps-nav">
          <a-step title="基本信息" />
          <a-step title="课程介绍" />
          <a-step title="排课参考" />
          <a-step title="导入课" />
          <a-step title="集体课" />
          <a-step title="领域课" />
          <a-step title="环创建设" />
        </a-steps>

        <!-- 完成度进度条 -->
        <div class="completion-bar">
          <span>完成度</span>
          <a-progress :percent="completionPercent" :status="completionStatus" size="small" />
        </div>

        <!-- 步骤内容 -->
        <div class="step-content">
          <!-- 步骤1：基本信息 -->
          <Step1BasicInfo
            v-show="currentStep === 0"
            ref="step1Ref"
            v-model="formData.basic"
            @change="handleDataChange"
          />

          <!-- 步骤2：课程介绍 -->
          <Step2CourseIntro
            v-show="currentStep === 1"
            ref="step2Ref"
            v-model="formData.intro"
            @change="handleDataChange"
          />

          <!-- 步骤3：排课参考 -->
          <Step3ScheduleRef
            v-show="currentStep === 2"
            ref="step3Ref"
            v-model="formData.scheduleRefData"
            @change="handleDataChange"
          />

          <!-- 步骤4：导入课 -->
          <Step4IntroLesson
            v-show="currentStep === 3"
            ref="step4Ref"
            :school-course-id="schoolCourseId"
            :lesson-data="formData.lessons.introduction"
            @change="handleDataChange"
          />

          <!-- 步骤5：集体课 -->
          <Step5CollectiveLesson
            v-show="currentStep === 4"
            ref="step5Ref"
            :school-course-id="schoolCourseId"
            :lesson-data="formData.lessons.collective"
            @change="handleDataChange"
          />

          <!-- 步骤6：领域课 -->
          <Step6DomainLessons
            v-show="currentStep === 5"
            ref="step6Ref"
            :school-course-id="schoolCourseId"
            :domain-lessons="formData.lessons.domainLessons"
            @change="handleDataChange"
          />

          <!-- 步骤7：环创建设 -->
          <Step7Environment
            v-show="currentStep === 6"
            ref="step7Ref"
            v-model="formData.environmentConstruction"
            @change="handleDataChange"
          />
        </div>

        <!-- 步骤导航按钮 -->
        <div class="step-actions">
          <a-button v-if="currentStep > 0" @click="prevStep">
            上一步
          </a-button>
          <a-button v-if="currentStep < 6" type="primary" @click="nextStep">
            下一步
          </a-button>
          <a-button v-if="currentStep === 6" type="primary" @click="showSaveModal = true">
            {{ isEdit ? '保存' : '创建' }}
          </a-button>
        </div>
      </a-card>
    </a-spin>

    <!-- 保存位置选择弹窗 -->
    <a-modal
      v-model:open="showSaveModal"
      title="选择保存位置"
      @ok="() => handleSave(false)"
      :confirm-loading="saving"
    >
      <a-radio-group v-model:value="saveLocation">
        <a-space direction="vertical" style="width: 100%;">
          <a-radio value="PERSONAL">
            <div class="save-option">
              <div class="option-title">
                <UserOutlined /> 保存到个人课程中心
              </div>
              <div class="option-desc">仅您自己可以看到和使用</div>
            </div>
          </a-radio>
          <a-radio value="SCHOOL">
            <div class="save-option">
              <div class="option-title">
                <TeamOutlined /> 提交到校本课程中心
              </div>
              <div class="option-desc">本校所有教师都可以看到（需审核）</div>
            </div>
          </a-radio>
        </a-space>
      </a-radio-group>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { BookOutlined, UserOutlined, TeamOutlined } from '@ant-design/icons-vue';
import Step1BasicInfo from '@/components/course-edit/Step1BasicInfo.vue';
import Step2CourseIntro from '@/components/course-edit/Step2CourseIntro.vue';
import Step3ScheduleRef from '@/components/course-edit/Step3ScheduleRef.vue';
import Step4IntroLesson from './components/Step4IntroLesson.vue';
import Step5CollectiveLesson from './components/Step5CollectiveLesson.vue';
import Step6DomainLessons from './components/Step6DomainLessons.vue';
import Step7Environment from '@/components/course-edit/Step7Environment.vue';
import * as schoolCourseApi from '@/api/school-course';

const router = useRouter();
const route = useRoute();

const isEdit = computed(() => !!route.params.id);
const schoolCourseId = computed(() => Number(route.params.id));

const loading = ref(false);
const saving = ref(false);
const currentStep = ref(0);
const showSaveModal = ref(false);
const saveLocation = ref<'PERSONAL' | 'SCHOOL'>('PERSONAL');
const sourceCourse = ref<any>(null);

// 步骤组件引用
const step1Ref = ref();
const step2Ref = ref();
const step3Ref = ref();
const step4Ref = ref();
const step5Ref = ref();
const step6Ref = ref();
const step7Ref = ref();

// 表单数据
const formData = reactive({
  basic: {
    name: '',
    themeId: undefined as number | undefined,
    grades: [] as string[],
    pictureBookName: '',
    coreContent: '',
    duration: 25,
    domainTags: [] as string[],
    coverImagePath: '',
  },
  intro: {
    introSummary: '',
    introHighlights: '',
    introGoals: '',
    introSchedule: '',
    introKeyPoints: '',
    introMethods: '',
    introEvaluation: '',
    introNotes: '',
  },
  scheduleRefData: '',
  environmentConstruction: '',
  lessons: {
    introduction: null as any,
    collective: null as any,
    domainLessons: {
      LANGUAGE: null as any,
      HEALTH: null as any,
      SCIENCE: null as any,
      SOCIAL: null as any,
      ART: null as any,
    },
  },
});

// 计算完成度
const completionPercent = computed(() => {
  let filled = 0;
  let total = 0;

  // 基本信息必填项
  total += 4;
  if (formData.basic.name) filled++;
  if (formData.basic.themeId) filled++;
  if (formData.basic.grades.length > 0) filled++;
  if (formData.basic.coreContent) filled++;

  // 课程介绍（8项可选）
  total += 8;
  if (formData.intro.introSummary) filled++;
  if (formData.intro.introHighlights) filled++;
  if (formData.intro.introGoals) filled++;
  if (formData.intro.introSchedule) filled++;
  if (formData.intro.introKeyPoints) filled++;
  if (formData.intro.introMethods) filled++;
  if (formData.intro.introEvaluation) filled++;
  if (formData.intro.introNotes) filled++;

  return Math.round((filled / total) * 100);
});

const completionStatus = computed(() => {
  if (completionPercent.value >= 75) return 'success';
  if (completionPercent.value >= 50) return 'normal';
  return 'exception';
});

// 获取课程详情
const fetchDetail = async () => {
  if (!isEdit.value) return;

  loading.value = true;
  try {
    const res = await schoolCourseApi.getTeacherSchoolCourseFullDetail(schoolCourseId.value) as any;
    const data = res.data || res;

    // 基本信息
    formData.basic.name = data.name || '';
    formData.basic.themeId = data.themeId;
    formData.basic.grades = Array.isArray(data.gradeTags) ? data.gradeTags : (data.gradeTags ? JSON.parse(data.gradeTags) : []);
    formData.basic.pictureBookName = '';
    formData.basic.coreContent = data.coreContent || data.core_content || '';
    formData.basic.duration = data.duration || 25;
    formData.basic.domainTags = data.domainTags ? JSON.parse(data.domainTags) : [];
    formData.basic.coverImagePath = data.coverImagePath || data.cover_image_path || '';

    // 课程介绍
    formData.intro.introSummary = data.introSummary || data.intro_summary || '';
    formData.intro.introHighlights = data.introHighlights || data.intro_highlights || '';
    formData.intro.introGoals = data.introGoals || data.intro_goals || '';
    formData.intro.introSchedule = data.introSchedule || data.intro_schedule || '';
    formData.intro.introKeyPoints = data.introKeyPoints || data.intro_key_points || '';
    formData.intro.introMethods = data.introMethods || data.intro_methods || '';
    formData.intro.introEvaluation = data.introEvaluation || data.intro_evaluation || '';
    formData.intro.introNotes = data.introNotes || data.intro_notes || '';

    // 排课参考和环创建设
    formData.scheduleRefData = data.scheduleRefData || data.schedule_ref_data || '';
    formData.environmentConstruction = data.environmentConstruction || data.environment_construction || '';

    // 源课程信息
    sourceCourse.value = data.sourceCourse;

    // 课程配置
    if (data.lessons && data.lessons.length > 0) {
      for (const lesson of data.lessons) {
        const stepsData = lesson.stepsData ? JSON.parse(lesson.stepsData) : null;

        if (lesson.lessonType === 'INTRODUCTION') {
          formData.lessons.introduction = {
            ...lesson,
            stepsData,
          };
        } else if (lesson.lessonType === 'COLLECTIVE') {
          formData.lessons.collective = {
            ...lesson,
            stepsData,
          };
        } else if (['LANGUAGE', 'HEALTH', 'SCIENCE', 'SOCIAL', 'ART'].includes(lesson.lessonType)) {
          formData.lessons.domainLessons[lesson.lessonType as keyof typeof formData.lessons.domainLessons] = {
            ...lesson,
            stepsData,
          };
        }
      }
    }
  } catch (error: any) {
    message.error(error.message || '获取详情失败');
  } finally {
    loading.value = false;
  }
};

// 从源课程创建
const createFromSource = async () => {
  const sourceCourseId = Number(route.query.sourceCourseId);
  if (!sourceCourseId) return;

  loading.value = true;
  try {
    const res = await schoolCourseApi.createTeacherSchoolCourseFromSource(sourceCourseId, saveLocation.value);
    const data = res.data || res;

    message.success('创建成功，请编辑课程内容');
    router.replace(`/teacher/school-courses/${data.id}/edit`);
    await fetchDetail();
  } catch (error: any) {
    message.error(error.message || '创建失败');
  } finally {
    loading.value = false;
  }
};

// 步骤导航
const onStepChange = (step: number) => {
  if (step > currentStep.value) {
    if (!validateCurrentStep()) {
      return;
    }
  }
  currentStep.value = step;
};

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

const nextStep = () => {
  if (!validateCurrentStep()) {
    return;
  }
  if (currentStep.value < 6) {
    currentStep.value++;
  }
};

// 验证当前步骤
const validateCurrentStep = () => {
  if (currentStep.value === 0) {
    const result = step1Ref.value?.validate();
    if (!result?.valid) {
      message.warning(result?.errors[0] || '请完成基本信息');
      return false;
    }
  }
  return true;
};

// 处理数据变化
const handleDataChange = () => {
  // 数据变化时可以自动保存草稿
};

// 保存草稿
const handleSaveDraft = async () => {
  await handleSave(true);
};

// 保存
const handleSave = async (_isDraft = false) => {
  if (saving.value) return;

  if (!validateCurrentStep()) {
    return;
  }

  saving.value = true;

  try {
    const data = {
      name: formData.basic.name,
      themeId: formData.basic.themeId,
      gradeTags: JSON.stringify(formData.basic.grades),
      coreContent: formData.basic.coreContent,
      duration: formData.basic.duration,
      domainTags: JSON.stringify(formData.basic.domainTags),
      coverImagePath: formData.basic.coverImagePath,

      introSummary: formData.intro.introSummary,
      introHighlights: formData.intro.introHighlights,
      introGoals: formData.intro.introGoals,
      introSchedule: formData.intro.introSchedule,
      introKeyPoints: formData.intro.introKeyPoints,
      introMethods: formData.intro.introMethods,
      introEvaluation: formData.intro.introEvaluation,
      introNotes: formData.intro.introNotes,

      scheduleRefData: formData.scheduleRefData,
      environmentConstruction: formData.environmentConstruction,

      lessons: formData.lessons,
    };

    if (isEdit.value) {
      await schoolCourseApi.updateTeacherSchoolCourseFull(schoolCourseId.value, data);
      message.success('保存成功');
    } else {
      await schoolCourseApi.createTeacherSchoolCourseFromSource(
        Number(route.query.sourceCourseId),
        saveLocation.value,
      );
      message.success('创建成功');
    }

    showSaveModal.value = false;
    router.back();
  } catch (error: any) {
    message.error(error.message || '保存失败');
  } finally {
    saving.value = false;
  }
};

onMounted(async () => {
  if (route.query.sourceCourseId) {
    await createFromSource();
  } else {
    await fetchDetail();
  }
});
</script>

<style scoped lang="scss">
.school-course-edit-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: calc(100vh - 64px);
}

.source-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #f0f7ff;
  border-radius: 8px;
  margin-bottom: 16px;

  .anticon {
    font-size: 18px;
    color: #1890ff;
  }

  span {
    font-size: 14px;
    color: #333;
  }
}

.steps-nav {
  margin-bottom: 24px;
}

.completion-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding: 12px 16px;
  background: #fafafa;
  border-radius: 8px;

  span {
    font-size: 14px;
    color: #666;
    white-space: nowrap;
  }

  .ant-progress {
    flex: 1;
  }
}

.step-content {
  min-height: 400px;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.save-option {
  padding: 12px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  margin-bottom: 12px;
  transition: all 0.2s;

  &:hover {
    border-color: #1890ff;
    background: #f0f7ff;
  }

  .option-title {
    font-weight: 500;
    margin-bottom: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .option-desc {
    font-size: 13px;
    color: #999;
  }
}
</style>
