<template>
  <div class="package-list-page">
    <a-card :bordered="false">
      <template #title>
        <span>课程套餐管理</span>
      </template>
      <template #extra>
        <a-space>
          <a-button @click="$router.push('/admin/packages/review')">
            <AuditOutlined /> 审核管理
            <a-badge v-if="pendingCount > 0" :count="pendingCount" :offset="[10, 0]" />
          </a-button>
          <a-button type="primary" @click="handleCreate">
            <template #icon><PlusOutlined /></template>
            新建课程套餐
          </a-button>
        </a-space>
      </template>

      <!-- 筛选 -->
      <div class="filter-section">
        <a-space>
          <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">待审核</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>
          <a-select
            v-model:value="filters.gradeLevels"
            placeholder="适用年级"
            style="width: 150px"
            allowClear
            mode="multiple"
            @change="fetchData"
          >
            <a-select-option value="小班">小班</a-select-option>
            <a-select-option value="中班">中班</a-select-option>
            <a-select-option value="大班">大班</a-select-option>
          </a-select>
        </a-space>
      </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 === 'discountPrice'">
            {{ record.discountPrice ? '¥' + (record.discountPrice / 100).toFixed(2) : '-' }}
          </template>
          <template v-else-if="column.key === 'discountType'">
            {{ getDiscountTypeText(record.discountType) }}
          </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' || record.status === 'REJECTED'"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>
              <a-tooltip v-if="(record.status === 'DRAFT' || record.status === 'REJECTED') && (record.packageCount || 0) === 0" title="请先添加至少一个课程包">
                <span>
                  <a-button type="link" size="small" disabled>提交</a-button>
                </span>
              </a-tooltip>
              <a-button
                v-else-if="record.status === 'DRAFT' || record.status === 'REJECTED'"
                type="link"
                size="small"
                @click="handleSubmit(record)"
              >
                提交
              </a-button>
              <a-button
                type="link"
                size="small"
                v-if="record.status === 'PENDING'"
                @click="handleReview(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 === 'PUBLISHED'"
                title="确定要下架吗？"
                @confirm="handleOffline(record)"
              >
                <a-button type="link" size="small">下架</a-button>
              </a-popconfirm>
              <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, AuditOutlined } from '@ant-design/icons-vue';
import { getCollectionList, deleteCollection, submitCollection, publishCollection, archiveCollection } from '@/api/package';
import type { CourseCollection } from '@/api/package';
import * as collectionsApi from '@/api/collections';

const router = useRouter();

const loading = ref(false);
const dataSource = ref<CourseCollection[]>([]);
const pendingCount = ref(0);
const filters = reactive({
  status: undefined as string | undefined,
  gradeLevels: 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: 'discountPrice', key: 'discountPrice', width: 100 },
  { title: '折扣类型', dataIndex: 'discountType', key: 'discountType', width: 100 },
  { title: '适用年级', dataIndex: 'gradeLevels', key: 'gradeLevels', width: 150 },
  { title: '课程包数', dataIndex: 'packageCount', key: 'packageCount', width: 80 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 200 },
];

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 parseGradeLevels = (gradeLevels: string | string[] | undefined): string[] => {
  if (!gradeLevels) return [];
  if (Array.isArray(gradeLevels)) {
    if (gradeLevels.length === 0) return [];
    if (gradeLevels[0]?.toString().startsWith('[')) {
      try {
        return JSON.parse(gradeLevels.join(''));
      } catch {
        return [];
      }
    }
    return gradeLevels;
  }
  try {
    return JSON.parse(gradeLevels || '[]');
  } catch {
    return [];
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getCollectionList({
      status: filters.status,
      gradeLevels: filters.gradeLevels?.join(','),
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    }) as any;
    dataSource.value = res.list || [];
    pagination.total = Number(res.total) || 0;
    // 获取待审核数量
    try {
      const pendingRes = await getCollectionList({ status: 'PENDING', pageNum: 1, pageSize: 1 }) as any;
      pendingCount.value = Number(pendingRes.total) || 0;
    } catch {
      pendingCount.value = 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 handleReview = (_record: any) => {
  router.push('/admin/packages/review');
};

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

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

const handleOffline = async (record: any) => {
  try {
    await archiveCollection(record.id);
    message.success('下架成功');
    fetchData();
  } catch (error) {
    message.error('下架失败');
  }
};

const handleDelete = async (record: any) => {
  try {
    await deleteCollection(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>
