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

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

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

      <a-table
        :columns="packageColumns"
        :data-source="packageList"
        row-key="id"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'package'">
            <div class="package-info">
              <span>{{ record.coursePackage?.name || '-' }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'gradeLevel'">
            <a-tag>{{ record.gradeLevel || '-' }}</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 {
  getBundleDetail,
  submitBundle,
  publishBundle,
  offlineBundle,
  getBundleCoursePackages,
  type ProductBundle,
} from '@/api/productBundle';

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

const loading = ref(false);
const bundle = ref<ProductBundle | null>(null);
const packageList = ref<any[]>([]);

const packageColumns = [
  { title: '课程包', key: 'package', width: 300 },
  { title: '适用年级', dataIndex: 'gradeLevel', key: 'gradeLevel', width: 120 },
  { title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', 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 getDiscountTypeText = (type?: string) => {
  if (!type) return '-';
  const map: Record<string, string> = {
    PERCENT: '折扣',
    FIXED: '立减',
  };
  return map[type] || type;
};

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

const parseGradeLevels = (gradeLevels: string | string[] | undefined) => {
  if (!gradeLevels) return [];
  if (Array.isArray(gradeLevels)) return gradeLevels;
  try {
    return JSON.parse(gradeLevels);
  } catch {
    return [];
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const id = String(route.params.id);
    const [bundleRes, packagesRes] = await Promise.all([
      getBundleDetail(id),
      getBundleCoursePackages(id),
    ]);

    bundle.value = bundleRes as any;
    packageList.value = (packagesRes as any).data || [];
  } catch (error) {
    console.error('获取套餐详情失败', error);
    message.error('获取套餐详情失败');
  } finally {
    loading.value = false;
  }
};

const routerBack = () => {
  router.push('/admin/bundles');
};

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

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

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

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

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

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

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