<template>
  <div class="collection-edit-container">
    <a-card :title="isEdit ? '编辑课程套餐' : '创建课程套餐'" :bordered="false">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="套餐名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入套餐名称" />
        </a-form-item>

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

        <a-form-item label="价格（元）" name="price">
          <a-input-number v-model:value="formState.price" :min="0" :precision="2" style="width: 100%" />
        </a-form-item>

        <a-form-item label="优惠价（元）" name="discountPrice">
          <a-space>
            <a-input-number
              v-model:value="formState.discountPrice"
              :min="0"
              :precision="2"
              style="width: 100%"
              :placeholder="getDiscountPricePlaceholder()"
            />
            <span v-if="formState.discountType" class="discount-hint" :style="{ color: getDiscountPriceHintColor() }">
              {{ getDiscountPriceHint() }}
            </span>
          </a-space>
        </a-form-item>

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

        <a-form-item label="适用年级" name="gradeLevels">
          <a-checkbox-group v-model:value="formState.gradeLevels">
            <a-checkbox value="小班">小班</a-checkbox>
            <a-checkbox value="中班">中班</a-checkbox>
            <a-checkbox value="大班">大班</a-checkbox>
          </a-checkbox-group>
        </a-form-item>

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

        <a-form-item label="已选课程包">
          <div class="package-list">
            <a-table
              :columns="packageColumns"
              :data-source="selectedPackages"
              row-key="packageId"
              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: 6, span: 18 }">
          <a-space>
            <a-button type="primary" @click="handleSubmit" :loading="loading">
              {{ isEdit ? '保存' : '创建' }}
            </a-button>
            <a-button @click="handleCancel">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 课程包选择器 -->
    <a-modal
      v-model:open="showPackageSelector"
      title="选择课程包"
      width="800px"
      :confirm-loading="addingPackages"
      @ok="handleAddPackages"
    >
      <a-table
        :columns="selectorColumns"
        :data-source="availablePackages"
        :row-selection="rowSelection"
        row-key="id"
        size="small"
        :loading="loadingPackages"
        :pagination="{
          current: selectorPagination.current,
          pageSize: selectorPagination.pageSize,
          total: selectorPagination.total,
          showSizeChanger: true,
          showTotal: (t: number) => `共 ${t} 条`,
          onChange: (page: number, size: number) => {
            selectorPagination.current = page;
            selectorPagination.pageSize = size;
            fetchAvailablePackages();
          },
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'gradeTags'">
            <a-tag v-for="tag in parseGradeTags(record.gradeTags)" :key="tag">{{ tag }}</a-tag>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { getCollectionDetail, createCollection, updateCollection, setCollectionPackages, getCoursePackageList, getCoursePackage } from '@/api/package';

const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();

const isEdit = computed(() => !!route.params.id);
const collectionId = computed(() => route.params.id as string | undefined);

const loading = ref(false);
const loadingPackages = ref(false);
const showPackageSelector = ref(false);
const availablePackages = ref<any[]>([]);
const selectedRowKeys = ref<(number | string)[]>([]);
const selectorPagination = reactive({ current: 1, pageSize: 10, total: 0 });
const addingPackages = ref(false);

const formState = ref({
  name: '',
  description: '',
  price: 0,
  discountPrice: null as number | null,
  discountType: null as string | null,
  gradeLevels: [] as string[],
});

const selectedPackages = ref<{ packageId: number | string; gradeLevel: string; sortOrder: number; packageName: string }[]>([]);

const formRules = {
  name: [{ required: true, message: '请输入套餐名称' }],
  price: [{ required: true, message: '请输入价格' }],
};

const packageColumns = [
  { title: '课程包', dataIndex: 'packageName', key: 'packageName' },
  { 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: 'gradeTags', key: 'gradeTags' },
  { title: '时长', dataIndex: 'duration', key: 'duration', width: 80 },
];

const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[]) => {
    selectedRowKeys.value = keys;
  },
}));

const parseGradeTags = (tags: string | string[]) => {
  if (Array.isArray(tags)) return tags;
  try {
    return JSON.parse(tags || '[]');
  } catch {
    return [];
  }
};

// 获取折扣价格输入框的 placeholder
const getDiscountPricePlaceholder = () => {
  if (!formState.value.discountType) return '请先选择优惠类型';
  if (formState.value.discountType === 'PERCENTAGE') return '请输入折扣率（0-100）';
  if (formState.value.discountType === 'FIXED') return '请输入立减金额';
  return '';
};

// 获取折扣价格提示文本
const getDiscountPriceHint = () => {
  if (!formState.value.discountType || !formState.value.price) return '';
  if (formState.value.discountType === 'PERCENTAGE') {
    if (formState.value.discountPrice !== undefined && formState.value.discountPrice !== null) {
      const finalPrice = formState.value.price * (1 - (formState.value.discountPrice / 100));
      if (finalPrice < 0) {
        return '折后价不能小于 0';
      }
      return `折后价：¥${finalPrice.toFixed(2)}`;
    }
    return '按百分比减免';
  }
  if (formState.value.discountType === 'FIXED') {
    if (formState.value.discountPrice !== undefined && formState.value.discountPrice !== null) {
      const finalPrice = formState.value.price - formState.value.discountPrice;
      if (finalPrice < 0) {
        return '立减金额超过原价';
      }
      return `折后价：¥${finalPrice.toFixed(2)}`;
    }
    return '按固定金额减免';
  }
  return '';
};

// 获取折扣价格提示文本的颜色
const getDiscountPriceHintColor = () => {
  if (!formState.value.discountType || !formState.value.price || !formState.value.discountPrice) return '#666';
  if (formState.value.discountType === 'PERCENTAGE') {
    const finalPrice = formState.value.price * (1 - (formState.value.discountPrice / 100));
    return finalPrice < 0 ? 'red' : '#666';
  }
  if (formState.value.discountType === 'FIXED') {
    const finalPrice = formState.value.price - formState.value.discountPrice;
    return finalPrice < 0 ? 'red' : '#666';
  }
  return '#666';
};

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

  try {
    const detail = await getCollectionDetail(collectionId.value!);
    formState.value.name = detail.name;
    formState.value.description = detail.description || '';
    formState.value.price = (detail.price || 0) / 100;  // 分转元
    formState.value.discountPrice = detail.discountPrice ? detail.discountPrice / 100 : null;
    formState.value.discountType = detail.discountType || null;
    // 解析年级，后端是 String[] 数组类型，直接使用或转为数组
    if (detail.gradeLevels) {
      formState.value.gradeLevels = Array.isArray(detail.gradeLevels)
        ? detail.gradeLevels
        : detail.gradeLevels.split(',');
    }

    // 加载已选课程包
    selectedPackages.value = (detail.packages || []).map((p: any) => ({
      packageId: p.id,
      packageName: p.name,
      gradeLevel: p.gradeLevels?.[0] || '小班',
      sortOrder: p.sortOrder,
    }));
  } catch (error) {
    console.error('获取套餐详情失败:', error);
    message.error('获取套餐详情失败');
  }
};

const fetchAvailablePackages = async () => {
  loadingPackages.value = true;
  try {
    const res = await getCoursePackageList({
      pageNum: selectorPagination.current,
      pageSize: selectorPagination.pageSize,
      status: 'PUBLISHED',
    });
    availablePackages.value = res.list || [];
    selectorPagination.total = res.total || 0;
  } catch (error) {
    console.error('获取课程包列表失败', error);
  } finally {
    loadingPackages.value = false;
  }
};

// 打开选择弹窗时：回显已选课程包，加载第一页数据
watch(showPackageSelector, (visible) => {
  if (visible) {
    selectedRowKeys.value = selectedPackages.value.map((p) => p.packageId);
    selectorPagination.current = 1;
    fetchAvailablePackages();
  }
});

const handleAddPackages = async () => {
  const existingIds = new Set(selectedPackages.value.map((p) => p.packageId));
  const idsToAdd = selectedRowKeys.value.filter((id) => !existingIds.has(id));
  if (idsToAdd.length === 0) {
    showPackageSelector.value = false;
    return;
  }

  addingPackages.value = true;
  try {
    const pkgMap = new Map(availablePackages.value.map((p) => [p.id, p]));
    const newPackages: { packageId: number | string; packageName: string; gradeLevel: string; sortOrder: number }[] = [];
    let sortOrder = selectedPackages.value.length;

    for (const id of idsToAdd) {
      let pkg = pkgMap.get(id);
      if (!pkg) {
        try {
          pkg = await getCoursePackage(id);
        } catch {
          continue;
        }
      }
      newPackages.push({
        packageId: pkg.id,
        packageName: pkg.name,
        gradeLevel: parseGradeTags(pkg.gradeTags)?.[0] || '小班',
        sortOrder: sortOrder++,
      });
    }

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

const removePackage = (index: number) => {
  selectedPackages.value.splice(index, 1);
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 手动触发表单校验
    await formRef.value.validate();

    // 校验折扣价格逻辑：折扣减免后价格不能小于 0
    if (formState.value.discountPrice !== undefined && formState.value.discountPrice !== null) {
      if (formState.value.discountType === 'PERCENTAGE') {
        // 折扣类型：折扣率应该是 0-100 之间的数值
        if (formState.value.discountPrice < 0 || formState.value.discountPrice > 100) {
          message.error('折扣率应该在 0-100 之间');
          return;
        }
      } else if (formState.value.discountType === 'FIXED') {
        // 立减类型：立减金额不能超过原价
        if (formState.value.discountPrice > formState.value.price) {
          message.error('立减金额不能超过原价');
          return;
        }
      }
    }

    loading.value = true;
    const data = {
      name: formState.value.name,
      description: formState.value.description,
      price: Math.round(formState.value.price * 100),  // 元转分
      discountPrice: formState.value.discountPrice ? Math.round(formState.value.discountPrice * 100) : undefined,
      discountType: formState.value.discountType || undefined,
      gradeLevels: formState.value.gradeLevels,
    };

    console.log('套餐请求数据:', data);

    let id: number | string;
    if (isEdit.value) {
      // 更新套餐
      id = collectionId.value!;
      await updateCollection(id, data);
    } else {
      // 创建套餐
      const res = await createCollection(data) as any;
      console.log('套餐创建响应:', res);
      id = res.id;
    }

    // 保存课程包关联
    if (selectedPackages.value.length > 0) {
      await setCollectionPackages(
        id,
        selectedPackages.value.map((p) => p.packageId),
      );
    }

    message.success(isEdit.value ? '套餐更新成功' : '套餐创建成功');
    router.push('/admin/collections');
  } catch (error) {
    console.error('提交失败:', error);
    // 表单校验错误不显示全局提示
    if (error?.errorFields) {
      return;
    }
    message.error(error.response?.data?.message || '提交失败');
  } finally {
    loading.value = false;
  }
};

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

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

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

.package-list {
  width: 100%;
}

.discount-hint {
  color: #666;
  font-size: 12px;
  margin-left: 8px;
}
</style>
