<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="道具名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入道具名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="道具描述" prop="itemDesc">
              <el-input v-model="queryParams.itemDesc" placeholder="请输入道具描述" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:items:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:items:edit']"
              >修改</el-button
            >
          </el-col>
          <!--          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:items:remove']"
              >删除</el-button
            >
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:items:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="itemsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="道具ID" align="center" prop="id" v-if="true" />
        <el-table-column label="主类型" align="center" prop="giftTypeParentName" />
        <el-table-column label="子类型" align="center" prop="giftTypeChildName" />
        <el-table-column label="道具名称" align="center" prop="name" />
        <el-table-column label="图片" align="center" width="90">
          <template #default="scope">
            <el-image
              v-if="scope.row.itemUrl"
              :src="scope.row.itemUrl"
              style="width: 40px; height: 40px; border-radius: 4px; cursor: zoom-in"
              :preview-src-list="[scope.row.itemUrl]"
              :preview-teleported="true"
              fit="cover"
            />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="类型值" align="center" prop="itemType" />
        <el-table-column label="积分值" align="center" prop="itemValue" />
        <el-table-column label="数量" align="center" prop="itemCount" />
        <el-table-column label="道具描述" align="center" prop="itemDesc" />
        <el-table-column label="有效期" align="center">
          <template #default="scope">
            <span v-if="+scope.row.effectiveType === 0">永久</span>
            <span v-else-if="[1, 3].includes(+scope.row.effectiveType)">{{ scope.row.expireTime }}</span>
            <span v-else-if="+scope.row.effectiveType === 2">{{ scope.row.effectiveDay }}天</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="是否通用" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isCommon === 1 ? 'success' : 'info'">
              {{ scope.row.isCommon === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否赠送" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isGiveAway === 1 ? 'success' : 'info'">
              {{ scope.row.isGiveAway === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="赠送截止时间" align="center" prop="giveStopTime" />
        <el-table-column label="是否审核" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isAudit === 1 ? 'success' : 'info'">
              {{ scope.row.isAudit === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:items:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:items:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改道具对话框 disabled-->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="itemsFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="主类型" prop="giftTypeParentId">
          <el-select v-model="form.giftTypeParentId" placeholder="请选择" clearable filterable @change="onParentChange">
            <el-option v-for="item in itemOptionsGiftList" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="子类型" prop="giftTypeChildId">
          <el-select
            v-model="form.giftTypeChildId"
            placeholder="请选择"
            clearable
            filterable
            @visible-change="handleChildVisibleChange"
            @change="onParentChildChange"
          >
            <el-option v-for="item in itemOptionsChildList" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="道具名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入道具名称" />
        </el-form-item>
        <!-- 在现有表单项中添加图片上传 -->
        <el-form-item label="道具图标" prop="itemUrl">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleIconChange"
              :on-remove="handleIconRemove"
              :file-list="iconFileList"
              :auto-upload="false"
              accept="image/*"
            >
              <template #trigger>
                <el-button type="primary">点击选择图标</el-button>
              </template>

              <!-- 预览图区域 -->
              <template #default>
                <div class="preview-area" @click="handlePreviewClick">
                  <!-- 只有当 iconPreviewUrl 或 itemUrl 存在时才显示 img -->
                  <img
                    v-if="iconPreviewUrl || form.itemUrl"
                    :src="iconPreviewUrl || form.itemUrl"
                    alt="预览图"
                    style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer"
                  />
                  <!-- 可选：无图时显示提示文字 -->
                  <div v-else style="margin-top: 10px; color: #999">暂无图片</div>
                </div>
              </template>

              <template #tip>
                <div class="el-upload__tip">
                  <span v-if="iconFileList.length > 0">当前已选文件：{{ iconFileList[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="价值" prop="itemValue">
          <el-input v-model="form.itemValue" placeholder="请输入价值" />
        </el-form-item>
        <el-form-item label="描述" prop="itemDesc">
          <el-input v-model="form.itemDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="数量" prop="itemValue">
          <el-input v-model="form.itemCount" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="有效时间" prop="gameType">
          <el-select aria-required="true" v-model="form.effectiveType" placeholder="请选择">
            <el-option v-for="dict in effective_tools_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效天数" prop="itemValue" v-if="form.effectiveType === '2'">
          <el-input v-model="form.effectiveDay" placeholder="请输入有效天数" />
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime" v-if="[1, 3].includes(Number(form.effectiveType))">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            placeholder="选择时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="是否通用" prop="isCommon">
          <el-switch v-model="form.isCommon" active-text="是" inactive-text="否" :active-value="1" :inactive-value="0" :value-on="1" :value-off="0" />
        </el-form-item>
        <el-form-item label="是否赠送" prop="isGiveAway">
          <el-switch
            v-model="form.isGiveAway"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0"
            @change="handleIsGiveAwayChange"
          />
        </el-form-item>
        <el-form-item label="赠送截止类型" prop="giftTypeChildId" v-if="form.isGiveAway === 1">
          <el-select v-model="form.giveStopType" placeholder="请选择" clearable @change="onGiveStopTypeChange">
            <el-option :value="0" label="不限时" />
            <el-option :value="1" label="选择固定日期" />
          </el-select>
        </el-form-item>
        <el-form-item label="赠送截止时间" prop="expireTime" v-if="form.isGiveAway === 1 && [1].includes(Number(form.giveStopType))">
          <el-date-picker
            v-model="form.giveStopTime"
            type="datetime"
            placeholder="选择时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="是否审核" prop="isFace">
          <el-select v-model="form.isAudit" placeholder="请选择" style="width: 200px">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <!-- 除了服务包 为 2  其他 为 1
        <el-form-item label="道具类型" prop="gameType">
          <el-select aria-required="true" v-model="form.itemTypeCode" placeholder="请选择">
            <el-option v-for="dict in tools_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>-->

        <!--        <el-form-item label="类型值" prop="itemType">
          <el-input v-model="form.itemType" placeholder="请输入类型值" />
        </el-form-item>-->
        <!-- 是服务包的话加上这个 -->
        <el-form-item label="道具详情" v-if="form.itemTypeCode === '2'">
          <div v-for="(reward, index) in formPrize.rewards" :key="index" style="display: flex; align-items: center; margin-bottom: 8px">
            <span>第{{ reward.ranking }}个</span>

            <!-- 道具选择 -->
            <el-select v-model="reward.itemId" placeholder="选项" style="width: 120px; margin-right: 8px">
              <el-option v-for="item in itemOptions" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>

            <!-- 数量输入 -->
            <el-input v-model="reward.quantity" placeholder="请输入数量" style="width: 100px; margin-right: 8px" />

            <!-- 操作按钮 -->
            <el-button type="primary" @click="addReward" v-if="index === 0">+</el-button>
            <el-button type="primary" @click="removeReward(index)" v-if="index !== 0">-</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Items" lang="ts">
import { listItems, getItems, delItems, addItems, updateItems } from '@/api/system/business/items';
import { ItemsVO, ItemsQuery, ItemsForm } from '@/api/system/business/items/types';
// ✅ 引入 parseTime
import { parseTime } from '@/utils/dateUtils';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { effective_tools_type, tools_type } = toRefs<any>(proxy?.useDict('effective_tools_type', 'tools_type'));
import { selectItemsSelList } from '@/api/system/business/items';
import { uploadTournament } from '@/api/system/business/tournaments';
import { selectGiftTypeChildList, selectGiftTypeParentList, getType } from '@/api/system/business/type';
const itemsList = ref<ItemsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const itemsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ItemsForm = {
  id: undefined,
  name: undefined,
  itemType: undefined,
  itemDesc: undefined,
  itemValue: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  itemTypeCode: '1',
  isGiveAway: 0,
  isCommon: 1
};
const data = reactive<PageData<ItemsForm, ItemsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    itemType: undefined,
    itemDesc: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '道具名称不能为空', trigger: 'blur' }],
    giftTypeParentId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    /* giftTypeChildId: [{ required: true, message: '不能为空', trigger: 'blur' }],*/
    itemType: [{ required: true, message: '道具类型不能为空', trigger: 'change' }]
  }
});
const formPrize = reactive({
  // ...其他表单字段
  rewards: [
    {
      ranking: 1,
      itemId: null,
      quantity: null
    }
  ]
});
const { queryParams, form, rules } = toRefs(data);

/** 查询道具列表 */
const getList = async () => {
  loading.value = true;
  const res = await listItems(queryParams.value);
  itemsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  iconFileList.value = [];
  iconPreviewUrl.value = '';
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  itemsFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ItemsVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  resetFormPrize();
  // 新增时清空图片状态
  iconPreviewUrl.value = '';
  iconFileList.value = [];
  dialog.visible = true;
  dialog.title = '添加';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ItemsVO) => {
  reset();
  resetFormPrize();
  form.value.giftTypeParentId = null;
  form.value.giftTypeParentId = null;
  const _id = row?.id || ids.value[0];
  const res = await getItems(_id);
  Object.assign(form.value, res.data);
  form.value.effectiveType = String(res.data.effectiveType);
  // 处理奖励表单数据
  const prizeItems = res.data.itemsPrizeList || [];
  if (prizeItems.length > 0) {
    formPrize.rewards = prizeItems.map((item, index) => ({
      ranking: item.ranking || index + 1,
      itemId: Number(item.itemId),
      quantity: Number(item.quantity)
    }));
  } else {
    formPrize.rewards = [
      {
        ranking: 1,
        itemId: null,
        quantity: null
      }
    ];
  }
  // 处理图片上传状态 - 保留已有图片
  if (res.data.itemUrl) {
    // 如果有现有图片，初始化文件列表
    iconPreviewUrl.value = res.data.itemUrl;
    iconFileList.value = [
      {
        name: '图片',
        url: res.data.itemUrl,
        status: 'success'
      }
    ];
  } else {
    // 没有现有图片，清空状态
    iconPreviewUrl.value = '';
    iconFileList.value = [];
  }
  // 触发子类型变更处理
  if (form.value.giftTypeParentId) {
    await onParentChange(form.value.giftTypeParentId);
  }
  if (form.value.giftTypeChildId) {
    await onParentChildChange(form.value.giftTypeChildId);
  }
  dialog.visible = true;
  dialog.title = '修改';
};

/** 提交按钮 */
const submitForm = () => {
  itemsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // ✅ 新增校验：如果是套票（'2'），则必须有道具详情且数量不能为0
      if (form.value.itemTypeCode === '2') {
        // 检查是否存在有效道具详情
        const validRewards = formPrize.rewards.filter(
          (reward) =>
            reward.itemId !== null &&
            reward.itemId !== undefined &&
            reward.itemId !== '' &&
            reward.quantity !== null &&
            reward.quantity !== undefined &&
            reward.quantity !== ''
        );

        // 如果没有有效道具详情
        if (validRewards.length === 0) {
          ElMessage.error('请选择至少一个有效的道具详情');
          buttonLoading.value = false;
          return;
        }

        // 检查是否有数量为0或负数的情况
        const invalidQuantity = validRewards.some((reward) => Number(reward.quantity) <= 0);

        if (invalidQuantity) {
          ElMessage.error('道具数量必须大于0');
          buttonLoading.value = false;
          return;
        }
      }

      // 构造最终要提交的数据对象
      const formData: ItemsForm = {
        ...data.form,
        itemsPrizeList: formPrize.rewards.map((reward) => ({
          ranking: Number(reward.ranking),
          itemId: Number(reward.itemId),
          quantity: Number(reward.quantity)
        }))
      };
      if (form.value.id) {
        await updateItems(formData).finally(() => (buttonLoading.value = false));
      } else {
        await addItems(formData).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ItemsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除道具编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delItems(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/items/export',
    {
      ...queryParams.value
    },
    `道具${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};
const addReward = () => {
  const currentLength = formPrize.rewards.length;

  // 判断是否超过 itemOptions 的数量限制
  if (currentLength < itemOptions.value.length) {
    formPrize.rewards.push({
      ranking: currentLength + 1, // 自动生成排名，从 1 开始
      itemId: null,
      quantity: null
    });
  } else {
    ElMessage.warning(`最多只能添加 ${itemOptions.value.length} 个项`);
  }
};
// 下拉选项数据 selectBlingStructuresInfo
const itemOptions = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadItemOptions = async () => {
  try {
    const res = await selectItemsSelList();
    if (res.code === 200) {
      // 类型断言
      const data = res.data as unknown as { id: number; name: string }[];

      // 过滤掉 id === 2 的项，并映射为 { id, label }
      itemOptions.value = data
        .filter((item) => item.id !== 2) // ✅ 过滤 id 为 2 的
        .filter((item) => item.id !== 2001) // ✅ 过滤 id 为 2 的
        .map((item) => ({
          id: item.id,
          label: item.name
        }));
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
const removeReward = (index: number) => {
  formPrize.rewards.splice(index, 1);

  // 删除后重新设置排名
  formPrize.rewards.forEach((r, i) => {
    r.ranking = i + 1;
  });
};
// 用于保存原始的默认奖励结构
const defaultReward = {
  ranking: 1,
  itemId: null,
  quantity: null
};

// 重置函数
const resetFormPrize = () => {
  // 清空 rewards 并添加默认项
  formPrize.rewards.splice(0); // 清空数组
  formPrize.rewards.push({ ...defaultReward }); // 添加初始项
};
onMounted(() => {
  loadItemOptions();
  getList();
  loadCategoryOptions();
});

/** 加载父级选项 */
const itemOptionsGiftList = ref<{ id: number; label: string }[]>([]);
const loadCategoryOptions = async () => {
  try {
    const res = await selectGiftTypeParentList();
    if (res.code === 200) {
      const data = res.data as unknown as { id: number; name: string }[];
      itemOptionsGiftList.value = data.map((item) => ({
        id: item.id,
        label: item.name
      }));
    }
  } catch (error) {
    console.error('加载父级选项失败:', error);
  }
};
// 在文件顶部导入 nextTick
const itemOptionsChildList = ref<{ id: number; label: string }[]>([]);
// 主类型变更时加载子类型
const onParentChange = async (parentId: number | string | null) => {
  if (!parentId) {
    itemOptionsChildList.value = [];
    return;
  }

  try {
    const res = await selectGiftTypeChildList(parentId); // ✅ 传入 parentId
    if (res.code === 200) {
      const data = res.data as unknown as { id: number; name: string }[];
      itemOptionsChildList.value = data.map((item) => ({
        id: item.id,
        label: item.name
      }));
      // 检查是否为服务包子类型
      const res2 = await getType(parentId);
      if (res2.code === 200) {
        // ✅ data2 是单个对象，不是数组！
        const data2 = res2.data as unknown as { id: number; name: string; typeCode?: string; typeValue?: number };

        // ✅ 直接访问 typeCode 字段（注意字段名是 typeCode，不是 type_code）
        if (data2.typeCode === 'combo_package') {
          form.value.itemTypeCode = '2'; // 设置为服务包类型
          await nextTick();
        } else {
          form.value.itemTypeCode = '1'; // 默认设置为普通类型
          await nextTick();
        }
        form.value.itemType = data2.typeValue;
      }
    }
    //是否是服务包 如果他的 type_code = combo_package
  } catch (error) {
    console.error('加载子类型失败:', error);
    ElMessage.error('加载子类型失败');
  }
};
const onParentChildChange = async (parentId: number | string | null) => {
  try {
    // 检查是否为服务包子类型
    const res2 = await getType(parentId);
    if (res2.code === 200) {
      // ✅ data2 是单个对象，不是数组！
      const data2 = res2.data as unknown as { id: number; name: string; typeValue?: number };
      form.value.itemType = data2.typeValue;
    }
    //是否是服务包 如果他的 type_code = combo_package
  } catch (error) {
    console.error('加载失败:', error);
    ElMessage.error('加载失败');
  }
};
// 添加图片上传相关响应式变量
const iconPreviewUrl = ref('');
const iconFileList = ref([]);

// 图片上传处理函数
const handleIconChange = async (file) => {
  const index = iconFileList.value.findIndex((f) => f.uid === file.uid);
  iconFileList.value = [];

  if (file.raw) {
    iconPreviewUrl.value = URL.createObjectURL(file.raw);
  }

  if (index === -1) {
    // 如果文件不在列表中，则添加进去
    iconFileList.value.push(file);
  }

  try {
    const rawFile = file.raw;
    // 使用 tournament 的上传接口
    const res = await uploadTournament(rawFile); // 修改为使用 tournament 上传接口
    if (res.code === 200) {
      // 更新文件状态为成功
      iconFileList.value[index] = {
        ...file,
        status: 'success',
        response: res.data.url
      };
      form.value.itemUrl = iconFileList.value[index].response;
      iconPreviewUrl.value = iconFileList.value[index].response;
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg);
    }
  } catch (error) {
    // 更新文件状态为失败
    iconFileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};
// 删除文件处理函数
const handleIconRemove = (file, updatedFileList) => {
  iconFileList.value = updatedFileList;
  // 清除预览图和临时链接
  iconPreviewUrl.value = '';
  form.value.itemUrl = null;
};

// 点击预览图触发放大
const handlePreviewClick = () => {
  const currentSrc = iconPreviewUrl.value || form.value.itemUrl;
  if (currentSrc) {
    // 如果需要预览功能，可以打开预览对话框
    openPreview(currentSrc);
  }
};

// 预览弹窗相关
const dialogVisible = ref(false);
const previewSrc = ref('');

function openPreview(src: string) {
  previewSrc.value = src;
  dialogVisible.value = true;
}
const onGiveStopTypeChange = (value: number | null) => {
  if (value === 0) {
    form.value.giveStopTime = undefined; // 清空赠送截止时间
  }
};
// 是否赠送开关变化处理
const handleIsGiveAwayChange = (value: number) => {
  if (value === 0) {
    // 当切换为"否"时
    form.value.giveStopType = undefined;
    form.value.giveStopTime = undefined;
  }
};
const handleChildVisibleChange = (visible: boolean) => {
  if (visible && itemOptionsChildList.value.length === 1) {
    const onlyItem = itemOptionsChildList.value[0];
    if (form.value.giftTypeChildId !== onlyItem.id) {
      form.value.giftTypeChildId = onlyItem.id;
      nextTick(() => onParentChildChange(onlyItem.id));
    }
  }
};
</script>
<style scoped>
.upload-container {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.preview-area {
  cursor: pointer;
}

.upload-icon .el-upload {
  width: auto;
  height: auto;
}
</style>
