<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' || pkg?.status === 'REJECTED'"
            type="primary"
            @click="handleEdit"
          >
            编辑
          </a-button>
          <!-- 提交审核按钮 -->
          <a-tooltip v-if="pkg?.status === 'DRAFT' && (pkg?.packageCount || 0) === 0" title="请先添加至少一个课程包">
            <span>
              <a-button disabled>提交审核</a-button>
            </span>
          </a-tooltip>
          <a-button
            v-else-if="(pkg?.status === 'DRAFT' || pkg?.status === 'REJECTED') && (pkg?.packageCount || 0) > 0"
            @click="handleSubmit"
          >
            提交审核
          </a-button>
          <!-- 发布按钮 -->
          <a-button v-if="pkg?.status === 'APPROVED'" type="primary" @click="handlePublish">发布</a-button>
          <!-- 下架按钮 -->
          <a-popconfirm
            v-if="pkg?.status === 'PUBLISHED'"
            title="确定要下架吗？"
            @confirm="handleOffline"
          >
            <a-button danger>下架</a-button>
          </a-popconfirm>
        </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="折扣类型">
          {{ getDiscountTypeText(pkg?.discountType) }}
        </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?.packageCount }}</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="packageColumns"
        :data-source="pkg?.packages || []"
        row-key="id"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="package-info">
              <span>{{ record.name }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'gradeLevels'">
            <a-tag v-for="grade in record.gradeLevels" :key="grade">{{ grade }}</a-tag>
          </template>
          <template v-else-if="column.key === 'sortOrder'">
            {{ record.sortOrder }}
          </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 { getCollectionDetail, submitCollection, publishCollection, archiveCollection } from '@/api/package';
import type { CourseCollection } from '@/api/package';
import * as collectionsApi from '@/api/collections';

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

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

const packageColumns = [
  { title: '课程包名称', key: 'name', dataIndex: 'name' },
  { title: '适用年级', key: 'gradeLevels', dataIndex: 'gradeLevels', width: 150 },
  { title: '排序', key: 'sortOrder', dataIndex: 'sortOrder', width: 80 },
];

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

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

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

const getDiscountTypeText = collectionsApi.getDiscountTypeText;

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

const fetchData = async () => {
  loading.value = true;
  try {
    const id = route.params.id as string;
    const res = await getCollectionDetail(id);
    console.log('套餐详情数据:', res);
    console.log('套餐状态:', res?.status);
    pkg.value = res;
  } catch (error) {
    console.error('获取套餐详情失败:', error);
    message.error('获取套餐详情失败');
  } finally {
    loading.value = false;
  }
};

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

const handleSubmit = async () => {
  if ((pkg.value?.packageCount || 0) === 0) {
    message.warning('套餐必须包含至少一个课程包，请先编辑添加');
    return;
  }
  try {
    await submitCollection(route.params.id as string);
    message.success('提交成功');
    fetchData();
  } catch (error: any) {
    message.error(error.response?.data?.message || '提交失败');
  }
};

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

const handleOffline = async () => {
  try {
    await archiveCollection(route.params.id as string);
    message.success('下架成功');
    fetchData();
  } catch (error) {
    message.error('下架失败');
  }
};

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

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

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

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