<template>
  <div class="bundle-edit-page">
    <a-card :bordered="false">
      <template #title>
        <span>{{ isEdit ? '编辑套餐' : '创建套餐' }}</span>
      </template>
      <template #extra>
        <a-button @click="routerBack()">返回</a-button>
      </template>

      <a-form
        :model="form"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        @finish="handleSave"
      >
        <a-form-item label="套餐名称" name="name" :rules="[{ required: true, message: '请输入套餐名称' }]">
          <a-input v-model:value="form.name" placeholder="请输入套餐名称" />
        </a-form-item>

        <a-form-item label="套餐描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入套餐描述" :rows="3" />
        </a-form-item>

        <a-form-item label="封面图片 URL" name="coverUrl">
          <a-input v-model:value="form.coverUrl" placeholder="请输入封面图片 URL" />
        </a-form-item>

        <a-form-item label="价格（元）" name="price" :rules="[{ required: true, message: '请输入价格' }]">
          <a-input-number v-model:value="form.price" :min="0" :precision="2" style="width: 200px" />
        </a-form-item>

        <a-form-item label="优惠价（元）" name="discountPrice">
          <a-input-number v-model:value="form.discountPrice" :min="0" :precision="2" style="width: 200px" />
        </a-form-item>

        <a-form-item label="优惠类型" name="discountType">
          <a-select v-model:value="form.discountType" placeholder="请选择优惠类型" allowClear style="width: 200px">
            <a-select-option value="PERCENT">折扣</a-select-option>
            <a-select-option value="FIXED">立减</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="适用年级" name="gradeLevels" :rules="[{ required: true, message: '请选择适用年级' }]">
          <a-select v-model:value="form.gradeLevels" mode="multiple" placeholder="请选择适用年级" style="width: 300px">
            <a-select-option value="小班">小班</a-select-option>
            <a-select-option value="中班">中班</a-select-option>
            <a-select-option value="大班">大班</a-select-option>
          </a-select>
        </a-form-item>

        <a-divider>课程包配置</a-divider>

        <a-form-item label="已选课程包">
          <div class="course-list">
            <a-table
              :columns="courseColumns"
              :data-source="selectedPackages"
              row-key="id"
              size="small"
              :pagination="false"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'sortOrder'">
                  <a-input-number v-model:value="record.sortOrder" :min="0" size="small" />
                </template>
                <template v-else-if="column.key === 'gradeLevel'">
                  <a-select v-model:value="record.gradeLevel" size="small" style="width: 100px">
                    <a-select-option value="小班">小班</a-select-option>
                    <a-select-option value="中班">中班</a-select-option>
                    <a-select-option value="大班">大班</a-select-option>
                  </a-select>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button type="link" size="small" danger @click="removePackage(index)">移除</a-button>
                </template>
              </template>
            </a-table>
            <a-button type="dashed" block style="margin-top: 16px" @click="showPackageSelector = true">
              <template #icon><PlusOutlined /></template>
              添加课程包
            </a-button>
          </div>
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-space>
            <a-button type="primary" html-type="submit" :loading="saving">保存</a-button>
            <a-button @click="routerBack()">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 课程包选择器 -->
    <a-modal
      v-model:open="showPackageSelector"
      title="选择课程包"
      width="800px"
      @ok="handleAddPackages"
    >
      <a-table
        :columns="selectorColumns"
        :data-source="availablePackages"
        :row-selection="rowSelection"
        row-key="id"
        size="small"
        :loading="loadingPackages"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'courseCount'">
            {{ record.courseCount }} 个课程
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import {
  getBundleDetail,
  createBundle,
  updateBundle,
  getBundleCoursePackages,
  addBundleCoursePackage,
  removeBundleCoursePackage,
  updateBundleCoursePackageSort,
} from '@/api/productBundle';
import { getPackages } from '@/api/package';

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

const isEdit = computed(() => !!route.params.id);
const bundleId = computed(() => String(route.params.id));

const saving = ref(false);
const loadingPackages = ref(false);
const showPackageSelector = ref(false);
const availablePackages = ref<any[]>([]);
const selectedRowKeys = ref<string[]>([]);

const form = reactive({
  name: '',
  description: '',
  coverUrl: '',
  price: 0,
  discountPrice: undefined as number | undefined,
  discountType: undefined as string | undefined,
  gradeLevels: [] as string[],
});

const selectedPackages = ref<{
  id: string;
  coursePackageId: string;
  gradeLevel: string;
  sortOrder: number;
  coursePackageName: string;
}[]>([]);

const courseColumns = [
  { title: '课程包', dataIndex: 'coursePackageName', key: 'coursePackageName' },
  { title: '年级', dataIndex: 'gradeLevel', key: 'gradeLevel', width: 120 },
  { title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 80 },
  { title: '操作', key: 'action', width: 80 },
];

const selectorColumns = [
  { title: '课程包名称', dataIndex: 'name', key: 'name' },
  { title: '课程数量', dataIndex: 'courseCount', key: 'courseCount', width: 100 },
  { title: '描述', dataIndex: 'description', key: 'description' },
];

const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: (string | number)[]) => {
    selectedRowKeys.value = keys as string[];
  },
}));

const routerBack = () => {
  if (isEdit.value) {
    router.push(`/admin/bundles/${bundleId.value}`);
  } else {
    router.push('/admin/bundles');
  }
};

const fetchBundleDetail = async () => {
  if (!isEdit.value) return;

  try {
    const bundle = await getBundleDetail(bundleId.value) as any;
    form.name = bundle.name;
    form.description = bundle.description || '';
    form.coverUrl = bundle.coverUrl || '';
    form.price = bundle.price / 100;
    form.discountPrice = bundle.discountPrice ? bundle.discountPrice / 100 : undefined;
    form.discountType = bundle.discountType;
    form.gradeLevels = JSON.parse(bundle.gradeLevels || '[]');

    // 加载关联的课程包
    const packagesRes = await getBundleCoursePackages(bundleId.value) as any;
    selectedPackages.value = (packagesRes.data || []).map((p: any) => ({
      id: p.id,
      coursePackageId: p.coursePackageId,
      coursePackageName: p.coursePackage?.name || '未知课程包',
      gradeLevel: p.gradeLevel || '小班',
      sortOrder: p.sortOrder || 0,
    }));
  } catch (error) {
    console.error('获取套餐详情失败', error);
    message.error('获取套餐详情失败');
  }
};

const fetchAvailablePackages = async () => {
  loadingPackages.value = true;
  try {
    const res = await getPackages({ page: 1, pageSize: 100 }) as any;
    availablePackages.value = res.data?.items || [];
  } catch (error) {
    console.error('获取课程包列表失败', error);
  } finally {
    loadingPackages.value = false;
  }
};

const handleAddPackages = async () => {
  const existingIds = new Set(selectedPackages.value.map((p) => p.coursePackageId));
  const newPackages = availablePackages.value
    .filter((p) => selectedRowKeys.value.includes(p.id) && !existingIds.has(p.id))
    .map((p) => ({
      id: '', // 新建时 ID 为空
      coursePackageId: p.id,
      coursePackageName: p.name,
      gradeLevel: '小班',
      sortOrder: selectedPackages.value.length,
    }));

  selectedPackages.value.push(...newPackages);
  selectedRowKeys.value = [];
  showPackageSelector.value = false;
};

const removePackage = async (index: number) => {
  const pkg = selectedPackages.value[index];
  if (pkg.id && isEdit.value) {
    try {
      await removeBundleCoursePackage(bundleId.value, pkg.id);
      message.success('移除成功');
    } catch (error) {
      message.error('移除失败');
      return;
    }
  }
  selectedPackages.value.splice(index, 1);
};

const handleSave = async () => {
  saving.value = true;
  try {
    const data = {
      name: form.name,
      description: form.description,
      coverUrl: form.coverUrl,
      price: Math.round(form.price * 100),
      discountPrice: form.discountPrice ? Math.round(form.discountPrice * 100) : undefined,
      discountType: form.discountType,
      gradeLevels: form.gradeLevels,
    };

    let id = bundleId.value;
    if (isEdit.value) {
      await updateBundle(id, data);

      // 同步课程包关联
      for (const pkg of selectedPackages.value) {
        if (!pkg.id) {
          // 新增关联
          await addBundleCoursePackage(id, {
            coursePackageId: pkg.coursePackageId,
            gradeLevel: pkg.gradeLevel,
          });
        } else {
          // 更新关联
          await updateBundleCoursePackageSort(id, pkg.id, pkg.sortOrder);
        }
      }
    } else {
      const res = await createBundle(data) as any;
      id = res.data.id;

      // 添加课程包关联
      for (const pkg of selectedPackages.value) {
        await addBundleCoursePackage(id, {
          coursePackageId: pkg.coursePackageId,
          gradeLevel: pkg.gradeLevel,
        });
      }
    }

    message.success('保存成功');
    router.push(`/admin/bundles/${id}`);
  } catch (error) {
    console.error('保存失败', error);
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  fetchBundleDetail();
  fetchAvailablePackages();
});
</script>

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

.course-list {
  width: 100%;
}
</style>
