<template>
  <div class="collection-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="PUBLISHED">已发布</a-select-option>
          <a-select-option value="ARCHIVED">已下架</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'">
            {{ formatPrice(record.price) }}
          </template>
          <template v-else-if="column.key === 'discountPrice'">
            {{ formatPrice(record.discountPrice) }}
          </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>
              <!-- 草稿状态 -->
              <template v-if="record.status === 'DRAFT'">
                <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
                <a-tooltip v-if="(record.packageCount || 0) === 0" title="请先添加至少一个课程包">
                  <span>
                    <a-button type="primary" size="small" disabled>发布</a-button>
                  </span>
                </a-tooltip>
                <a-popconfirm v-else title="确定要发布此套餐吗？发布后学校端将可以查看。" @confirm="handlePublish(record)">
                  <a-button type="primary" size="small">发布</a-button>
                </a-popconfirm>
                <a-popconfirm title="确定要删除吗？" @confirm="handleDelete(record)">
                  <a-button type="link" size="small" danger>删除</a-button>
                </a-popconfirm>
              </template>

              <!-- 待审核状态 -->
              <template v-else-if="record.status === 'PENDING'">
                <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                <a-button type="link" size="small" @click="handleWithdraw(record)">撤销</a-button>
              </template>

              <!-- 已驳回状态 -->
              <template v-else-if="record.status === 'REJECTED'">
                <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                <a-button type="link" size="small" @click="handleEdit(record)">修改</a-button>
                <a-tooltip v-if="(record.packageCount || 0) === 0" title="请先添加至少一个课程包">
                  <span>
                    <a-button type="primary" size="small" disabled>发布</a-button>
                  </span>
                </a-tooltip>
                <a-popconfirm v-else title="确定要发布此套餐吗？发布后学校端将可以查看。" @confirm="handlePublish(record)">
                  <a-button type="primary" size="small">发布</a-button>
                </a-popconfirm>
              </template>

              <!-- 已通过状态 -->
              <template v-else-if="record.status === 'APPROVED'">
                <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                <a-button type="primary" size="small" @click="handlePublish(record)">发布</a-button>
              </template>

              <!-- 已发布状态 -->
              <template v-else-if="record.status === 'PUBLISHED'">
                <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                <a-popconfirm title="确定要下架吗？" @confirm="handleArchive(record)">
                  <a-button type="link" size="small" danger>下架</a-button>
                </a-popconfirm>
              </template>

              <!-- 已下架状态 -->
              <template v-else-if="record.status === 'ARCHIVED'">
                <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
                <a-popconfirm title="确定要重新发布吗？" @confirm="handleRepublish(record)">
                  <a-button type="primary" size="small">重新发布</a-button>
                </a-popconfirm>
                <a-popconfirm title="确定要删除吗？" @confirm="handleDelete(record)">
                  <a-button type="link" size="small" danger>删除</a-button>
                </a-popconfirm>
              </template>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {useRouter} from 'vue-router';
import {message} from 'ant-design-vue';
import {PlusOutlined} from '@ant-design/icons-vue';
import * as collectionsApi from '@/api/collections';

const router = useRouter();

const loading = ref(false);
const dataSource = ref<collectionsApi.Collection[]>([]);
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: '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: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 200 },
];

const getStatusColor = (status: string) => collectionsApi.getCollectionStatusInfo(status).color;
const getStatusText = (status: string) => collectionsApi.getCollectionStatusInfo(status).label;
const formatPrice = (price: number | null | undefined) => collectionsApi.formatPrice(price);
const getDiscountTypeText = collectionsApi.getDiscountTypeText;

const parseGradeLevels = (gradeLevels: string | string[]) => {
  return collectionsApi.parseGradeLevels(gradeLevels);
};

const fetchData = async () => {
  loading.value = true;
  try {
    const data = await collectionsApi.getCollections({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...(filters.status ? { status: filters.status } : {}),
    });
    dataSource.value = data.items;
    pagination.total = Number(data.total);
  } catch (error) {
    console.error('获取套餐列表失败', error);
    message.error('获取套餐列表失败');
  } finally {
    loading.value = false;
  }
};

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

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

const handleView = (record: collectionsApi.Collection) => {
  router.push(`/admin/collections/${record.id}`);
};

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

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

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

const handleWithdraw = async (record: collectionsApi.Collection) => {
  try {
    await collectionsApi.withdrawCollection(record.id);
    message.success('已撤销');
    fetchData();
  } catch (error) {
    message.error('撤销失败');
  }
};

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

const handleRepublish = async (record: collectionsApi.Collection) => {
  try {
    await collectionsApi.republishCollection(record.id);
    message.success('重新发布成功');
    fetchData();
  } catch (error) {
    message.error('重新发布失败');
  }
};

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

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

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