<template>
  <div class="school-course-list-page">
    <a-card :bordered="false">
      <template #title>
        <span>我的校本课程包</span>
      </template>
      <template #extra>
        <a-space>
          <a-select
            v-model:value="filterLocation"
            placeholder="筛选位置"
            style="width: 150px"
            @change="fetchData"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="PERSONAL">
              <UserOutlined /> 个人课程中心
            </a-select-option>
            <a-select-option value="SCHOOL">
              <TeamOutlined /> 校本课程中心
            </a-select-option>
          </a-select>
          <a-button type="primary" @click="handleCreate">
            <template #icon><PlusOutlined /></template>
            从课程中心创建
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="filteredData"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="name-cell">
              <span>{{ record.name }}</span>
              <a-tag v-if="record.saveLocation === 'PERSONAL'" size="small" color="blue">
                个人
              </a-tag>
              <a-tag v-else size="small" color="green">
                校本
              </a-tag>
            </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"
              />
              <span>{{ record.sourceCourse?.name }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'reviewStatus'">
            <a-tag :color="getReviewStatusColor(record.reviewStatus)">
              {{ getReviewStatusText(record.reviewStatus) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getCourseStatusColor(record.status)">
              {{ getCourseStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm title="确定要删除吗？" @confirm="handleDelete(record)">
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { PlusOutlined, UserOutlined, TeamOutlined } from '@ant-design/icons-vue';
import { getTeacherSchoolCourseList, deleteTeacherSchoolCourse } from '@/api/school-course';
import type { SchoolCourse } from '@/api/school-course';
import { translateCourseStatus } from '@/utils/tagMaps';

// 审核状态映射
const getReviewStatusText = (status: string): string => {
  if (!status) return '-';
  return translateCourseStatus(status);
};

const getReviewStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    'PENDING': 'orange',
    'APPROVED': 'success',
    'REJECTED': 'error',
    'DRAFT': 'default',
  };
  return colorMap[status] || 'default';
};

// 状态映射
const getCourseStatusText = (status: string): string => {
  if (!status) return '未知';
  if (status === 'ACTIVE') return '启用';
  if (status === 'INACTIVE') return '禁用';
  return status;
};

const getCourseStatusColor = (status: string): string => {
  if (status === 'ACTIVE') return 'success';
  if (status === 'INACTIVE') return 'default';
  return 'default';
};

const router = useRouter();

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

const filteredData = computed(() => {
  if (!filterLocation.value) return dataSource.value;
  return dataSource.value.filter(item => item.saveLocation === filterLocation.value);
});

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '名称', key: 'name', width: 200 },
  { title: '源课程包', key: 'sourceCourse' },
  { title: '修改说明', dataIndex: 'changesSummary', key: 'changesSummary' },
  { title: '使用次数', dataIndex: 'usageCount', key: 'usageCount', width: 100 },
  { title: '审核状态', key: 'reviewStatus', width: 100 },
  { title: '状态', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 180 },
];

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}`;
};

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

const handleCreate = () => {
  // 跳转到课程中心列表，让用户选择源课程
  router.push('/teacher/courses');
};

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

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

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

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

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

.name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.source-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

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