<template>
  <div class="package-list-page">
    <a-card :bordered="false">
      <template #title>
        <span>课程套餐管理</span>
      </template>
      <template #extra>
        <a-button type="primary" @click="handleCreate">
          <template #icon><PlusOutlined /></template>
          新建套餐
        </a-button>
      </template>

      <!-- 筛选 -->
      <div class="filter-section">
        <a-select
          v-model:value="filters.status"
          placeholder="状态筛选"
          style="width: 150px"
          allowClear
          @change="fetchData"
        >
          <a-select-option value="DRAFT">草稿</a-select-option>
          <a-select-option value="PENDING_REVIEW">待审核</a-select-option>
          <a-select-option value="APPROVED">已通过</a-select-option>
          <a-select-option value="REJECTED">已拒绝</a-select-option>
          <a-select-option value="PUBLISHED">已发布</a-select-option>
          <a-select-option value="OFFLINE">已下架</a-select-option>
        </a-select>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'price'">
            ¥{{ (record.price / 100).toFixed(2) }}
          </template>
          <template v-else-if="column.key === 'gradeLevels'">
            <a-tag v-for="grade in parseGradeLevels(record.gradeLevels)" :key="grade">{{ grade }}</a-tag>
          </template>
          <template v-else-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="handleView(record)">查看</a-button>
              <a-button
                type="link"
                size="small"
                v-if="record.status === 'DRAFT'"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                v-if="record.status === 'DRAFT'"
                @click="handleSubmit(record)"
              >
                提交
              </a-button>
              <a-button
                type="link"
                size="small"
                v-if="record.status === 'APPROVED'"
                @click="handlePublish(record)"
              >
                发布
              </a-button>
              <a-popconfirm
                v-if="record.status === 'DRAFT'"
                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, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { getPackageList, deletePackage, submitPackage, publishPackage } from '@/api/package';
import type { CoursePackage } from '@/api/package';

const router = useRouter();

const loading = ref(false);
const dataSource = ref<CoursePackage[]>([]);
const filters = reactive({
  status: undefined as string | undefined,
});
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '套餐名称', dataIndex: 'name', key: 'name' },
  { title: '价格', dataIndex: 'price', key: 'price', width: 100 },
  { title: '适用年级', dataIndex: 'gradeLevels', key: 'gradeLevels', width: 150 },
  { title: '课程数', dataIndex: 'courseCount', key: 'courseCount', width: 80 },
  { title: '使用学校数', dataIndex: 'tenantCount', key: 'tenantCount', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 200 },
];

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 parseGradeLevels = (gradeLevels: string | string[]) => {
  if (Array.isArray(gradeLevels)) return gradeLevels;
  try {
    return JSON.parse(gradeLevels || '[]');
  } catch {
    return [];
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getPackageList({
      status: filters.status,
      page: pagination.current,
      pageSize: pagination.pageSize,
    }) as any;
    dataSource.value = res.items || [];
    pagination.total = res.total || 0;
  } catch (error) {
    console.error('获取套餐列表失败', error);
  } finally {
    loading.value = false;
  }
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchData();
};

const handleCreate = () => {
  router.push('/admin/packages/create');
};

const handleView = (record: any) => {
  router.push(`/admin/packages/${record.id}`);
};

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

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

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

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

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

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

.filter-section {
  margin-bottom: 16px;
}
</style>
