<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="levelName">
              <el-input v-model="queryParams.levelName" placeholder="请输入等级名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="等级编码" prop="levelCode">
              <el-input v-model="queryParams.levelCode" 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="['physical:memberLevelConfig:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:memberLevelConfig:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['physical:memberLevelConfig:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Picture" @click="handleUploadFile('IMAGE')">上传图片</el-button>
          </el-col>
          <!--          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:memberLevelConfig: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="memberLevelConfigList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编码" align="center" prop="id" v-if="true" />
        <el-table-column label="等级名称" align="center" prop="levelName" />
        <el-table-column label="等级编码" align="center" prop="levelCode" />
        <el-table-column label="等级图标" align="center" width="90">
          <template #default="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              style="width: 40px; height: 40px; border-radius: 4px; cursor: zoom-in"
              :preview-src-list="[scope.row.imageUrl]"
              :preview-teleported="true"
              fit="cover"
            />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="满足条件（晋升）" align="center" min-width="220">
          <template #default="{ row }">
            <div v-if="row.promotionConditions">
              <div v-for="(cond, idx) in parseConditions(row.promotionConditions)" :key="'p' + idx" class="condition-item">
                {{ cond.description }}
              </div>
            </div>
            <span v-else style="color: #999">--</span>
          </template>
        </el-table-column>
        <!-- 替换现有的保级条件列 -->
        <el-table-column label="保级条件" align="center" min-width="220">
          <template #default="{ row }">
            <div v-if="row.retentionConditions">
              <div v-for="(cond, idx) in parseConditions(row.retentionConditions)" :key="'r' + idx" class="condition-item">
                {{ cond.description }}
              </div>
            </div>
            <span v-else style="color: #999">与晋升条件一致</span>
          </template>
        </el-table-column>
        <el-table-column label="权益配置（赠送次数）" align="center" width="200">
          <template #default="{ row }">
            <div>主赛: {{ row.mainTournamentGiftCount || 0 }}次</div>
            <div>附赛: {{ row.sideTournamentGiftCount || 0 }}次</div>
            <div>服务券: {{ row.serviceVoucherGiftCount || 0 }}张</div>
          </template>
        </el-table-column>
        <el-table-column label="发布状态" align="center" prop="status">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'draft'" type="info">草稿</el-tag>
            <el-tag v-if="row.status === 'published'" type="success">已发布</el-tag>
            <el-tag v-if="row.status === 'disabled'" type="danger">已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="允许赠送" align="center" prop="allowGift">
          <template #default="{ row }">
            <el-tag v-if="row.allowGift === true" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template #default="scope">
            <!-- 发布按钮（仅在草稿状态时显示） -->
            <el-tooltip content="发布" placement="top" v-if="scope.row.status === 'draft'">
              <el-button
                link
                type="success"
                icon="Check"
                @click="handlePublish(scope.row)"
                v-hasPermi="['physical:memberLevelConfig:publish']"
              ></el-button>
            </el-tooltip>

            <!-- 修改按钮 -->
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['physical:memberLevelConfig:edit']"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['physical:memberLevelConfig: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>

    <!-- 添加或修改会员等级权益配置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="860px" append-to-body>
      <el-form ref="memberLevelConfigFormRef" :model="form" :rules="rules" label-width="160px" style="max-width: 860px; margin: 0 auto">
        <el-form-item label="等级编码" prop="levelCode">
          <el-select v-model="form.levelCode" placeholder="请选择等级编码" @change="handleLevelCodeChange">
            <el-option v-for="dict in member_level_type" :key="dict.value" :label="dict.value" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 基础信息 -->
        <el-form-item label="等级名称" prop="levelName">
          <el-input v-model="form.levelName" placeholder="如：白银会员(T1)" disabled />
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="draft">草稿</el-radio>
            <el-radio label="published">已发布</el-radio>
            <el-radio label="disabled">已禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="等级图标">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleImageChange"
              :on-remove="handleImageRemove"
              :file-list="imageFileList"
              :auto-upload="false"
              accept="image/*"
            >
              <template #trigger>
                <el-button type="primary">点击选择图标</el-button>
              </template>

              <!-- 预览图区域 -->
              <template #default>
                <div class="preview-area" @click="handleImagePreviewClick">
                  <img
                    v-if="imagePreviewUrl || form.imageUrl"
                    :src="imagePreviewUrl || form.imageUrl"
                    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="imageFileList.length > 0">当前已选文件：{{ imageFileList[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
        <!-- 权益配置 -->
        <el-divider content-position="left">权益配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="主赛赠送次数">
              <el-input-number v-model="form.mainTournamentGiftCount" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="附赛赠送次数">
              <el-input-number v-model="form.sideTournamentGiftCount" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务券赠送次数">
              <el-input-number v-model="form.serviceVoucherGiftCount" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="是否允许被赠送">
          <el-switch v-model="form.allowGift" />
        </el-form-item>

        <!-- 满足条件（晋升） -->
        <el-divider content-position="left">满足条件（晋升）</el-divider>
        <div v-if="form.promotionConditions2.length === 0" class="empty-condition">
          <el-button size="small" @click="addPromotionCondition">+ 添加晋升条件</el-button>
        </div>
        <div v-for="(cond, index) in form.promotionConditions2" :key="'promo-' + index" class="condition-item">
          <el-row :gutter="10">
            <el-col :span="7">
              <el-select v-model="cond.type" placeholder="条件类型" size="small" style="width: 100%">
                <el-option value="register" label="注册并实名" />
                <el-option value="tournament" label="参加现场赛事" />
                <el-option value="main_tournament" label="参加系列赛主赛" />
                <el-option value="championship" label="获得冠军" />
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-input-number
                v-model="cond.count"
                :min="1"
                :max="999"
                size="small"
                controls-position="right"
                style="width: 100%"
                placeholder="次数"
              />
            </el-col>
            <el-col :span="7">
              <el-select v-model="cond.timeScope" placeholder="时间范围" size="small" style="width: 100%">
                <el-option value="none" label="不限时间" />
                <el-option value="natural_year" label="自然年内" />
                <el-option value="two_years" label="两个自然年内" />
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-select v-model="cond.logic" placeholder="关系" size="small" style="width: 100%">
                <el-option value="and" label="且" />
                <el-option value="or" label="或" />
              </el-select>
            </el-col>
            <el-col :span="2">
              <el-button size="small" type="danger" @click="removePromotionCondition(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <el-button v-if="form.promotionConditions2.length > 0" size="small" @click="addPromotionCondition" style="margin-top: 8px">
          + 再添加一个晋升条件
        </el-button>

        <!-- 保级条件（可选） -->
        <el-divider content-position="left">保级条件（可选）</el-divider>
        <div v-if="form.retentionConditions2.length === 0" class="empty-condition">
          <el-button size="small" @click="addRetentionCondition">+ 添加保级条件</el-button>
          <!--          <span style="color: #999; margin-left: 12px">（留空表示与晋升条件一致）</span>-->
        </div>
        <div v-for="(cond, index) in form.retentionConditions2" :key="'retention-' + index" class="condition-item">
          <el-row :gutter="10">
            <el-col :span="7">
              <el-select v-model="cond.type" placeholder="条件类型" @change="updateDescription(cond)" size="small" style="width: 100%">
                <el-option value="register" label="注册并实名" />
                <el-option value="tournament" label="参加现场赛事" />
                <el-option value="main_tournament" label="参加系列赛主赛" />
                <el-option value="championship" label="获得冠军" />
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-input-number
                v-model="cond.count"
                :min="1"
                :max="999"
                size="small"
                controls-position="right"
                style="width: 100%"
                @change="updateDescription(cond)"
                placeholder="次数"
              />
            </el-col>
            <el-col :span="7">
              <el-select v-model="cond.timeScope" placeholder="时间范围" size="small" style="width: 100%" @change="updateDescription(cond)">
                <el-option value="none" label="不限时间" />
                <el-option value="natural_year" label="自然年内" />
                <el-option value="two_years" label="两个自然年内" />
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-select v-model="cond.logic" placeholder="关系" size="small" style="width: 100%">
                <el-option value="and" label="且" />
                <el-option value="or" label="或" />
              </el-select>
            </el-col>
            <el-col :span="2">
              <el-button size="small" type="danger" @click="removeRetentionCondition(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <el-button v-if="form.retentionConditions2.length > 0" size="small" @click="addRetentionCondition" style="margin-top: 8px">
          + 再添加一个保级条件
        </el-button>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="buttonLoading">保存配置</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 图标预览弹窗 -->
    <el-dialog v-model="imageDialogVisible" title="图标预览" width="60%">
      <img :src="imagePreviewUrl || form.imageUrl" alt="预览" style="max-width: 100%; max-height: 80vh" />
    </el-dialog>
  </div>
</template>

<script setup name="MemberLevelConfig" lang="ts">
import {
  listMemberLevelConfig,
  getMemberLevelConfig,
  delMemberLevelConfig,
  addMemberLevelConfig,
  updateMemberLevelConfig
} from '@/api/system/physical/memberLevelConfig';
import { uploadTournament } from '@/api/system/business/tournaments';
import { MemberLevelConfigVO, MemberLevelConfigQuery, MemberLevelConfigForm } from '@/api/system/physical/memberLevelConfig/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { member_level_type } = toRefs<any>(proxy?.useDict('member_level_type'));
const memberLevelConfigList = ref<MemberLevelConfigVO[]>([]);
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 memberLevelConfigFormRef = ref<ElFormInstance>();

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

const initFormData: MemberLevelConfigForm = {
  id: undefined,
  levelName: undefined,
  levelCode: undefined,
  status: 'draft',
  imageUrl: undefined,
  mainTournamentGiftCount: undefined,
  sideTournamentGiftCount: undefined,
  serviceVoucherGiftCount: undefined,
  allowGift: undefined,
  promotionConditions: undefined,
  retentionConditions: undefined,
  promotionConditions2: [],
  retentionConditions2: [],
  createdAt: undefined,
  updatedAt: undefined,
  deletedAt: undefined
};
const data = reactive<PageData<MemberLevelConfigForm, MemberLevelConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    levelName: undefined,
    levelCode: undefined,
    status: undefined,
    imageUrl: undefined,
    mainTournamentGiftCount: undefined,
    sideTournamentGiftCount: undefined,
    serviceVoucherGiftCount: undefined,
    allowGift: undefined,
    promotionConditions: undefined,
    retentionConditions: undefined,
    promotionConditions2: [],
    retentionConditions2: [],
    createdAt: undefined,
    updatedAt: undefined,
    deletedAt: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    levelName: [{ required: true, message: '等级名称，如：青铜会员(T0)不能为空', trigger: 'blur' }],
    levelCode: [{ required: true, message: '等级编码，如：T0, T1, ..., T5不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '发布状态：draft=草稿, published=已发布, disabled=已禁用不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询会员等级权益配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMemberLevelConfig(queryParams.value);
  memberLevelConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

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

  // 清空图标上传相关数据
  imageFileList.value = [];
  imagePreviewUrl.value = '';
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 清空图标上传相关数据
  imageFileList.value = [];
  imagePreviewUrl.value = '';
  dialog.visible = true;
  dialog.title = '添加会员等级权益配置';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MemberLevelConfigVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMemberLevelConfig(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改会员等级权益配置';

  // 如果有现有图标URL，创建虚拟文件对象以便显示
  if (res.data.imageUrl) {
    imageFileList.value = [
      {
        name: '已上传图标',
        url: res.data.imageUrl,
        status: 'success'
      }
    ];
  }
};
/** 提交按钮 */
const submitForm = () => {
  memberLevelConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 提交前确保所有描述已更新
      form.value.promotionConditions2.forEach((cond) => updateDescription(cond));
      form.value.retentionConditions2.forEach((cond) => updateDescription(cond));
      form.value.promotionConditions = JSON.stringify(form.value.promotionConditions2);
      form.value.retentionConditions = JSON.stringify(form.value.retentionConditions2);
      if (form.value.id) {
        await updateMemberLevelConfig(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMemberLevelConfig(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MemberLevelConfigVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除会员等级权益配置编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMemberLevelConfig(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/memberLevelConfig/export',
    {
      ...queryParams.value
    },
    `memberLevelConfig_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
/** 添加晋升条件 */
const addPromotionCondition = () => {
  const cond = {
    type: 'tournament',
    count: 1,
    timeScope: 'none',
    description: ''
  };
  updateDescription(cond); // 自动生成描述
  form.value.promotionConditions2.push(cond);
};
/** 删除晋升条件 */
const removePromotionCondition = (index: number) => {
  form.value.promotionConditions2.splice(index, 1);
};
/** 添加保级条件 */
const addRetentionCondition = () => {
  const cond = {
    type: 'tournament',
    count: 1,
    timeScope: 'none',
    description: ''
  };
  updateDescription(cond); // 自动生成描述
  form.value.retentionConditions2.push(cond);
};
/** 删除保级条件 */
const removeRetentionCondition = (index: number) => {
  form.value.retentionConditions2.splice(index, 1);
};
/** 更新条件描述 */
const updateDescription = (cond: any) => {
  const typeMap = {
    register: '注册并实名',
    tournament: '参加现场赛事',
    main_tournament: '参加系列赛主赛',
    championship: '获得主赛冠军',
    all_series: '参加全部系列赛',
    total_tournament: '参加所有现场系列赛'
  };
  const timeMap = {
    none: '',
    natural_year: '自然年内',
    two_years: '两个自然年内'
  };

  const prefix = timeMap[cond.timeScope] || '';
  const baseText = typeMap[cond.type] || cond.type;

  if (['register', 'all_series'].includes(cond.type)) {
    cond.description = prefix + baseText;
  } else if (cond.type === 'championship') {
    // 冠军用“次”，不是“场”
    cond.description = `${prefix}${baseText}${cond.count}次`;
  } else {
    // 其他用“场”
    cond.description = `${prefix}${baseText}${cond.count}场`;
  }
};
// 在现有 methods 或 setup 中添加以下方法
const parseConditions = (conditionsStr: string) => {
  try {
    if (!conditionsStr) return [];

    const conditions = JSON.parse(conditionsStr);
    return conditions.map((cond: any) => {
      // 如果已经有 description 则直接使用，否则生成
      if (cond.description) {
        return cond;
      }

      return generateConditionDescription(cond);
    });
  } catch (error) {
    console.error('解析条件失败:', error);
    return [];
  }
};

const generateConditionDescription = (cond: any) => {
  const typeMap = {
    register: '注册并实名',
    tournament: '参加现场赛事',
    main_tournament: '参加主赛',
    championship: '获得冠军'
  };

  const timeMap = {
    none: '',
    natural_year: '自然年内',
    two_years: '两个自然年内'
  };

  const prefix = timeMap[cond.timeScope] || '';
  const baseText = typeMap[cond.type] || cond.type;

  let description = '';
  if (['register'].includes(cond.type)) {
    description = prefix + baseText;
  } else if (cond.type === 'championship') {
    description = `${prefix}${baseText}${cond.count}次`;
  } else {
    description = `${prefix}${baseText}${cond.count}场`;
  }

  return {
    ...cond,
    description
  };
};
/** 处理等级编码变化 */
const handleLevelCodeChange = () => {
  // 找到对应的字典项
  const dictItem = member_level_type.value.find((item) => item.value === form.value.levelCode);
  if (dictItem) {
    // 设置等级名称为字典项的标签
    form.value.levelName = dictItem.label;
  }
};
/** 发布按钮操作 */
const handlePublish = async (row: MemberLevelConfigVO) => {
  await proxy?.$modal.confirm('是否确认发布会员等级权益配置编号为"' + row.id + '"的数据项？').finally(() => (loading.value = false));

  // 更新状态为已发布
  // 创建完整的更新数据对象
  const updateData = {
    id: row.id,
    status: 'published',
    // 保留原有条件数据
    promotionConditions2: row.promotionConditions2 || [],
    retentionConditions2: row.retentionConditions2 || [],
    // 其他必要字段
    levelName: row.levelName,
    levelCode: row.levelCode,
    imageUrl: row.imageUrl,
    mainTournamentGiftCount: row.mainTournamentGiftCount,
    sideTournamentGiftCount: row.sideTournamentGiftCount,
    serviceVoucherGiftCount: row.serviceVoucherGiftCount,
    allowGift: row.allowGift,
    // 如果有其他必需字段也需要添加
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
    deletedAt: row.deletedAt
  };
  try {
    await updateMemberLevelConfig(updateData);
    proxy?.$modal.msgSuccess('发布成功');
    await getList(); // 刷新列表
  } catch (error) {
    proxy?.$modal.msgError('发布失败');
  }
};
// 图标上传相关
const imageFileList = ref([]);
const imagePreviewUrl = ref('');
const imageDialogVisible = ref(false);

// 处理图标上传变化
const handleImageChange = async (file) => {
  const index = imageFileList.value.findIndex((f) => f.uid === file.uid);
  imageFileList.value = [];

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

  if (index === -1) {
    imageFileList.value.push(file);
  }

  try {
    const rawFile = file.raw;
    if (!rawFile) return;

    const res = await uploadTournament(rawFile);
    if (res.code === 200 && res.data?.url) {
      imageFileList.value[index] = {
        ...file,
        status: 'success',
        response: res.data.url
      };
      form.value.imageUrl = res.data.url;
      imagePreviewUrl.value = res.data.url;
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg || '上传失败');
    }
  } catch (error) {
    imageFileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};

// 删除图标处理
const handleImageRemove = (file, updatedFileList) => {
  imageFileList.value = updatedFileList;
  imagePreviewUrl.value = '';
  form.value.imageUrl = '';
};

// 点击预览图放大
const handleImagePreviewClick = () => {
  if (imagePreviewUrl.value || form.value.imageUrl) {
    imageDialogVisible.value = true;
  }
};
const handleUploadFile = (fileType: string) => {
  proxy?.$router.push({
    path: '/physical/mediaResource',
    query: {
      bizType: 'member_type', // 转为字符串以兼容 URL 参数
      fileType: fileType
    }
  });
};
</script>
