<template>
  <div class="package-detail-page">
    <a-card :bordered="false" :loading="loading">
      <template #title>
        <span>套餐详情</span>
      </template>
      <template #extra>
        <a-space>
          <a-button @click="router.back()">返回</a-button>
          <a-button v-if="pkg?.status === 'DRAFT'" type="primary" @click="handleEdit">编辑</a-button>
          <a-button v-if="pkg?.status === 'DRAFT'" @click="handleSubmit">提交审核</a-button>
          <a-button v-if="pkg?.status === 'APPROVED'" type="primary" @click="handlePublish">发布</a-button>
        </a-space>
      </template>

      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="套餐名称">{{ pkg?.name }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(pkg?.status || '')">{{ getStatusText(pkg?.status || '') }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="价格">¥{{ ((pkg?.price || 0) / 100).toFixed(2) }}</a-descriptions-item>
        <a-descriptions-item label="优惠价">
          {{ pkg?.discountPrice ? '¥' + (pkg.discountPrice / 100).toFixed(2) : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="适用年级">
          <a-tag v-for="grade in pkg?.gradeLevels" :key="grade">{{ grade }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="课程包数量">{{ pkg?.courseCount }}</a-descriptions-item>
        <a-descriptions-item label="使用学校数">{{ pkg?.tenantCount }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ formatDate(pkg?.createdAt) }}</a-descriptions-item>
        <a-descriptions-item label="发布时间" :span="2">{{ formatDate(pkg?.publishedAt) }}</a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">{{ pkg?.description || '-' }}</a-descriptions-item>
      </a-descriptions>

      <a-divider>包含课程包</a-divider>

      <a-table
        :columns="courseColumns"
        :data-source="pkg?.courses || []"
        row-key="courseId"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'course'">
            <div class="course-info">
              <img
                v-if="record.course?.coverImagePath"
                :src="record.course.coverImagePath"
                class="course-cover"
              />
              <span>{{ record.course?.name }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'gradeTags'">
            <a-tag v-for="tag in parseGradeTags(record.course?.gradeTags)" :key="tag">{{ tag }}</a-tag>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { getPackageDetail, submitPackage, publishPackage } from '@/api/package';
import type { CoursePackage } from '@/api/package';

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

const loading = ref(false);
const pkg = ref<CoursePackage | null>(null);

const courseColumns = [
  { title: '课程包', key: 'course' },
  { title: '年级', dataIndex: 'gradeLevel', key: 'gradeLevel', width: 100 },
  { title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 80 },
  { title: '时长', dataIndex: ['course', 'duration'], key: 'duration', width: 80 },
];

const statusColors: Record<string, string> = {
  DRAFT: 'default',
  PENDING_REVIEW: 'processing',
  APPROVED: 'success',
  REJECTED: 'error',
  PUBLISHED: 'blue',
  OFFLINE: 'warning',
};

const statusTexts: Record<string, string> = {
  DRAFT: '草稿',
  PENDING_REVIEW: '待审核',
  APPROVED: '已通过',
  REJECTED: '已拒绝',
  PUBLISHED: '已发布',
  OFFLINE: '已下架',
};

const getStatusColor = (status: string) => statusColors[status] || 'default';
const getStatusText = (status: string) => statusTexts[status] || status;

const formatDate = (date?: string) => {
  if (!date) return '-';
  return new Date(date).toLocaleString();
};

const parseGradeTags = (tags?: string) => {
  if (!tags) return [];
  try {
    return JSON.parse(tags);
  } catch {
    return [];
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const id = Number(route.params.id);
    const res = await getPackageDetail(id);
    pkg.value = res.data;
  } catch (error) {
    message.error('获取套餐详情失败');
  } finally {
    loading.value = false;
  }
};

const handleEdit = () => {
  router.push(`/admin/packages/${route.params.id}/edit`);
};

const handleSubmit = async () => {
  try {
    await submitPackage(Number(route.params.id));
    message.success('提交成功');
    fetchData();
  } catch (error) {
    message.error('提交失败');
  }
};

const handlePublish = async () => {
  try {
    await publishPackage(Number(route.params.id));
    message.success('发布成功');
    fetchData();
  } catch (error) {
    message.error('发布失败');
  }
};

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

<style scoped>
.package-detail-page {
  padding: 24px;
}

.course-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

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