<template>
  <div class="school-course-edit-page">
    <a-card :bordered="false">
      <template #title>
        <span>{{ isEdit ? '编辑校本课程包' : '创建校本课程包' }}</span>
      </template>
      <template #extra>
        <a-button @click="router.back()">返回</a-button>
      </template>

      <a-form
        :model="form"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        @finish="handleSave"
      >
        <a-form-item label="源课程包" name="sourceCourseId" v-if="!isEdit">
          <a-select
            v-model:value="form.sourceCourseId"
            placeholder="请选择源课程包"
            show-search
            :filter-option="filterOption"
            @change="handleSourceChange"
          >
            <a-select-option v-for="course in sourceCourses" :key="course.id" :value="course.id">
              {{ course.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
          <a-input v-model:value="form.name" placeholder="请输入校本课程包名称" />
        </a-form-item>

        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入描述" :rows="3" />
        </a-form-item>

        <a-form-item label="修改说明" name="changesSummary">
          <a-textarea
            v-model:value="form.changesSummary"
            placeholder="请描述对源课程包的修改内容"
            :rows="3"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-space>
            <a-button type="primary" html-type="submit" :loading="saving">保存</a-button>
            <a-button @click="router.back()">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </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 {
  getTeacherSourceCourses,
  getTeacherSchoolCourseDetail,
  createTeacherSchoolCourse,
  updateTeacherSchoolCourse,
} from '@/api/school-course';

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

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

const saving = ref(false);
const sourceCourses = ref<any[]>([]);

const form = reactive({
  sourceCourseId: undefined as number | undefined,
  name: '',
  description: '',
  changesSummary: '',
});

const filterOption = (input: string, option: any) => {
  return option.children?.[0]?.children?.toLowerCase().includes(input.toLowerCase());
};

const fetchSourceCourses = async () => {
  try {
    const res = await getTeacherSourceCourses();
    sourceCourses.value = res.data || [];
  } catch (error) {
    console.error('获取源课程列表失败', error);
  }
};

const fetchDetail = async () => {
  if (!isEdit.value) return;

  try {
    const res = await getTeacherSchoolCourseDetail(courseId.value);
    const data = res.data;
    form.name = data.name;
    form.description = data.description || '';
    form.changesSummary = data.changesSummary || '';
    form.sourceCourseId = data.sourceCourseId;
  } catch (error) {
    message.error('获取详情失败');
  }
};

const handleSourceChange = (value: any) => {
  const course = sourceCourses.value.find((c) => c.id === value);
  if (course) {
    form.name = course.name + ' (校本版)';
    form.description = course.description || '';
  }
};

const handleSave = async () => {
  saving.value = true;
  try {
    const data = {
      name: form.name,
      description: form.description,
      changesSummary: form.changesSummary,
    };

    if (isEdit.value) {
      await updateTeacherSchoolCourse(courseId.value, data);
    } else {
      if (!form.sourceCourseId) {
        message.warning('请选择源课程包');
        return;
      }
      await createTeacherSchoolCourse({
        sourceCourseId: form.sourceCourseId,
        ...data,
      });
    }

    message.success('保存成功');
    router.push('/teacher/school-courses');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  fetchSourceCourses();
  fetchDetail();
});
</script>

<style scoped>
.school-course-edit-page {
  padding: 24px;
}
</style>
