<template>
  <div class="schedule-list-view">
    <!-- 筛选区 -->
    <div class="filter-section">
      <a-space wrap>
        <a-select
          v-model:value="filters.classId"
          placeholder="选择班级"
          allowClear
          style="width: 150px"
          @change="loadSchedules"
        >
          <a-select-option v-for="cls in classes" :key="cls.id" :value="cls.id">
            {{ cls.name }}
          </a-select-option>
        </a-select>
        <a-select
          v-model:value="filters.teacherId"
          placeholder="选择教师"
          allowClear
          style="width: 150px"
          @change="loadSchedules"
        >
          <a-select-option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">
            {{ teacher.name }}
          </a-select-option>
        </a-select>
        <a-range-picker
          :value="dateRange"
          @change="handleDateChange"
        />
        <a-select
          v-model:value="filters.status"
          placeholder="状态"
          allowClear
          style="width: 120px"
          @change="loadSchedules"
        >
          <a-select-option value="ACTIVE">有效</a-select-option>
          <a-select-option value="cancelled">已取消</a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 排课列表 -->
    <a-table
      :columns="columns"
      :data-source="schedules"
      :loading="loading"
      :pagination="pagination"
      rowKey="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'scheduledDate'">
          {{ formatDate(record.scheduledDate) }}
          <span v-if="record.scheduledTime" class="time-slot">{{ record.scheduledTime }}</span>
        </template>
        <template v-if="column.key === 'lessonType'">
          <a-tag v-if="record.lessonType" size="small" :style="getLessonTagStyle(record.lessonType)">
            {{ getLessonTypeName(record.lessonType) }}
          </a-tag>
          <span v-else>-</span>
        </template>
        <template v-if="column.key === 'status'">
          <a-tag :color="getScheduleStatusColor(record.status)">
            {{ getScheduleStatusText(record.status) }}
          </a-tag>
        </template>
        <template v-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-popconfirm
              v-if="isScheduleActive(record.status)"
              title="确定要取消此排课吗？"
              @confirm="handleCancel(record.id)"
            >
              <a-button type="link" size="small" danger>取消</a-button>
            </a-popconfirm>
            <a-popconfirm
              v-if="isScheduleCancelled(record.status)"
              title="确定要删除此排课吗？删除后不可恢复！"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 编辑排课弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      title="编辑排课"
      :confirm-loading="modalLoading"
      @ok="handleSubmit"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="班级" name="classId">
          <a-select
            v-model:value="formState.classId"
            placeholder="选择班级"
            disabled
          >
            <a-select-option v-for="cls in classes" :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="formState.courseId"
            placeholder="选择课程"
            disabled
          >
            <a-select-option v-for="course in courses" :key="course.id" :value="course.id">
              {{ course.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="课程类型">
          <a-tag v-if="editingSchedule?.lessonType" :style="getLessonTagStyle(editingSchedule.lessonType)">
            {{ getLessonTypeName(editingSchedule.lessonType) }}
          </a-tag>
          <span v-else>-</span>
        </a-form-item>
        <a-form-item label="授课教师" name="teacherId">
          <a-select
            v-model:value="formState.teacherId"
            placeholder="选择教师（可选）"
            allowClear
          >
            <a-select-option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">
              {{ teacher.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排课日期" name="scheduledDate">
          <a-date-picker
            v-model:value="formState.scheduledDate"
            style="width: 100%"
            :disabled-date="(current) => current && current < dayjs().startOf('day')"
          />
        </a-form-item>
        <a-form-item label="时间段" name="scheduledTimeRange">
          <a-time-range-picker
            v-model:value="formState.scheduledTimeRange"
            format="HH:mm"
            style="width: 100%"
            :placeholder="['开始时间', '结束时间']"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { TableProps, FormInstance } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';
import {
  getSchedules,
  updateSchedule,
  cancelSchedule,
  deleteSchedule,
  getClasses,
  getTeachers,
  getSchoolCourses,
  type SchedulePlan,
  type UpdateScheduleDto,
  type ClassInfo,
  type Teacher,
} from '@/api/school';
import { getLessonTypeName, getLessonTagStyle, translateGenericStatus, getGenericStatusStyle } from '@/utils/tagMaps';
import { trimFormModel } from '@/utils/trimFormModel';

// 状态辅助函数
const getScheduleStatusText = (status: string): string => {
  if (status === 'ACTIVE' || status === 'scheduled') return '有效';
  if (status === 'CANCELLED' || status === 'cancelled') return '已取消';
  return translateGenericStatus(status);
};

const getScheduleStatusColor = (status: string): string => {
  if (status === 'ACTIVE' || status === 'scheduled') return 'success';
  if (status === 'CANCELLED' || status === 'cancelled') return 'error';
  const style = getGenericStatusStyle(status);
  // 简单映射到 antd 颜色
  return style.color === '#43A047' ? 'success' : 'default';
};

const isScheduleActive = (status: string): boolean => {
  return status === 'ACTIVE' || status === 'scheduled';
};

const isScheduleCancelled = (status: string): boolean => {
  return status === 'CANCELLED' || status === 'cancelled';
};

const handleDelete = async (id: number) => {
  try {
    await deleteSchedule(id);
    message.success('删除成功');
    loadSchedules();
  } catch (error) {
    message.error('删除失败');
  }
};

// 数据
const loading = ref(false);
const schedules = ref<SchedulePlan[]>([]);
const classes = ref<ClassInfo[]>([]);
const teachers = ref<Teacher[]>([]);
const courses = ref<any[]>([]);

// 筛选
const filters = reactive({
  classId: undefined as number | undefined,
  teacherId: undefined as number | undefined,
  status: undefined as string | undefined,
  startDate: undefined as string | undefined,
  endDate: undefined as string | undefined,
});
const dateRange = ref<[Dayjs, Dayjs] | undefined>(undefined);

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
});

// 表格列
const columns = [
  { title: '班级', dataIndex: 'className', key: 'className' },
  { title: '课程', dataIndex: 'courseName', key: 'courseName' },
  { title: '课程类型', key: 'lessonType', width: 120 },
  { title: '授课教师', dataIndex: 'teacherName', key: 'teacherName' },
  { title: '排课时间', key: 'scheduledDate' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'actions', width: 150 },
];

// 弹窗
const modalVisible = ref(false);
const modalLoading = ref(false);
const editingSchedule = ref<SchedulePlan | null>(null);
const formRef = ref<FormInstance>();

// 表单
interface FormState {
  classId: number;
  courseId: number;
  teacherId?: number;
  scheduledDate?: Dayjs;
  scheduledTimeRange?: [Dayjs, Dayjs];
}

const formState = reactive<FormState>({
  classId: undefined as any,
  courseId: undefined as any,
  teacherId: undefined,
  scheduledDate: undefined,
  scheduledTimeRange: undefined,
});

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

// 加载数据
const loadSchedules = async () => {
  loading.value = true;
  try {
    const res = await getSchedules({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    });
    schedules.value = res.list;
    pagination.total = Number(res.total) || 0;
  } catch (error) {
    message.error('加载排课列表失败');
  } finally {
    loading.value = false;
  }
};

const loadBaseData = async () => {
  try {
    const [classesRes, teachersRes, coursesRes] = await Promise.all([
      getClasses(),
      getTeachers({ pageNum: 1, pageSize: 100 }),
      getSchoolCourses(),
    ]);
    classes.value = classesRes;
    teachers.value = teachersRes.list;
    courses.value = coursesRes;
  } catch (error) {
    message.error('加载基础数据失败');
  }
};

// 事件处理
const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current || 1;
  pagination.pageSize = pag.pageSize || 20;
  loadSchedules();
};

const handleDateChange = (dates: any) => {
  if (dates && dates.length === 2) {
    dateRange.value = dates;
    filters.startDate = dates[0].format('YYYY-MM-DD');
    filters.endDate = dates[1].format('YYYY-MM-DD');
  } else {
    dateRange.value = undefined;
    filters.startDate = undefined;
    filters.endDate = undefined;
  }
  loadSchedules();
};

const showEditModal = (record: any) => {
  editingSchedule.value = record;

  // 解析时间字符串为时间范围
  let timeRange: [Dayjs, Dayjs] | undefined = undefined;
  if (record.scheduledTime) {
    const parts = record.scheduledTime.split('-');
    if (parts.length === 2) {
      const baseDate = dayjs().format('YYYY-MM-DD');
      timeRange = [
        dayjs(`${baseDate} ${parts[0]}`, 'YYYY-MM-DD HH:mm'),
        dayjs(`${baseDate} ${parts[1]}`, 'YYYY-MM-DD HH:mm'),
      ];
    }
  }

  Object.assign(formState, {
    classId: record.classId,
    courseId: record.courseId,
    teacherId: record.teacherId,
    scheduledDate: record.scheduledDate ? dayjs(record.scheduledDate) : undefined,
    scheduledTimeRange: timeRange,
  });
  modalVisible.value = true;
};

const handleModalCancel = () => {
  modalVisible.value = false;
  formRef.value?.resetFields();
};

const handleSubmit = async () => {
  try {
    // 提交前移除字符串字段首尾空格，避免空格导致的误校验
    trimFormModel(formState as any);
    await formRef.value?.validate();
    modalLoading.value = true;

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

    const data: UpdateScheduleDto = {
      teacherId: formState.teacherId,
      scheduledDate: formState.scheduledDate?.format('YYYY-MM-DD'),
      scheduledTime,
    };

    await updateSchedule(editingSchedule.value!.id, data);
    message.success('更新成功');
    modalVisible.value = false;
    loadSchedules();
  } catch (error) {
    message.error('更新失败');
  } finally {
    modalLoading.value = false;
  }
};

const handleCancel = async (id: number) => {
  try {
    await cancelSchedule(id);
    message.success('取消成功');
    loadSchedules();
  } catch (error) {
    message.error('取消失败');
  }
};

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

// 暴露刷新方法给父组件
defineExpose({
  refresh: loadSchedules,
});

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

<style scoped lang="scss">
.schedule-list-view {
  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #fafafa;
    border-radius: 8px;
  }

  .time-slot {
    margin-left: 8px;
    color: #666;
    font-size: 12px;
  }
}
</style>
