<template>
  <div class="teacher-schedule-view">
    <div class="page-header">
      <h2>我的课表</h2>
      <a-space>
        <a-button type="primary" @click="showCreateModal">
          <template #icon><PlusOutlined /></template>
          预约上课
        </a-button>
      </a-space>
    </div>

    <!-- 今日课程 -->
    <div class="today-section" v-if="todaySchedules.length > 0">
      <h3><CalendarOutlined /> 今日课程</h3>
      <a-row :gutter="16">
        <a-col :span="6" v-for="schedule in todaySchedules" :key="schedule.id">
          <a-card size="small" class="today-card" :class="{ 'has-lesson': schedule.hasLesson }">
            <template #title>
              <span>{{ schedule.scheduledTime || '待定' }}</span>
            </template>
            <div class="course-name">{{ schedule.courseName }}</div>
            <div class="class-name">{{ schedule.className }}</div>
            <div class="card-actions">
              <a-button
                v-if="schedule.hasLesson && schedule.lessonStatus === 'PLANNED'"
                type="primary"
                size="small"
                @click="goToLesson(schedule.lessonId!)"
              >
                开始上课
              </a-button>
              <a-button
                v-else-if="schedule.hasLesson && schedule.lessonStatus === 'IN_PROGRESS'"
                type="primary"
                size="small"
                @click="goToLesson(schedule.lessonId!)"
              >
                继续上课
              </a-button>
              <a-button
                v-else
                size="small"
                @click="startLessonFromSchedule(schedule)"
              >
                创建课堂
              </a-button>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 周次导航 -->
    <div class="week-navigation">
      <a-space>
        <a-button @click="goToPrevWeek">
          <template #icon><LeftOutlined /></template>
          上一周
        </a-button>
        <a-button @click="goToCurrentWeek">本周</a-button>
        <a-button @click="goToNextWeek">
          下一周
          <template #icon><RightOutlined /></template>
        </a-button>
        <span class="week-range">{{ weekRangeText }}</span>
      </a-space>
    </div>

    <!-- 课表 -->
    <div class="timetable-container">
      <a-spin :spinning="loading">
        <div class="timetable-header">
          <div
            v-for="day in weekDays"
            :key="day.date"
            class="day-header"
            :class="{ 'is-today': day.isToday }"
          >
            <div class="day-name">{{ day.dayName }}</div>
            <div class="day-date">{{ day.dateDisplay }}</div>
          </div>
        </div>

        <div class="timetable-body">
          <div class="timetable-grid">
            <div
              v-for="day in weekDays"
              :key="day.date"
              class="day-column"
              :class="{ 'is-today': day.isToday }"
            >
              <div
                v-for="schedule in day.schedules"
                :key="schedule.id"
                class="schedule-card"
                :class="{
                  'school-schedule': schedule.source === 'SCHOOL',
                  'teacher-schedule': schedule.source === 'TEACHER',
                  'has-lesson': schedule.hasLesson,
                }"
                @click="showScheduleDetail(schedule)"
              >
                <div class="schedule-time">{{ schedule.scheduledTime || '待定' }}</div>
                <div class="schedule-course">{{ schedule.courseName }}</div>
                <div class="schedule-class">{{ schedule.className }}</div>
                <div class="schedule-source">
                  <a-tag v-if="schedule.source === 'SCHOOL'" color="orange" size="small">学校排课</a-tag>
                  <a-tag v-else color="purple" size="small">自主预约</a-tag>
                </div>
                <div v-if="schedule.hasLesson" class="lesson-status">
                  <a-tag :color="getLessonStatusColor(schedule.lessonStatus)" size="small">
                    {{ getLessonStatusText(schedule.lessonStatus) }}
                  </a-tag>
                </div>
              </div>
              <div v-if="!day.schedules.length" class="empty-day">
                暂无排课
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </div>

    <!-- 预约上课弹窗 -->
    <a-modal
      v-model:open="createModalVisible"
      title="预约上课"
      :confirm-loading="createModalLoading"
      @ok="handleCreateSubmit"
      @cancel="createModalVisible = false"
      width="600px"
    >
      <a-form
        ref="createFormRef"
        :model="createFormState"
        :rules="createFormRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="班级" name="classId">
          <a-select v-model:value="createFormState.classId" placeholder="选择班级">
            <a-select-option v-for="cls in myClasses" :key="cls.id" :value="cls.id">
              {{ cls.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="课程" name="courseId">
          <a-select
            v-model:value="createFormState.courseId"
            placeholder="选择课程"
            showSearch
            :filterOption="filterCourseOption"
          >
            <a-select-option v-for="course in availableCourses" :key="course.id" :value="course.id">
              {{ course.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="预约日期" name="scheduledDate">
          <a-date-picker v-model:value="createFormState.scheduledDate" style="width: 100%" />
        </a-form-item>
        <a-form-item label="时间段" name="scheduledTimeRange">
          <a-time-range-picker
            v-model:value="createFormState.scheduledTimeRange"
            format="HH:mm"
            style="width: 100%"
            :placeholder="['开始时间', '结束时间']"
          />
        </a-form-item>
        <a-form-item label="重复方式" name="repeatType">
          <a-radio-group v-model:value="createFormState.repeatType">
            <a-radio value="NONE">单次</a-radio>
            <a-radio value="WEEKLY">每周重复</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-if="createFormState.repeatType === 'WEEKLY'" label="重复截止" name="repeatEndDate">
          <a-date-picker v-model:value="createFormState.repeatEndDate" style="width: 100%" />
        </a-form-item>
        <a-form-item label="备注" name="note">
          <a-textarea v-model:value="createFormState.note" :rows="2" placeholder="备注信息" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 排课详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="排课详情"
      :footer="null"
      width="500px"
    >
      <template v-if="selectedSchedule">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="班级">{{ selectedSchedule.className }}</a-descriptions-item>
          <a-descriptions-item label="课程">{{ selectedSchedule.courseName }}</a-descriptions-item>
          <a-descriptions-item label="排课日期">{{ formatDate(selectedSchedule.scheduledDate) }}</a-descriptions-item>
          <a-descriptions-item label="时间段">{{ selectedSchedule.scheduledTime || '待定' }}</a-descriptions-item>
          <a-descriptions-item label="重复方式">
            <a-tag v-if="selectedSchedule.repeatType === 'NONE'" color="default">单次</a-tag>
            <a-tag v-else-if="selectedSchedule.repeatType === 'WEEKLY'" color="green">每周</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="来源">
            <a-tag v-if="selectedSchedule.source === 'SCHOOL'" color="orange">学校排课</a-tag>
            <a-tag v-else color="purple">自主预约</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag v-if="selectedSchedule.status === 'ACTIVE'" color="success">有效</a-tag>
            <a-tag v-else color="error">已取消</a-tag>
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedSchedule.note" label="备注">{{ selectedSchedule.note }}</a-descriptions-item>
        </a-descriptions>
        <div style="margin-top: 16px; text-align: right;">
          <a-space>
            <a-button
              v-if="selectedSchedule.hasLesson && selectedSchedule.lessonId"
              type="primary"
              @click="goToLesson(selectedSchedule.lessonId)"
            >
              {{ selectedSchedule.lessonStatus === 'IN_PROGRESS' ? '继续上课' : '查看课堂' }}
            </a-button>
            <a-button
              v-else-if="selectedSchedule.status === 'ACTIVE'"
              type="primary"
              @click="startLessonFromSchedule(selectedSchedule)"
            >
              开始上课
            </a-button>
            <a-popconfirm
              v-if="selectedSchedule.source === 'TEACHER' && selectedSchedule.status === 'ACTIVE'"
              title="确定要取消此预约吗？"
              @confirm="handleCancelSchedule(selectedSchedule.id)"
            >
              <a-button danger>取消预约</a-button>
            </a-popconfirm>
          </a-space>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';
import {
  PlusOutlined,
  CalendarOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons-vue';
import {
  getTeacherTimetable,
  getTodayTeacherSchedules,
  createTeacherSchedule,
  cancelTeacherSchedule,
  type TeacherSchedule,
  type CreateTeacherScheduleDto,
} from '@/api/teacher';
import { getTeacherClasses, getTeacherCourses, createLesson } from '@/api/teacher';

const router = useRouter();

// 数据
const loading = ref(false);
const todaySchedules = ref<TeacherSchedule[]>([]);
const timetable = ref<any[]>([]);
const myClasses = ref<any[]>([]);
const availableCourses = ref<any[]>([]);

// 当前周
const currentWeekStart = ref(dayjs().startOf('week').add(1, 'day')); // 周一

// 弹窗
const createModalVisible = ref(false);
const createModalLoading = ref(false);
const detailVisible = ref(false);
const selectedSchedule = ref<TeacherSchedule | null>(null);
const createFormRef = ref<FormInstance>();

// 表单
const createFormState = reactive<CreateTeacherScheduleDto & { scheduledDate?: Dayjs; repeatEndDate?: Dayjs; scheduledTimeRange?: [Dayjs, Dayjs] }>({
  classId: undefined as any,
  courseId: undefined as any,
  scheduledDate: undefined,
  scheduledTimeRange: undefined,
  repeatType: 'NONE',
  repeatEndDate: undefined,
  note: undefined,
});

const createFormRules = {
  classId: [{ required: true, message: '请选择班级' }],
  courseId: [{ required: true, message: '请选择课程' }],
  scheduledDate: [{ required: true, message: '请选择预约日期' }],
};

// 计算属性
const weekRangeText = computed(() => {
  const start = currentWeekStart.value;
  const end = start.add(6, 'day');
  return `${start.format('MM-DD')} 至 ${end.format('MM-DD')}`;
});

const weekDays = computed(() => {
  const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const today = dayjs().format('YYYY-MM-DD');

  return Array.from({ length: 7 }, (_, i) => {
    const date = currentWeekStart.value.add(i, 'day');
    const dateStr = date.format('YYYY-MM-DD');
    const dayData = timetable.value.find(t => t.date === dateStr);

    return {
      date: dateStr,
      dayName: days[i],
      dateDisplay: date.format('MM-DD'),
      isToday: dateStr === today,
      schedules: dayData?.schedules || [],
    };
  });
});

// 加载数据
const loadTimetable = async () => {
  loading.value = true;
  try {
    const start = currentWeekStart.value;
    const res = await getTeacherTimetable({
      startDate: start.format('YYYY-MM-DD'),
      endDate: start.add(6, 'day').format('YYYY-MM-DD'),
    });
    timetable.value = res;
  } catch (error) {
    message.error('加载课表失败');
  } finally {
    loading.value = false;
  }
};

const loadTodaySchedules = async () => {
  try {
    const res = await getTodayTeacherSchedules();
    todaySchedules.value = res;
  } catch (error) {
    console.error('加载今日课程失败', error);
  }
};

const loadBaseData = async () => {
  try {
    const [classesRes, coursesRes] = await Promise.all([
      getTeacherClasses(),
      getTeacherCourses({ page: 1, pageSize: 100 }),
    ]);
    myClasses.value = classesRes;
    availableCourses.value = coursesRes.items;
  } catch (error) {
    message.error('加载基础数据失败');
  }
};

// 周次导航
const goToPrevWeek = () => {
  currentWeekStart.value = currentWeekStart.value.subtract(7, 'day');
  loadTimetable();
};

const goToNextWeek = () => {
  currentWeekStart.value = currentWeekStart.value.add(7, 'day');
  loadTimetable();
};

const goToCurrentWeek = () => {
  currentWeekStart.value = dayjs().startOf('week').add(1, 'day');
  loadTimetable();
};

// 预约上课
const showCreateModal = () => {
  Object.assign(createFormState, {
    classId: undefined,
    courseId: undefined,
    scheduledDate: undefined,
    scheduledTimeRange: undefined,
    repeatType: 'NONE',
    repeatEndDate: undefined,
    note: undefined,
  });
  createModalVisible.value = true;
};

const handleCreateSubmit = async () => {
  try {
    await createFormRef.value?.validate();
    createModalLoading.value = true;

    // 格式化时间范围
    let scheduledTime: string | undefined = undefined;
    if (createFormState.scheduledTimeRange && createFormState.scheduledTimeRange.length === 2) {
      scheduledTime = `${createFormState.scheduledTimeRange[0].format('HH:mm')}-${createFormState.scheduledTimeRange[1].format('HH:mm')}`;
    }

    await createTeacherSchedule({
      classId: createFormState.classId,
      courseId: createFormState.courseId,
      scheduledDate: createFormState.scheduledDate?.format('YYYY-MM-DD'),
      scheduledTime,
      repeatType: createFormState.repeatType,
      repeatEndDate: createFormState.repeatEndDate?.format('YYYY-MM-DD'),
      note: createFormState.note,
    });

    message.success('预约成功');
    createModalVisible.value = false;
    loadTimetable();
    loadTodaySchedules();
  } catch (error) {
    message.error('预约失败');
  } finally {
    createModalLoading.value = false;
  }
};

// 详情
const showScheduleDetail = (schedule: TeacherSchedule) => {
  selectedSchedule.value = schedule;
  detailVisible.value = true;
};

const handleCancelSchedule = async (id: number) => {
  try {
    await cancelTeacherSchedule(id);
    message.success('取消成功');
    detailVisible.value = false;
    loadTimetable();
    loadTodaySchedules();
  } catch (error) {
    message.error('取消失败');
  }
};

// 开始上课
const startLessonFromSchedule = async (schedule: TeacherSchedule) => {
  try {
    const lesson = await createLesson({
      courseId: schedule.courseId,
      classId: schedule.classId,
      plannedDatetime: schedule.scheduledDate,
    });
    message.success('课堂创建成功');
    router.push(`/teacher/lessons/${lesson.id}`);
  } catch (error) {
    message.error('创建课堂失败');
  }
};

const goToLesson = (lessonId: number) => {
  router.push(`/teacher/lessons/${lessonId}`);
};

// 工具方法
const formatDate = (date: string | undefined) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD');
};

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

const getLessonStatusColor = (status: string | undefined) => {
  switch (status) {
    case 'PLANNED': return 'blue';
    case 'IN_PROGRESS': return 'processing';
    case 'COMPLETED': return 'success';
    case 'CANCELLED': return 'error';
    default: return 'default';
  }
};

const getLessonStatusText = (status: string | undefined) => {
  switch (status) {
    case 'PLANNED': return '待上课';
    case 'IN_PROGRESS': return '进行中';
    case 'COMPLETED': return '已完成';
    case 'CANCELLED': return '已取消';
    default: return '未知';
  }
};

onMounted(() => {
  loadBaseData();
  loadTimetable();
  loadTodaySchedules();
});
</script>

<style scoped lang="scss">
.teacher-schedule-view {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }
  }

  .today-section {
    margin-bottom: 24px;

    h3 {
      margin-bottom: 12px;
      color: #FF8C42;
    }

    .today-card {
      &.has-lesson {
        border-color: #52c41a;
      }

      .course-name {
        font-weight: 500;
        margin-bottom: 4px;
      }

      .class-name {
        font-size: 12px;
        color: #666;
        margin-bottom: 8px;
      }

      .card-actions {
        text-align: right;
      }
    }
  }

  .week-navigation {
    margin-bottom: 16px;
    padding: 12px 16px;
    background: #fafafa;
    border-radius: 8px;

    .week-range {
      margin-left: 16px;
      color: #666;
    }
  }

  .timetable-container {
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    overflow: hidden;
  }

  .timetable-header {
    display: table;
    width: 100%;
    table-layout: fixed;
    background: linear-gradient(135deg, #FF8C42 0%, #E67635 100%);
    color: white;

    .day-header {
      display: table-cell;
      padding: 12px 8px;
      text-align: center;
      border-right: 1px solid rgba(255, 255, 255, 0.2);
      vertical-align: middle;

      &:last-child {
        border-right: none;
      }

      &.is-today {
        background: rgba(255, 255, 255, 0.2);
      }

      .day-name {
        font-weight: 500;
      }

      .day-date {
        font-size: 12px;
        opacity: 0.8;
      }
    }
  }

  .timetable-body {
    min-height: 400px;
  }

  .timetable-grid {
    display: table;
    width: 100%;
    table-layout: fixed;

    .day-column {
      display: table-cell;
      min-height: 300px;
      padding: 8px;
      border-right: 1px solid #e8e8e8;
      background: #fafafa;
      vertical-align: top;

      &:last-child {
        border-right: none;
      }

      &.is-today {
        background: #fff4ec;
      }
    }
  }

  .schedule-card {
    background: white;
    border-radius: 8px;
    padding: 10px;
    margin-bottom: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s;
    border-left: 3px solid #722ed1;

    &:hover {
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
      transform: translateY(-2px);
    }

    &.school-schedule {
      border-left-color: #FF8C42;
    }

    &.has-lesson {
      background: #f6ffed;
    }

    .schedule-time {
      font-size: 12px;
      color: #666;
      margin-bottom: 4px;
    }

    .schedule-course {
      font-weight: 500;
      color: #333;
      margin-bottom: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .schedule-class {
      font-size: 12px;
      color: #666;
      margin-bottom: 4px;
    }

    .schedule-source {
      margin-bottom: 4px;
    }

    .lesson-status {
      margin-top: 4px;
    }
  }

  .empty-day {
    text-align: center;
    color: #999;
    padding: 20px;
    font-size: 12px;
  }
}
</style>
