<template>
  <div class="school-course-list-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-icon-wrapper">
            <AppstoreOutlined class="title-icon" />
          </div>
          <div class="title-text">
            <h2>校本课程包</h2>
            <p>管理本校教师创建的校本课程包</p>
          </div>
        </div>
        <a-button type="primary" @click="handleCreate">
          <PlusOutlined /> 创建校本课程包
        </a-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-icon total">
          <AppstoreOutlined />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ dataSource.length }}</div>
          <div class="stat-label">校本课程包总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon usage">
          <BarChartOutlined />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ totalUsage }}</div>
          <div class="stat-label">本周使用次数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon reservation">
          <CalendarOutlined />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ pendingReservations }}</div>
          <div class="stat-label">待上课预约</div>
        </div>
      </div>
    </div>

    <!-- 套餐列表 -->
    <a-card :bordered="false" class="list-card">
      <template #title>
        <span>校本课程包列表</span>
      </template>
      <template #extra>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索课程包名称"
          style="width: 200px"
          @search="handleSearch"
        />
      </template>

      <a-table
        :columns="columns"
        :data-source="filteredData"
        :loading="loading"
        row-key="id"
        :pagination="{ pageSize: 10 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="course-name">
              <span class="name">{{ record.name }}</span>
              <span v-if="record.changesSummary" class="changes-hint">
                {{ record.changesSummary }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'sourceCourse'">
            <div class="source-info">
              <img
                v-if="record.sourceCourse?.coverImagePath"
                :src="getFileUrl(record.sourceCourse.coverImagePath)"
                class="cover"
              />
              <div v-else class="cover-placeholder">
                <BookOutlined />
              </div>
              <span>{{ record.sourceCourse?.name || '-' }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'createdBy'">
            <span>{{ record.creator?.name || '-' }}</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'ACTIVE' ? 'success' : 'default'">
              {{ record.status === 'ACTIVE' ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'usageCount'">
            <a-badge :count="record.usageCount || 0" :number-style="{ backgroundColor: '#52c41a' }" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-tooltip title="查看详情">
                <a-button type="link" size="small" @click="handleView(record)">
                  <EyeOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip title="预约">
                <a-button type="link" size="small" @click="showReserveModal(record)">
                  <CalendarOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip title="排课">
                <a-button type="link" size="small" @click="showScheduleModal(record)">
                  <ScheduleOutlined />
                </a-button>
              </a-tooltip>
              <a-dropdown>
                <a-button type="link" size="small">
                  <MoreOutlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleEdit(record)">
                      <EditOutlined /> 编辑
                    </a-menu-item>
                    <a-menu-divider />
                    <a-menu-item danger @click="confirmDelete(record)">
                      <DeleteOutlined /> 删除
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 预约弹窗 -->
    <a-modal
      v-model:open="reserveModalVisible"
      title="预约校本课程包"
      width="500px"
      @ok="handleReserve"
      :confirmLoading="reserveLoading"
    >
      <div class="reserve-modal" v-if="selectedCourse">
        <div class="course-info">
          <span class="label">课程包名称</span>
          <span class="value">{{ selectedCourse.name }}</span>
        </div>

        <a-divider />

        <a-form layout="vertical">
          <a-form-item label="授课教师" required>
            <a-select v-model:value="reserveForm.teacherId" placeholder="选择授课教师" show-search>
              <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="授课班级" required>
            <a-select v-model:value="reserveForm.classId" placeholder="选择授课班级">
              <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="预约时间" required>
            <a-date-picker
              v-model:value="reserveForm.scheduledDate"
              show-time
              format="YYYY-MM-DD HH:mm"
              placeholder="选择预约时间"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea v-model:value="reserveForm.note" :rows="2" placeholder="备注信息（可选）" />
          </a-form-item>
        </a-form>

        <a-alert
          v-if="conflictInfo"
          :type="conflictInfo.hasConflict ? 'error' : 'success'"
          :message="conflictInfo.message"
          show-icon
        />
      </div>
    </a-modal>

    <!-- 排课弹窗 -->
    <a-modal
      v-model:open="scheduleModalVisible"
      title="排课管理"
      width="800px"
      :footer="null"
    >
      <div class="schedule-modal" v-if="selectedCourse">
        <div class="course-info-header">
          <span>课程包：{{ selectedCourse.name }}</span>
          <a-button type="primary" size="small" @click="showReserveModal(selectedCourse)">
            <PlusOutlined /> 新增排课
          </a-button>
        </div>

        <a-tabs v-model:activeKey="scheduleTab">
          <a-tab-pane key="upcoming" tab="即将上课">
            <a-table
              :columns="reservationColumns"
              :data-source="upcomingReservations"
              :loading="reservationLoading"
              row-key="id"
              size="small"
              :pagination="false"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-space>
                    <a-button type="link" size="small" @click="cancelReserve(record)">取消</a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
            <div v-if="upcomingReservations.length === 0" class="empty-state">
              暂无即将上课的预约
            </div>
          </a-tab-pane>
          <a-tab-pane key="history" tab="历史记录">
            <a-table
              :columns="reservationColumns"
              :data-source="historyReservations"
              :loading="reservationLoading"
              row-key="id"
              size="small"
              :pagination="{ pageSize: 5 }"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import {
  PlusOutlined,
  AppstoreOutlined,
  BarChartOutlined,
  CalendarOutlined,
  EyeOutlined,
  ScheduleOutlined,
  MoreOutlined,
  EditOutlined,
  DeleteOutlined,
  BookOutlined,
} from '@ant-design/icons-vue';
import {
  getSchoolCourseList,
  deleteSchoolCourse,
  getReservations,
  createReservation,
  cancelReservation,
  type SchoolCourse,
  type CreateReservationData,
} from '@/api/school-course';
import { getTeachers, getClasses } from '@/api/school';
import type { Teacher, ClassInfo } from '@/api/school';
import dayjs from 'dayjs';

const router = useRouter();

const loading = ref(false);
const dataSource = ref<SchoolCourse[]>([]);
const searchKeyword = ref('');

// 预约相关
const reserveModalVisible = ref(false);
const scheduleModalVisible = ref(false);
const selectedCourse = ref<SchoolCourse | null>(null);
const reserveLoading = ref(false);
const reserveForm = ref<CreateReservationData>({
  teacherId: undefined as any,
  classId: undefined as any,
  scheduledDate: undefined as any,
  note: '',
});

// 数据
const teachers = ref<Teacher[]>([]);
const classes = ref<ClassInfo[]>([]);
const reservations = ref<any[]>([]);
const reservationLoading = ref(false);
const scheduleTab = ref('upcoming');
const conflictInfo = ref<{ hasConflict: boolean; message: string } | null>(null);

// 获取完整的文件 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.startsWith('/') ? '' : '/'}${filePath}`;
};

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 60 },
  { title: '校本课程包名称', key: 'name' },
  { title: '基于课程包', key: 'sourceCourse' },
  { title: '创建者', key: 'createdBy', width: 100 },
  { title: '使用次数', dataIndex: 'usageCount', key: 'usageCount', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 180 },
];

const reservationColumns = [
  { title: '预约时间', dataIndex: 'scheduledDate', key: 'scheduledDate', width: 160 },
  { title: '教师', dataIndex: ['teacher', 'name'], key: 'teacherName', width: 100 },
  { title: '班级', dataIndex: ['class', 'name'], key: 'className', width: 100 },
  { title: '状态', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 80 },
];

// 计算属性
const filteredData = computed(() => {
  if (!searchKeyword.value) return dataSource.value;
  const keyword = searchKeyword.value.toLowerCase();
  return dataSource.value.filter(item =>
    item.name.toLowerCase().includes(keyword) ||
    item.sourceCourse?.name?.toLowerCase().includes(keyword)
  );
});

const totalUsage = computed(() => {
  return dataSource.value.reduce((sum, item) => sum + (item.usageCount || 0), 0);
});

const pendingReservations = computed(() => {
  return reservations.value.filter(r => r.status === 'PENDING').length;
});

const upcomingReservations = computed(() => {
  const now = new Date();
  return reservations.value.filter(r => new Date(r.scheduledDate) >= now);
});

const historyReservations = computed(() => {
  const now = new Date();
  return reservations.value.filter(r => new Date(r.scheduledDate) < now);
});

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    PENDING: 'blue',
    COMPLETED: 'green',
    CANCELLED: 'red',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    PENDING: '待上课',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
  };
  return texts[status] || status;
};

const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getSchoolCourseList() as any;
    dataSource.value = res || [];
  } catch (error) {
    console.error('获取校本课程包列表失败', error);
  } finally {
    loading.value = false;
  }
};

const fetchBaseData = async () => {
  try {
    const [teacherRes, classRes] = await Promise.all([
      getTeachers({ pageSize: 1000 }),
      getClasses(),
    ]);
    teachers.value = (teacherRes as any).items || [];
    classes.value = classRes as any;
  } catch (error) {
    console.error('获取基础数据失败', error);
  }
};

const handleSearch = () => {
  // 搜索已通过 computed 实现
};

const handleCreate = () => {
  router.push('/school/school-courses/create');
};

const handleView = (record: any) => {
  router.push(`/school/school-courses/${record.id}`);
};

const handleEdit = (record: any) => {
  router.push(`/school/school-courses/${record.id}/edit`);
};

const confirmDelete = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除校本课程包"${record.name}"吗？`,
    okText: '删除',
    okType: 'danger',
    onOk: () => handleDelete(record),
  });
};

const handleDelete = async (record: any) => {
  try {
    await deleteSchoolCourse(record.id);
    message.success('删除成功');
    fetchData();
  } catch (error) {
    message.error('删除失败');
  }
};

// 显示预约弹窗
const showReserveModal = (record: SchoolCourse) => {
  selectedCourse.value = record;
  reserveForm.value = {
    teacherId: undefined as any,
    classId: undefined as any,
    scheduledDate: undefined as any,
    note: '',
  };
  conflictInfo.value = null;
  reserveModalVisible.value = true;
};

// 显示排课弹窗
const showScheduleModal = async (record: SchoolCourse) => {
  selectedCourse.value = record;
  scheduleTab.value = 'upcoming';
  scheduleModalVisible.value = true;
  await loadReservations(record.id);
};

// 加载预约列表
const loadReservations = async (schoolCourseId: number) => {
  reservationLoading.value = true;
  try {
    const res = await getReservations(schoolCourseId);
    reservations.value = (res as any) || [];
  } catch (error) {
    console.error('获取预约列表失败', error);
  } finally {
    reservationLoading.value = false;
  }
};

// 处理预约
const handleReserve = async () => {
  if (!selectedCourse.value) return;

  if (!reserveForm.value.teacherId) {
    message.warning('请选择授课教师');
    return;
  }
  if (!reserveForm.value.classId) {
    message.warning('请选择授课班级');
    return;
  }
  if (!reserveForm.value.scheduledDate) {
    message.warning('请选择预约时间');
    return;
  }

  reserveLoading.value = true;
  try {
    const data = {
      ...reserveForm.value,
      scheduledDate: reserveForm.value.scheduledDate.format('YYYY-MM-DD HH:mm'),
    };
    await createReservation(selectedCourse.value.id, data);
    message.success('预约成功');
    reserveModalVisible.value = false;
    await loadReservations(selectedCourse.value.id);
  } catch (error) {
    console.error('预约失败', error);
    message.error('预约失败');
  } finally {
    reserveLoading.value = false;
  }
};

// 取消预约
const cancelReserve = async (record: any) => {
  try {
    await cancelReservation(record.id);
    message.success('取消成功');
    if (selectedCourse.value) {
      await loadReservations(selectedCourse.value.id);
    }
  } catch (error) {
    message.error('取消失败');
  }
};

onMounted(() => {
  fetchData();
  fetchBaseData();
});
</script>

<style scoped lang="scss">
.school-course-list-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #FFF8F0 0%, #FFFFFF 100%);
  padding: 24px;
}

/* 页面头部 */
.page-header {
  margin-bottom: 24px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

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

  .title-icon-wrapper {
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 14px;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  }

  .title-icon {
    font-size: 28px;
    color: white;
  }

  .title-text h2 {
    color: #333;
    font-size: 24px;
    font-weight: 700;
    margin: 0;
  }

  .title-text p {
    color: #666;
    font-size: 14px;
    margin: 4px 0 0 0;
  }
}

/* 统计概览 */
.stats-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;

    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }

    &.usage {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      color: white;
    }

    &.reservation {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;
    }
  }

  .stat-info {
    .stat-value {
      font-size: 28px;
      font-weight: 700;
      color: #333;
    }

    .stat-label {
      font-size: 13px;
      color: #666;
    }
  }
}

/* 列表卡片 */
.list-card {
  border-radius: 12px;
}

/* 课程名称 */
.course-name {
  display: flex;
  flex-direction: column;

  .name {
    font-weight: 500;
  }

  .changes-hint {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }
}

/* 源课程信息 */
.source-info {
  display: flex;
  align-items: center;
  gap: 8px;

  .cover {
    width: 40px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
  }

  .cover-placeholder {
    width: 40px;
    height: 40px;
    background: #f0f0f0;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
  }
}

/* 预约弹窗 */
.reserve-modal {
  .course-info {
    background: #f9f9f9;
    border-radius: 8px;
    padding: 12px 16px;
    display: flex;
    gap: 8px;

    .label {
      color: #666;
    }

    .value {
      font-weight: 500;
    }
  }
}

/* 排课弹窗 */
.schedule-modal {
  .course-info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 12px 16px;
    background: #f9f9f9;
    border-radius: 8px;
  }

  .empty-state {
    text-align: center;
    padding: 40px;
    color: #999;
  }
}
</style>
