<template>
  <div class="collection-detail-container">
    <a-spin :spinning="loading">
      <a-card :title="collection?.name || '套餐详情'" :bordered="false">
        <template #extra>
          <a-space>
            <a-button @click="goBack">返回</a-button>

            <!-- 草稿状态：显示编辑、删除按钮 -->
            <template v-if="collection?.status === 'DRAFT'">
              <a-button type="primary" @click="editCollection">编辑</a-button>
              <a-popconfirm title="确定要删除此套餐吗？" @confirm="handleDelete">
                <a-button danger>删除</a-button>
              </a-popconfirm>
            </template>

            <!-- 待审核状态：显示查看、撤销按钮 -->
            <template v-else-if="collection?.status === 'PENDING'">
              <a-button @click="handleWithdraw">撤销审核</a-button>
            </template>

            <!-- 已通过状态：显示发布按钮 -->
            <template v-else-if="collection?.status === 'APPROVED'">
              <a-button type="primary" @click="handlePublish">发布</a-button>
            </template>

            <!-- 已发布状态：显示下架按钮 -->
            <template v-else-if="collection?.status === 'PUBLISHED'">
              <a-popconfirm title="确定要下架此套餐吗？下架后学校端将无法看到。" @confirm="handleArchive">
                <a-button danger>下架</a-button>
              </a-popconfirm>
            </template>

            <!-- 已下架状态：显示编辑、删除、重新发布按钮 -->
            <template v-else-if="collection?.status === 'ARCHIVED'">
              <a-button type="primary" @click="editCollection">编辑</a-button>
              <a-popconfirm title="确定要重新发布此套餐吗？" @confirm="handleRepublish">
                <a-button>重新发布</a-button>
              </a-popconfirm>
              <a-popconfirm title="确定要删除此套餐吗？" @confirm="handleDelete">
                <a-button danger>删除</a-button>
              </a-popconfirm>
            </template>

            <!-- 驳回状态：显示查看原因按钮 -->
            <template v-else-if="collection?.status === 'REJECTED'">
              <a-tooltip v-if="collection.reviewComment" :title="collection.reviewComment">
                <a-button>查看驳回原因</a-button>
              </a-tooltip>
            </template>
          </a-space>
        </template>

        <a-descriptions bordered :column="2" v-if="collection">
          <a-descriptions-item label="套餐名称">{{ collection.name }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(collection.status)">{{ getStatusText(collection.status) }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="价格">{{ formatPrice(collection.price) }}</a-descriptions-item>
          <a-descriptions-item label="优惠价">
            {{ formatPrice(collection.discountPrice) }}
          </a-descriptions-item>
          <a-descriptions-item label="折扣类型">{{ getDiscountTypeText(collection.discountType) }}</a-descriptions-item>
          <a-descriptions-item label="适用年级">
            <a-tag v-for="grade in collection.gradeLevels" :key="grade">{{ grade }}</a-tag>
            <span v-if="!collection.gradeLevels || collection.gradeLevels.length === 0">-</span>
          </a-descriptions-item>
          <a-descriptions-item label="课程包数量">{{ collection.packageCount || 0 }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatDate(collection.createdAt) }}</a-descriptions-item>
        </a-descriptions>

        <a-divider v-if="collection">套餐描述</a-divider>
        <p v-if="collection">{{ collection.description || '暂无描述' }}</p>

        <a-divider v-if="collection">
          <span>包含的课程包</span>
          <a-button
            v-if="collection.status === 'DRAFT'"
            type="primary"
            size="small"
            style="margin-left: 12px"
            @click="showAddPackageModal"
          >
            <PlusOutlined /> 添加课程包
          </a-button>
        </a-divider>
        <template v-if="collection">
          <template v-if="collection.packages && collection.packages.length > 0">
            <a-list
              :data-source="collection.packages"
              item-layout="horizontal"
            >
              <template #renderItem="{ item, index }">
                <a-list-item>
                  <a-list-item-meta :title="`${index + 1}. ${item.name}`" :description="item.description || '暂无描述'" />
                  <template #actions>
                    <a-popconfirm
                      v-if="collection.status === 'DRAFT'"
                      title="确定要移除此课程包吗？"
                      @confirm="handleRemovePackage(item.id)"
                    >
                      <a-button type="link" danger size="small">移除</a-button>
                    </a-popconfirm>
                  </template>
                </a-list-item>
              </template>
            </a-list>
          </template>
          <template v-else>
            <a-empty
              v-if="!collection.packageCount || collection.packageCount === 0"
              description="暂无课程包"
            >
              <a-button v-if="collection.status === 'DRAFT'" type="primary" @click="showAddPackageModal">
                添加课程包
              </a-button>
            </a-empty>
            <a-alert
              v-else
              type="warning"
              :message="`数据不一致：显示有 ${collection.packageCount} 个课程包，但未找到关联数据。请联系管理员检查数据库。`"
              show-icon
            />
          </template>
        </template>
      </a-card>
    </a-spin>

    <!-- 添加课程包弹窗 -->
    <a-modal
      v-model:open="addPackageModalVisible"
      title="添加课程包"
      :confirm-loading="addingPackage"
      @ok="handleAddPackage"
    >
      <a-form layout="vertical">
        <a-form-item label="选择课程包">
          <a-select
            v-model:value="selectedPackageId"
            placeholder="请选择要添加的课程包"
            :loading="loadingPackages"
            :options="availablePackages.map(p => ({ label: p.name, value: p.id }))"
            show-search
            :filter-option="(input, option) => option.label.toLowerCase().includes(input.toLowerCase())"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

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

const collection = ref<collectionsApi.Collection | null>(null);
const loading = ref(false);

// 添加课程包相关
const addPackageModalVisible = ref(false);
const addingPackage = ref(false);
const selectedPackageId = ref<number | undefined>(undefined);
const loadingPackages = ref(false);
const availablePackages = ref<any[]>([]);

const loadCollection = async () => {
  loading.value = true;
  collection.value = null;
  try {
    const id = route.params.id;
    collection.value = await collectionsApi.getCollection(id);
  } catch (error) {
    console.error('加载套餐详情失败:', error);
    message.error('加载失败: ' + (error as any).message);
  } finally {
    loading.value = false;
  }
};

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

const goBack = () => {
  router.back();
};

const formatPrice = (price: number | null | undefined) => {
  return collectionsApi.formatPrice(price);
};

const formatDate = (date: string) => {
  return collectionsApi.formatDate(date);
};

const getStatusColor = (status: string) => {
  return collectionsApi.getCollectionStatusInfo(status).color;
};

const getStatusText = (status: string) => {
  return collectionsApi.getCollectionStatusInfo(status).label;
};

const getDiscountTypeText = collectionsApi.getDiscountTypeText;

// 删除套餐
const handleDelete = async () => {
  try {
    await collectionsApi.deleteCollection(route.params.id);
    message.success('删除成功');
    router.push('/admin/collections');
  } catch (error) {
    message.error('删除失败');
  }
};

// 发布套餐
const handlePublish = async () => {
  try {
    await collectionsApi.publishCollection(route.params.id);
    message.success('发布成功');
    loadCollection();
  } catch (error) {
    message.error('发布失败');
  }
};

// 下架套餐
const handleArchive = async () => {
  try {
    await collectionsApi.archiveCollection(route.params.id);
    message.success('下架成功');
    loadCollection();
  } catch (error: any) {
    const errorMsg = error?.message || '下架失败';
    message.error(errorMsg);
  }
};

// 重新发布
const handleRepublish = async () => {
  try {
    await collectionsApi.republishCollection(route.params.id);
    message.success('重新发布成功');
    loadCollection();
  } catch (error) {
    message.error('重新发布失败');
  }
};

// 撤销审核
const handleWithdraw = async () => {
  try {
    await collectionsApi.withdrawCollection(route.params.id);
    message.success('已撤销');
    loadCollection();
  } catch (error) {
    message.error('撤销失败');
  }
};

// 显示添加课程包弹窗
const showAddPackageModal = async () => {
  addPackageModalVisible.value = true;
  loadingPackages.value = true;
  try {
    // 获取所有已发布的课程包
    const data = await packagesApi.getCourses({ status: 'PUBLISHED', pageSize: 1000 });
    // 过滤掉已经添加的课程包
    const existingPackageIds = collection.value?.packages?.map(p => p.id) || [];
    availablePackages.value = (data as any).items?.filter((p: any) => !existingPackageIds.includes(p.id)) || [];
  } catch (error) {
    console.error('获取课程包列表失败:', error);
    message.error('获取课程包列表失败');
  } finally {
    loadingPackages.value = false;
  }
};

// 添加课程包
const handleAddPackage = async () => {
  if (!selectedPackageId.value) {
    message.warning('请选择课程包');
    return;
  }

  addingPackage.value = true;
  try {
    // 获取当前课程包列表（去重）
    const currentPackageIds = [...new Set(collection.value?.packages?.map(p => p.id) || [])];
    // 添加新的课程包ID（避免重复）
    const newPackageIds = currentPackageIds.includes(selectedPackageId.value)
      ? currentPackageIds
      : [...currentPackageIds, selectedPackageId.value];

    await collectionsApi.setCollectionPackages(route.params.id, newPackageIds);
    message.success('添加成功');
    addPackageModalVisible.value = false;
    selectedPackageId.value = undefined;
    loadCollection();
  } catch (error) {
    message.error('添加失败');
  } finally {
    addingPackage.value = false;
  }
};

// 移除课程包
const handleRemovePackage = async (packageId: number) => {
  try {
    // 获取当前课程包列表（去重），移除指定的课程包
    const currentPackageIds = [...new Set(collection.value?.packages?.map(p => p.id) || [])];
    const newPackageIds = currentPackageIds.filter(id => id !== packageId);

    await collectionsApi.setCollectionPackages(route.params.id, newPackageIds);
    message.success('移除成功');
    loadCollection();
  } catch (error) {
    message.error('移除失败');
  }
};

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

<style scoped>
.collection-detail-container {
  padding: 24px;
}
</style>
