<template>
  <!-- 运营活动管理 - 新增/编辑页面 -->
  <div class="table-box" style="width: 100%; min-height: 100%; background-color: white">
    <div class="header">
      <el-button @click="goBack"> 返回 </el-button>
      <h2 class="title">{{ type == "add" ? "新建" : "编辑" }}活动</h2>
    </div>
    <div class="form-wrapper">
      <div class="form-wrapper-main">
        <el-form ref="ruleFormRef" :model="activityModel" :rules="rules" class="formBox" label-width="140px">
          <div class="form-content">
            <!-- 活动类型 -->
            <el-form-item label="活动类型" prop="activityType">
              <el-select v-model="activityModel.activityType" class="form-input" clearable placeholder="请选择">
                <el-option label="评论有礼" value="COMMENT" />
                <el-option label="营销活动" value="MARKETING" />
              </el-select>
            </el-form-item>

            <!-- 活动名称 -->
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="activityModel.activityName" class="form-input" clearable maxlength="50" placeholder="请输入" />
            </el-form-item>

            <!-- 活动时间 -->
            <el-form-item class="activity-time-item" label="活动时间" prop="activityTimeRange">
              <el-date-picker
                v-model="activityModel.activityTimeRange"
                :disabled-date="disabledDate"
                class="form-input"
                end-placeholder="结束日期"
                format="YYYY/MM/DD"
                range-separator="-"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <!-- 评论有礼相关字段 -->
            <template v-if="activityModel.activityType === 'COMMENT'">
              <!-- 用户可参与次数 -->
              <el-form-item label="用户可参与次数" prop="participationLimit">
                <el-input v-model="activityModel.participationLimit" placeholder="请输入" maxlength="4" />
              </el-form-item>

              <!-- 券类型 -->
              <el-form-item label="券类型" prop="rewardType">
                <el-radio-group v-model="activityModel.rewardType">
                  <el-radio label="COUPON"> 优惠券 </el-radio>
                  <el-radio label="VOUCHER"> 代金券 </el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 优惠券/代金券 -->
              <el-form-item
                :label="activityModel.rewardType === 'VOUCHER' ? '代金券' : '优惠券'"
                :prop="activityModel.rewardType === 'VOUCHER' ? 'voucherId' : 'couponId'"
              >
                <el-select
                  v-if="activityModel.rewardType === 'VOUCHER'"
                  v-model="activityModel.voucherId"
                  class="form-input"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option v-for="item in couponList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-select v-else v-model="activityModel.couponId" class="form-input" clearable filterable placeholder="请选择">
                  <el-option v-for="item in couponList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>

              <!-- 优惠券/代金券发放数量 -->
              <el-form-item
                :label="(activityModel.rewardType === 'VOUCHER' ? '代金券' : '优惠券') + '发放数量'"
                :prop="activityModel.rewardType === 'VOUCHER' ? 'voucherQuantity' : 'couponQuantity'"
              >
                <el-input
                  v-if="activityModel.rewardType === 'VOUCHER'"
                  v-model="activityModel.voucherQuantity"
                  placeholder="请输入"
                  maxlength="5"
                />
                <el-input v-else v-model="activityModel.couponQuantity" placeholder="请输入" maxlength="5" />
              </el-form-item>
            </template>

            <!-- 营销活动相关字段 -->
            <template v-if="activityModel.activityType === 'MARKETING'">
              <!-- 报名时间 -->
              <el-form-item class="activity-time-item" label="报名时间" prop="signupTimeRange">
                <el-date-picker
                  v-model="activityModel.signupTimeRange"
                  :disabled-date="disabledSignupDate"
                  class="form-input"
                  end-placeholder="结束日期"
                  format="YYYY/MM/DD"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>

              <!-- 活动限制人数 -->
              <el-form-item label="活动限制人数">
                <el-input
                  style="width: 95%"
                  v-model="activityModel.activityLimitPeople"
                  placeholder="请输入"
                  maxlength="20"
                  @input="handlePositiveIntegerInput('activityLimitPeople', $event)"
                />
                <div style="width: 5%; text-align: right">人</div>
              </el-form-item>

              <!-- 活动详情 -->
              <el-form-item label="活动详情" prop="activityDetails">
                <el-input
                  v-model="activityModel.activityDetails"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入活动详情"
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
            </template>

            <!-- 上传图片方式 -->
            <el-form-item label="活动图片类型" prop="uploadImgType">
              <el-radio-group v-model="activityModel.uploadImgType" :disabled="type !== 'add'">
                <el-radio :label="1"> 本地上传 </el-radio>
                <el-radio :label="2"> AI生成 </el-radio>
              </el-radio-group>
              <div v-if="type !== 'add'" style="margin-top: 4px; font-size: 12px; color: #909399">
                编辑模式下固定为"本地上传"，以便编辑图片
              </div>
            </el-form-item>

            <!-- 图片描述（当选择使用描述时显示） -->
            <el-form-item v-if="activityModel.uploadImgType === 2" label="图片描述" prop="imgDescribe">
              <el-input
                v-model="activityModel.imgDescribe"
                type="textarea"
                :rows="4"
                placeholder="请输入图片描述"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <!-- 活动标题图 -->
            <el-form-item v-if="activityModel.uploadImgType === 1" label="活动标题图" prop="activityTitleImage">
              <div class="upload-item-wrapper">
                <div class="upload-area upload-area-horizontal-21-9" :class="{ 'upload-full': titleFileList.length >= 1 }">
                  <el-upload
                    v-model:file-list="titleFileList"
                    :accept="'.jpg,.jpeg,.png'"
                    :auto-upload="false"
                    :before-remove="handleBeforeRemove"
                    :disabled="hasUnuploadedImages"
                    :limit="1"
                    :on-change="handleTitleUploadChange"
                    :on-exceed="handleUploadExceed"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleTitleRemove"
                    :show-file-list="true"
                    list-type="picture-card"
                  >
                    <template #trigger>
                      <div v-if="titleFileList.length < 1" class="upload-trigger-card el-upload--picture-card">
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </div>
                    </template>
                  </el-upload>
                </div>
                <div class="upload-hint">请上传21:9尺寸图片效果更佳,支持jpg、jpeg、png格式，上传图片不得超过5M</div>
              </div>
            </el-form-item>

            <!-- 活动详情图 -->
            <el-form-item v-if="activityModel.uploadImgType === 1" label="活动详情图" prop="activityDetailImage">
              <div class="upload-item-wrapper">
                <div class="upload-area upload-area-vertical" :class="{ 'upload-full': detailFileList.length >= 9 }">
                  <el-upload
                    v-model:file-list="detailFileList"
                    :accept="'.jpg,.jpeg,.png'"
                    :auto-upload="false"
                    :before-remove="handleBeforeRemove"
                    :disabled="hasUnuploadedImages"
                    :limit="9"
                    :on-change="handleDetailUploadChange"
                    :on-exceed="handleDetailUploadExceed"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleDetailRemove"
                    :show-file-list="true"
                    list-type="picture-card"
                  >
                    <template #trigger>
                      <div v-if="detailFileList.length < 9" class="upload-trigger-card el-upload--picture-card">
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </div>
                    </template>
                  </el-upload>
                </div>
                <div class="upload-hint">请上传竖版图片,支持jpg、jpeg、png格式，最多上传9张，单张图片不得超过5M</div>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 底部按钮区域 -->
      <div class="button-container">
        <el-button @click="goBack"> 取消 </el-button>
        <el-button type="primary" @click="handleSubmit()"> 提交审核 </el-button>
      </div>
    </div>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="imageViewerVisible"
      :initial-index="imageViewerInitialIndex"
      :url-list="imageViewerUrlList"
      @close="imageViewerVisible = false"
    />
  </div>
</template>

<script lang="tsx" name="newActivity" setup>
/**
 * 运营活动管理 - 新增/编辑页面
 * 功能：支持运营活动的新增和编辑操作
 */
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import type { FormInstance, UploadFile, UploadProps } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { addActivity, getActivityDetail, getCouponList, updateActivity } from "@/api/modules/operationManagement";
import { uploadContractImage } from "@/api/modules/licenseManagement";
import { localGet } from "@/utils";

// ==================== 响应式数据定义 ====================

// 路由相关
const router = useRouter();
const route = useRoute();

// 页面状态
const type = ref<string>(""); // 页面类型：add-新增, edit-编辑
const id = ref<string>(""); // 页面ID参数

// 表单引用
const ruleFormRef = ref<FormInstance>();

// 优惠券列表
const couponList = ref<any[]>([]);

// 文件上传相关
const titleFileList = ref<UploadFile[]>([]);
const detailFileList = ref<UploadFile[]>([]);
const titleImageUrl = ref<string>("");
const detailImageUrl = ref<string>("");
const pendingUploadFiles = ref<UploadFile[]>([]);
const uploading = ref(false);
const imageViewerVisible = ref(false);
const imageViewerUrlList = ref<string[]>([]);
const imageViewerInitialIndex = ref(0);

// 是否有未上传的图片
const hasUnuploadedImages = computed(() => {
  return (
    titleFileList.value.some(file => file.status === "ready" || file.status === "uploading") ||
    detailFileList.value.some(file => file.status === "ready" || file.status === "uploading")
  );
});

// ==================== 表单验证规则 ====================
const rules = reactive({
  activityType: [{ required: true, message: "请选择活动类型", trigger: "change" }],
  activityName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  activityTimeRange: [
    { required: true, message: "请选择活动时间", trigger: "change" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || !Array.isArray(value) || value.length !== 2) {
          callback(new Error("请选择活动时间"));
          return;
        }
        const [startTime, endTime] = value;
        if (!startTime || !endTime) {
          callback(new Error("请选择完整的活动时间"));
          return;
        }
        const start = new Date(startTime);
        const end = new Date(endTime);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        if (start < today) {
          callback(new Error("活动开始时间不能早于当前时间"));
          return;
        }
        if (start >= end) {
          callback(new Error("活动开始时间必须早于活动结束时间"));
          return;
        }
        callback();
        // 活动时间验证通过后，重新验证报名时间（如果已设置）
        if (
          activityModel.value.activityType === "MARKETING" &&
          activityModel.value.signupTimeRange &&
          Array.isArray(activityModel.value.signupTimeRange) &&
          activityModel.value.signupTimeRange.length === 2
        ) {
          nextTick(() => {
            ruleFormRef.value?.validateField("signupTimeRange");
          });
        }
      },
      trigger: "change"
    }
  ],
  participationLimit: [
    { required: true, message: "请输入用户可参与次数", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.activityType === "COMMENT") {
          if (!value) {
            callback(new Error("请输入用户可参与次数"));
            return;
          }
          const numValue = Number(value);
          if (isNaN(numValue) || !Number.isInteger(numValue) || numValue <= 0) {
            callback(new Error("用户可参与次数必须为正整数"));
            return;
          }
          if (numValue > 9999) {
            callback(new Error("用户可参与次数必须小于9999"));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  rewardType: [{ required: true, message: "请选择券类型", trigger: "change" }],
  couponId: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.activityType === "COMMENT" && activityModel.value.rewardType === "COUPON") {
          if (!value) {
            callback(new Error("请选择优惠券"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  couponQuantity: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.activityType === "COMMENT" && activityModel.value.rewardType === "COUPON") {
          if (!value) {
            callback(new Error("请输入优惠券发放数量"));
            return;
          }
          const numValue = Number(value);
          if (isNaN(numValue) || !Number.isInteger(numValue) || numValue <= 0) {
            callback(new Error("优惠券发放数量必须为正整数"));
            return;
          }
          if (numValue > 99999) {
            callback(new Error("优惠券发放数量必须小于99999"));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  voucherId: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.activityType === "COMMENT" && activityModel.value.rewardType === "VOUCHER") {
          if (!value) {
            callback(new Error("请选择代金券"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  voucherQuantity: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.activityType === "COMMENT" && activityModel.value.rewardType === "VOUCHER") {
          if (!value) {
            callback(new Error("请输入代金券发放数量"));
            return;
          }
          const numValue = Number(value);
          if (isNaN(numValue) || !Number.isInteger(numValue) || numValue <= 0) {
            callback(new Error("代金券发放数量必须为正整数"));
            return;
          }
          if (numValue > 99999) {
            callback(new Error("代金券发放数量必须小于99999"));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  signupTimeRange: [
    { required: true, message: "请选择报名时间", trigger: "change" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.activityType === "MARKETING") {
          if (!value || !Array.isArray(value) || value.length !== 2) {
            callback(new Error("请选择报名时间"));
            return;
          }
          const [startTime, endTime] = value;
          if (!startTime || !endTime) {
            callback(new Error("请选择完整的报名时间"));
            return;
          }
          const start = new Date(startTime);
          const end = new Date(endTime);
          start.setHours(0, 0, 0, 0);
          end.setHours(0, 0, 0, 0);
          if (start.getTime() >= end.getTime()) {
            callback(new Error("报名开始时间必须早于报名结束时间"));
            return;
          }
          // 报名时间必须在活动时间范围内（活动开始日期～活动结束日期）
          if (
            activityModel.value.activityTimeRange &&
            Array.isArray(activityModel.value.activityTimeRange) &&
            activityModel.value.activityTimeRange.length === 2
          ) {
            const activityStart = new Date(activityModel.value.activityTimeRange[0]);
            activityStart.setHours(0, 0, 0, 0);
            const activityEnd = new Date(activityModel.value.activityTimeRange[1]);
            activityEnd.setHours(0, 0, 0, 0);

            if (start.getTime() < activityStart.getTime()) {
              callback(new Error("报名开始时间必须在活动时间范围内"));
              return;
            }
            if (end.getTime() > activityEnd.getTime()) {
              callback(new Error("报名结束时间必须在活动时间范围内"));
              return;
            }
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  activityDetails: [
    { required: true, message: "请输入活动详情", trigger: ["blur", "change"] },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.activityType === "MARKETING") {
          if (!value || value.trim() === "") {
            callback(new Error("请输入活动详情"));
            return;
          }
        }
        callback();
      },
      trigger: ["blur", "change"]
    }
  ],
  uploadImgType: [{ required: true, message: "请选择上传图片方式", trigger: "change" }],
  imgDescribe: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.uploadImgType === 2) {
          if (!value || value.trim() === "") {
            callback(new Error("请输入图片描述"));
            return;
          }
        }
        callback();
      },
      trigger: ["blur", "change"]
    }
  ],
  activityTitleImage: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.uploadImgType === 1) {
          if (!titleImageUrl.value) {
            callback(new Error("请上传活动标题图"));
            return;
          }
        }
        callback();
      },
      trigger: ["change", "blur"]
    }
  ],
  activityDetailImage: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (activityModel.value.uploadImgType === 1) {
          // 检查是否有成功上传的图片
          const successFiles = detailFileList.value.filter((f: any) => f.status === "success" && f.url);
          if (successFiles.length === 0) {
            callback(new Error("请上传活动详情图"));
            return;
          }
        }
        callback();
      },
      trigger: ["change", "blur"]
    }
  ]
});

// ==================== 活动信息数据模型 ====================
const activityModel = ref<any>({
  // 活动类型：'MARKETING'-营销活动，'COMMENT'-评论有礼
  activityType: "MARKETING",
  // 活动宣传图（包含标题和详情）
  promotionImages: null,
  // 活动标题图片
  activityTitleImg: null,
  // 活动详情图片
  activityDetailImg: null,
  // 活动标题图（用于表单验证）
  activityTitleImage: null,
  // 活动详情图（用于表单验证）
  activityDetailImage: null,
  // 活动名称
  activityName: "",
  // 活动时间范围
  activityTimeRange: [],
  // 用户可参与次数（评论有礼）
  participationLimit: "",
  // 券类型：'COUPON'-优惠券，'VOUCHER'-代金券（评论有礼）
  rewardType: "COUPON",
  // 优惠券ID（评论有礼）
  couponId: "",
  // 优惠券名称（评论有礼）
  couponName: "",
  // 优惠券发放数量（评论有礼）
  couponQuantity: "",
  // 代金券ID（评论有礼）
  voucherId: "",
  // 代金券名称（评论有礼）
  voucherName: "",
  // 代金券发放数量（评论有礼）
  voucherQuantity: "",
  // 报名时间范围（营销活动）
  signupTimeRange: [],
  // 活动限制人数（营销活动）
  activityLimitPeople: "",
  // 活动详情（营销活动）
  activityDetails: "",
  // 上传图片方式：1-正常用户，2-使用描述
  uploadImgType: 1,
  // 图片描述（当uploadImgType为2时使用）
  imgDescribe: ""
});

// ==================== 日期选择器禁用规则 ====================

// 禁用日期（不能早于今天）
const disabledDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

// 禁用报名日期：只能选择活动时间范围内的日期（在活动开始日期与结束日期之间）
const disabledSignupDate = (time: Date) => {
  const t = new Date(time);
  t.setHours(0, 0, 0, 0);

  // 未选择活动时间时，不允许选择报名日期
  if (!activityModel.value.activityTimeRange || activityModel.value.activityTimeRange.length !== 2) {
    return true;
  }

  const activityStart = new Date(activityModel.value.activityTimeRange[0]);
  activityStart.setHours(0, 0, 0, 0);
  const activityEnd = new Date(activityModel.value.activityTimeRange[1]);
  activityEnd.setHours(0, 0, 0, 0);

  // 只能选择活动时间区域内的日期：早于活动开始或晚于活动结束的日期禁用
  if (t.getTime() < activityStart.getTime()) return true;
  if (t.getTime() > activityEnd.getTime()) return true;
  return false;
};

// ==================== 图片参数转换函数 ====================

/**
 * 图片URL转换为upload组件的参数
 * @param imageUrl 图片URL
 * @returns UploadFile对象
 */
const handleImageParam = (imageUrl: string): UploadFile => {
  // 使用split方法以'/'为分隔符将URL拆分成数组
  const parts = imageUrl.split("/");
  // 取数组的最后一项，即图片名称
  const imageName = parts[parts.length - 1];
  return {
    uid: Date.now() + Math.random(),
    name: imageName,
    status: "success",
    percentage: 100,
    url: imageUrl
  } as unknown as UploadFile;
};

// ==================== 文件上传相关函数 ====================

/**
 * 检查文件是否在排队中（未上传）
 */
const isFilePending = (file: any): boolean => {
  if (file.status === "ready") {
    return true;
  }
  if (pendingUploadFiles.value.some(item => item.uid === file.uid)) {
    return true;
  }
  return false;
};

/**
 * 图片上传 - 删除前确认
 */
const handleBeforeRemove = async (uploadFile: any, uploadFiles: any[]): Promise<boolean> => {
  if (isFilePending(uploadFile)) {
    ElMessage.warning("图片尚未上传，请等待上传完成后再删除");
    return false;
  }
  try {
    await ElMessageBox.confirm("确定要删除这张图片吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    return true;
  } catch {
    return false;
  }
};

/**
 * 活动标题图片上传 - 移除图片回调
 */
const handleTitleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  const file = uploadFile as any;
  const imageUrl = file.url;

  if (imageUrl) {
    titleImageUrl.value = "";
    activityModel.value.activityTitleImg = null;
    activityModel.value.activityTitleImage = null;
    // 触发表单验证
    nextTick(() => {
      ruleFormRef.value?.validateField("activityTitleImage");
    });
  }

  if (file.url && file.url.startsWith("blob:")) {
    URL.revokeObjectURL(file.url);
  }
  titleFileList.value = [...uploadFiles];
  ElMessage.success("图片已删除");
};

/**
 * 活动详情图片上传 - 移除图片回调
 */
const handleDetailRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  const file = uploadFile as any;
  const imageUrl = file.url;

  // 更新图片URL列表（移除已删除的图片）
  const successFiles = uploadFiles.filter((f: any) => f.status === "success" && f.url);
  const imageUrls = successFiles.map((f: any) => f.url);
  detailImageUrl.value = imageUrls.length > 0 ? imageUrls.join(",") : "";
  activityModel.value.activityDetailImg = imageUrls.length > 0 ? { url: imageUrls.join(",") } : null;
  activityModel.value.activityDetailImage = imageUrls.length > 0 ? imageUrls.join(",") : "";

  // 触发表单验证
  nextTick(() => {
    ruleFormRef.value?.validateField("activityDetailImage");
  });

  if (file.url && file.url.startsWith("blob:")) {
    URL.revokeObjectURL(file.url);
  }
  detailFileList.value = [...uploadFiles];
  ElMessage.success("图片已删除");
};

/**
 * 上传文件超出限制提示（标题图）
 */
const handleUploadExceed: UploadProps["onExceed"] = () => {
  ElMessage.warning("最多只能上传1张图片");
};

/**
 * 活动详情图上传超出限制提示
 */
const handleDetailUploadExceed: UploadProps["onExceed"] = () => {
  ElMessage.warning("最多只能上传9张图片");
};

/**
 * 活动标题图片上传 - 文件变更
 */
const handleTitleUploadChange: UploadProps["onChange"] = async (uploadFile, uploadFiles) => {
  if (uploadFile.raw) {
    const fileType = uploadFile.raw.type.toLowerCase();
    const fileName = uploadFile.name.toLowerCase();
    const validTypes = ["image/jpeg", "image/jpg", "image/png"];
    const validExtensions = [".jpg", ".jpeg", ".png"];

    const isValidType = validTypes.includes(fileType) || validExtensions.some(ext => fileName.endsWith(ext));

    if (!isValidType) {
      // 从文件列表中移除不符合类型的文件
      const index = titleFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
      if (index > -1) {
        titleFileList.value.splice(index, 1);
      }
      // 从 uploadFiles 中移除
      const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
      if (uploadIndex > -1) {
        uploadFiles.splice(uploadIndex, 1);
      }
      // 如果文件有 blob URL，释放它
      if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
        URL.revokeObjectURL(uploadFile.url);
      }
      ElMessage.warning("只支持上传 JPG、JPEG 和 PNG 格式的图片");
      return;
    }

    // 检查文件大小，不得超过5M
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (uploadFile.raw.size > maxSize) {
      // 从文件列表中移除超过大小的文件
      const index = titleFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
      if (index > -1) {
        titleFileList.value.splice(index, 1);
      }
      // 从 uploadFiles 中移除
      const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
      if (uploadIndex > -1) {
        uploadFiles.splice(uploadIndex, 1);
      }
      // 如果文件有 blob URL，释放它
      if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
        URL.revokeObjectURL(uploadFile.url);
      }
      ElMessage.warning("上传图片不得超过5M");
      return;
    }
  }

  const existingIndex = titleFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  if (existingIndex === -1) {
    titleFileList.value.push(uploadFile);
  }

  const readyFiles = titleFileList.value.filter(file => file.status === "ready");
  if (readyFiles.length) {
    readyFiles.forEach(file => {
      if (!pendingUploadFiles.value.some(item => item.uid === file.uid)) {
        pendingUploadFiles.value.push(file);
      }
    });
  }
  processUploadQueue("title");
};

/**
 * 活动详情图片上传 - 文件变更
 */
const handleDetailUploadChange: UploadProps["onChange"] = async (uploadFile, uploadFiles) => {
  if (uploadFile.raw) {
    const fileType = uploadFile.raw.type.toLowerCase();
    const fileName = uploadFile.name.toLowerCase();
    const validTypes = ["image/jpeg", "image/jpg", "image/png"];
    const validExtensions = [".jpg", ".jpeg", ".png"];

    const isValidType = validTypes.includes(fileType) || validExtensions.some(ext => fileName.endsWith(ext));

    if (!isValidType) {
      // 从文件列表中移除不符合类型的文件
      const index = detailFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
      if (index > -1) {
        detailFileList.value.splice(index, 1);
      }
      // 从 uploadFiles 中移除
      const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
      if (uploadIndex > -1) {
        uploadFiles.splice(uploadIndex, 1);
      }
      // 如果文件有 blob URL，释放它
      if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
        URL.revokeObjectURL(uploadFile.url);
      }
      ElMessage.warning("只支持上传 JPG、JPEG 和 PNG 格式的图片");
      return;
    }

    // 检查文件大小，不得超过5M
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (uploadFile.raw.size > maxSize) {
      // 从文件列表中移除超过大小的文件
      const index = detailFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
      if (index > -1) {
        detailFileList.value.splice(index, 1);
      }
      // 从 uploadFiles 中移除
      const uploadIndex = uploadFiles.findIndex((f: any) => f.uid === uploadFile.uid);
      if (uploadIndex > -1) {
        uploadFiles.splice(uploadIndex, 1);
      }
      // 如果文件有 blob URL，释放它
      if (uploadFile.url && uploadFile.url.startsWith("blob:")) {
        URL.revokeObjectURL(uploadFile.url);
      }
      ElMessage.warning("上传图片不得超过5M");
      return;
    }
  }

  const existingIndex = detailFileList.value.findIndex((f: any) => f.uid === uploadFile.uid);
  if (existingIndex === -1) {
    detailFileList.value.push(uploadFile);
  }

  const readyFiles = detailFileList.value.filter(file => file.status === "ready");
  if (readyFiles.length) {
    readyFiles.forEach(file => {
      if (!pendingUploadFiles.value.some(item => item.uid === file.uid)) {
        pendingUploadFiles.value.push(file);
      }
    });
  }
  processUploadQueue("detail");
};

/**
 * 处理上传队列 - 逐个上传文件
 */
const processUploadQueue = async (type: string) => {
  if (uploading.value || pendingUploadFiles.value.length === 0) {
    return;
  }
  const file = pendingUploadFiles.value.shift();
  if (file) {
    await uploadSingleFile(file, type);
    processUploadQueue(type);
  }
};

/**
 * 单文件上传图片
 */
const uploadSingleFile = async (file: UploadFile, uploadType: string) => {
  if (!file.raw) {
    return;
  }
  const rawFile = file.raw as File;
  const formData = new FormData();
  formData.append("file", rawFile);
  formData.append("user", "text");
  file.status = "uploading";
  file.percentage = 0;
  uploading.value = true;

  try {
    const result: any = await uploadContractImage(formData);
    if (result?.code === 200 && result.data) {
      let imageUrl = result.data[0];
      if (!imageUrl) {
        throw new Error("上传成功但未获取到图片URL");
      }

      file.status = "success";
      file.percentage = 100;
      file.url = imageUrl;
      file.response = { url: imageUrl };

      if (uploadType === "title") {
        titleImageUrl.value = imageUrl;
        activityModel.value.activityTitleImg = { url: imageUrl };
        activityModel.value.activityTitleImage = imageUrl;
        // 触发表单验证
        nextTick(() => {
          ruleFormRef.value?.validateField("activityTitleImage");
        });
      } else if (uploadType === "detail") {
        // 支持多张图片，将所有成功上传的图片URL组合
        const successFiles = detailFileList.value.filter((f: any) => f.status === "success" && f.url);
        const imageUrls = successFiles.map((f: any) => f.url);
        // 如果有多张图片，用逗号连接；如果只有一张，保持字符串格式
        detailImageUrl.value = imageUrls.length > 0 ? imageUrls.join(",") : "";
        activityModel.value.activityDetailImg = imageUrls.length > 0 ? { url: imageUrls.join(",") } : null;
        activityModel.value.activityDetailImage = imageUrls.length > 0 ? imageUrls.join(",") : "";
        // 触发表单验证
        nextTick(() => {
          ruleFormRef.value?.validateField("activityDetailImage");
        });
      }
    } else {
      throw new Error(result?.msg || "图片上传失败");
    }
  } catch (error: any) {
    // 上传失败时保持进度条为 0
    file.percentage = 0;
    // 不要设置 file.status = "fail"，直接移除文件，避免显示错误占位图
    if (file.url && file.url.startsWith("blob:")) {
      URL.revokeObjectURL(file.url);
    }
    // 从文件列表中移除失败的文件
    const index =
      uploadType === "title"
        ? titleFileList.value.findIndex((f: any) => f.uid === file.uid)
        : detailFileList.value.findIndex((f: any) => f.uid === file.uid);
    if (index > -1) {
      if (uploadType === "title") {
        titleFileList.value.splice(index, 1);
      } else {
        detailFileList.value.splice(index, 1);
      }
    }
    // Error message handled by global upload method, except for specific business logic errors
    if (error?.message && error.message.includes("未获取到图片URL")) {
      ElMessage.error(error.message);
    }
  } finally {
    uploading.value = false;
    // 触发视图更新
    if (uploadType === "title") {
      titleFileList.value = [...titleFileList.value];
    } else {
      detailFileList.value = [...detailFileList.value];
    }
  }
};

/**
 * 图片预览
 */
const handlePictureCardPreview = (file: any) => {
  if (isFilePending(file)) {
    ElMessage.warning("图片尚未上传，请等待上传完成后再预览");
    return;
  }
  if (file.status === "uploading" && file.url) {
    imageViewerUrlList.value = [file.url];
    imageViewerInitialIndex.value = 0;
    imageViewerVisible.value = true;
    return;
  }
  const allFiles = [...titleFileList.value, ...detailFileList.value];
  const urlList = allFiles
    .filter((item: any) => item.status === "success" && (item.url || item.response?.data))
    .map((item: any) => item.url || item.response?.data);
  const currentIndex = urlList.findIndex((url: string) => url === (file.url || file.response?.data));
  if (currentIndex < 0) {
    ElMessage.warning("图片尚未上传完成，无法预览");
    return;
  }
  imageViewerUrlList.value = urlList;
  imageViewerInitialIndex.value = currentIndex;
  imageViewerVisible.value = true;
};

// ==================== 加载优惠券列表函数 ====================

/**
 * 根据券类型加载优惠券/代金券列表
 */
const loadCouponList = async () => {
  if (activityModel.value.activityType !== "COMMENT") return;

  try {
    const params = {
      storeId: localGet("createdId"),
      groupType: localGet("businessSection"),
      couponType: activityModel.value.rewardType === "VOUCHER" ? "1" : "2", // 代金券传1，优惠券传2
      couponStatus: "1",
      couponsFromType: 1,
      pageNum: 1,
      pageSize: 99999
    };
    const res: any = await getCouponList(params);
    if (res && res.code == 200) {
      const isVoucher = activityModel.value.rewardType === "VOUCHER";
      // 代金券(couponType传1)：取 data.couponList；优惠券：取 discountList.records
      if (isVoucher) {
        const raw = res.data.couponList;
        couponList.value = Array.isArray(raw) ? raw : (raw?.records ?? raw?.list ?? []) || [];
      } else {
        couponList.value = res.data?.discountList?.records || [];
      }
    }
  } catch (error) {
    console.error("加载优惠券列表失败:", error);
  }
};

// ==================== 监听器 ====================

/**
 * 监听活动类型变化，切换时清除相关数据并重新验证
 */
watch(
  () => activityModel.value.activityType,
  (newVal, oldVal) => {
    // 如果 oldVal 为空或 undefined，说明是初始化，不处理
    if (oldVal === undefined || oldVal === null || oldVal === "") return;
    // 如果新旧值相同，不处理
    if (newVal === oldVal) return;

    nextTick(() => {
      // 兼容旧数据：如果传入的是数字，转换为字符串
      let typeValue = newVal;
      if (typeValue == 1 || typeValue == "1") {
        typeValue = "MARKETING";
      } else if (typeValue == 2 || typeValue == "2") {
        typeValue = "COMMENT";
      }

      if (typeValue === "MARKETING") {
        // 切换到营销活动：清除评论有礼相关字段
        activityModel.value.participationLimit = "";
        activityModel.value.rewardType = "COUPON";
        activityModel.value.couponId = "";
        activityModel.value.couponName = "";
        activityModel.value.couponQuantity = "";
        activityModel.value.voucherId = "";
        activityModel.value.voucherName = "";
        activityModel.value.voucherQuantity = "";
        couponList.value = [];
        // 清除评论有礼字段的验证状态
        ruleFormRef.value?.clearValidate([
          "participationLimit",
          "rewardType",
          "couponId",
          "couponQuantity",
          "voucherId",
          "voucherQuantity"
        ]);
      } else if (typeValue === "COMMENT") {
        // 切换到评论有礼：清除营销活动相关字段
        activityModel.value.signupTimeRange = [];
        activityModel.value.activityLimitPeople = "";
        activityModel.value.activityDetails = "";
        // 清除营销活动字段的验证状态
        ruleFormRef.value?.clearValidate(["signupTimeRange", "activityLimitPeople", "activityDetails"]);
        // 加载优惠券列表
        loadCouponList();
      }
    });
  },
  { immediate: false }
);

/**
 * 监听券类型变化，切换时重新加载列表并清空已选券
 */
watch(
  () => activityModel.value.rewardType,
  (newVal, oldVal) => {
    if (oldVal === undefined) return; // 初始化时不处理
    if (newVal === oldVal) return;
    if (activityModel.value.activityType !== "COMMENT") return; // 只有评论有礼才处理

    nextTick(() => {
      // 清空已选券（根据类型清空对应字段）
      if (newVal === "VOUCHER") {
        activityModel.value.voucherId = "";
        activityModel.value.voucherName = "";
        activityModel.value.voucherQuantity = "";
        ruleFormRef.value?.clearValidate(["voucherId", "voucherQuantity"]);
      } else {
        activityModel.value.couponId = "";
        activityModel.value.couponName = "";
        activityModel.value.couponQuantity = "";
        ruleFormRef.value?.clearValidate(["couponId", "couponQuantity"]);
      }
      couponList.value = [];
      // 重新加载列表
      loadCouponList();
    });
  }
);

/**
 * 监听上传图片方式变化，切换时清除相关数据并重新验证
 */
watch(
  () => activityModel.value.uploadImgType,
  (newVal, oldVal) => {
    if (oldVal === undefined) return; // 初始化时不处理

    nextTick(() => {
      if (newVal === 2) {
        // 切换到使用描述：清除图片数据
        titleFileList.value = [];
        detailFileList.value = [];
        titleImageUrl.value = "";
        detailImageUrl.value = "";
        activityModel.value.activityTitleImg = null;
        activityModel.value.activityDetailImg = null;
        activityModel.value.activityTitleImage = null;
        activityModel.value.activityDetailImage = null;
        // 清除图片字段的验证
        ruleFormRef.value?.clearValidate(["activityTitleImage", "activityDetailImage"]);
        // 验证描述字段
        ruleFormRef.value?.validateField("imgDescribe");
      } else if (newVal === 1) {
        // 切换到正常用户：清除描述数据
        activityModel.value.imgDescribe = "";
        // 清除描述字段的验证
        ruleFormRef.value?.clearValidate("imgDescribe");
        // 验证图片字段
        ruleFormRef.value?.validateField(["activityTitleImage", "activityDetailImage"]);
      }
    });
  }
);

/**
 * 监听活动时间变化，如果报名时间不在新的活动时间范围内则清空并提示
 */
watch(
  () => activityModel.value.activityTimeRange,
  (newVal, oldVal) => {
    // 初始化时不处理
    if (oldVal === undefined || oldVal === null) return;

    // 只有营销活动才需要检查报名时间
    if (activityModel.value.activityType !== "MARKETING") return;

    // 如果活动时间已选择且报名时间已选择
    if (
      newVal &&
      newVal.length === 2 &&
      activityModel.value.signupTimeRange &&
      activityModel.value.signupTimeRange.length === 2
    ) {
      const activityStart = new Date(newVal[0]);
      activityStart.setHours(0, 0, 0, 0);
      const activityEnd = new Date(newVal[1]);
      activityEnd.setHours(0, 0, 0, 0);
      const signupStart = new Date(activityModel.value.signupTimeRange[0]);
      signupStart.setHours(0, 0, 0, 0);
      const signupEnd = new Date(activityModel.value.signupTimeRange[1]);
      signupEnd.setHours(0, 0, 0, 0);

      // 报名时间必须在活动时间范围内，否则清空报名时间并提示
      const outOfRange = signupStart.getTime() < activityStart.getTime() || signupEnd.getTime() > activityEnd.getTime();
      if (outOfRange) {
        activityModel.value.signupTimeRange = [];
        nextTick(() => {
          ruleFormRef.value?.clearValidate("signupTimeRange");
          ElMessage.warning("活动时间已调整，报名时间必须在活动时间范围内，请重新选择报名时间");
        });
      } else {
        nextTick(() => {
          ruleFormRef.value?.validateField("signupTimeRange");
        });
      }
    }
  }
);

// ==================== 生命周期钩子 ====================

/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  id.value = (route.query.id as string) || "";
  type.value = (route.query.type as string) || "";

  // 如果是评论有礼类型，初始化时加载优惠券列表
  if (activityModel.value.activityType === "COMMENT") {
    await loadCouponList();
  }

  // 编辑模式下加载数据
  if (type.value != "add" && id.value) {
    try {
      const res: any = await getActivityDetail({ id: id.value });
      if (res && res.code == 200) {
        // 兼容旧数据：如果后端返回的是数字，转换为字符串
        if (res.data.activityType !== undefined) {
          let activityTypeValue = res.data.activityType;
          if (activityTypeValue == 1 || activityTypeValue == "1") {
            activityTypeValue = "MARKETING";
          } else if (activityTypeValue == 2 || activityTypeValue == "2") {
            activityTypeValue = "COMMENT";
          }
          activityModel.value.activityType = activityTypeValue;
        }

        // 合并其他数据
        activityModel.value.activityName = res.data.activityName || "";

        // 处理活动时间范围
        if (res.data.startTime && res.data.endTime) {
          // 只取日期部分（去掉时分秒）
          const startDate = res.data.startTime.split(" ")[0];
          const endDate = res.data.endTime.split(" ")[0];
          activityModel.value.activityTimeRange = [startDate, endDate];
        }

        // 根据活动类型加载对应字段
        if (activityModel.value.activityType === "MARKETING") {
          // 营销活动：加载报名时间、活动限制人数、活动详情
          if (res.data.signupStartTime && res.data.signupEndTime) {
            // 只取日期部分（去掉时分秒）
            const signupStartDate = res.data.signupStartTime.split(" ")[0];
            const signupEndDate = res.data.signupEndTime.split(" ")[0];
            activityModel.value.signupTimeRange = [signupStartDate, signupEndDate];
          } else {
            activityModel.value.signupTimeRange = [];
          }
          // 加载活动限制人数
          if (res.data.activityLimitPeople !== undefined && res.data.activityLimitPeople !== null) {
            activityModel.value.activityLimitPeople = String(res.data.activityLimitPeople);
          } else {
            activityModel.value.activityLimitPeople = "";
          }
          // 加载活动详情
          activityModel.value.activityDetails = res.data.activityDetails || "";
        } else if (activityModel.value.activityType === "COMMENT") {
          // 评论有礼：加载活动规则、券类型、优惠券/代金券、发放数量、用户可参与次数
          // 加载券类型（'COUPON'-优惠券，'VOUCHER'-代金券）
          // 兼容旧数据：如果后端返回的是数字，转换为新格式
          if (res.data.rewardType) {
            activityModel.value.rewardType = res.data.rewardType;
          } else if (res.data.couponType !== undefined) {
            // 兼容旧数据格式：1->COUPON, 4->VOUCHER
            activityModel.value.rewardType = res.data.couponType === 4 ? "VOUCHER" : "COUPON";
          } else {
            activityModel.value.rewardType = "COUPON";
          }
          // 根据 rewardType 加载对应的字段
          if (activityModel.value.rewardType === "VOUCHER") {
            activityModel.value.voucherId = res.data.voucherId || "";
            activityModel.value.voucherName = res.data.voucherName || "";
            if (res.data.voucherQuantity !== undefined && res.data.voucherQuantity !== null) {
              activityModel.value.voucherQuantity = String(res.data.voucherQuantity);
            } else {
              activityModel.value.voucherQuantity = "";
            }
          } else {
            activityModel.value.couponId = res.data.couponId || "";
            activityModel.value.couponName = res.data.couponName || "";
            if (res.data.couponQuantity !== undefined && res.data.couponQuantity !== null) {
              activityModel.value.couponQuantity = String(res.data.couponQuantity);
            } else {
              activityModel.value.couponQuantity = "";
            }
          }
          // 加载用户可参与次数
          if (res.data.participationLimit !== undefined && res.data.participationLimit !== null) {
            activityModel.value.participationLimit = String(res.data.participationLimit);
          } else {
            activityModel.value.participationLimit = "";
          }
          // 根据券类型加载对应的列表
          await loadCouponList();
        }
        // 编辑模式：默认使用本地上传模式（uploadImgType=1），以便编辑图片和banner图
        activityModel.value.uploadImgType = 1; // 编辑时固定为1-本地上传
        // 加载图片描述（保留原始数据，但不影响显示）
        if (res.data.imgDescribe) {
          activityModel.value.imgDescribe = res.data.imgDescribe;
        } else {
          activityModel.value.imgDescribe = "";
        }
        // 编辑模式：始终加载图片数据（无论原始uploadImgType是什么）
        // 如果有标题图片，添加到文件列表
        if (res.data.activityTitleImgUrl) {
          const titleImgUrl = res.data.activityTitleImgUrl;
          if (titleImgUrl) {
            titleImageUrl.value = titleImgUrl;
            activityModel.value.activityTitleImg = res.data.activityTitleImgUrl;
            activityModel.value.activityTitleImage = titleImgUrl;
            const titleFile = handleImageParam(titleImgUrl);
            titleFileList.value = [titleFile];
          }
        }
        // 如果有详情图片，添加到文件列表（支持多张图片，可能是字符串或数组）
        if (res.data.activityDetailImgUrl) {
          let detailImgUrls: string[] = [];
          // 如果是字符串，可能是逗号分隔的多张图片
          if (typeof res.data.activityDetailImgUrl === "string") {
            detailImgUrls = res.data.activityDetailImgUrl.split(",").filter((url: string) => url.trim());
          } else if (Array.isArray(res.data.activityDetailImgUrl)) {
            detailImgUrls = res.data.activityDetailImgUrl.filter((url: any) => url);
          }

          if (detailImgUrls.length > 0) {
            detailImageUrl.value = detailImgUrls.join(",");
            activityModel.value.activityDetailImg = res.data.activityDetailImgUrl;
            activityModel.value.activityDetailImage = detailImgUrls.join(",");
            // 将多张图片添加到文件列表
            detailFileList.value = detailImgUrls.map((url: string) => handleImageParam(url));
          }
        }
      }
    } catch (error) {
      console.error("加载活动详情失败:", error);
      ElMessage.error("加载活动详情失败");
    }
  }
  await nextTick();
  ruleFormRef.value?.clearValidate();
});

// ==================== 事件处理函数 ====================

/**
 * 处理正整数输入（只允许输入正整数）
 */
const handlePositiveIntegerInput = (field: string, value: string) => {
  // 移除所有非数字字符
  let filteredValue = value.replace(/[^\d]/g, "");

  // 限制最大长度为20
  if (filteredValue.length > 20) {
    filteredValue = filteredValue.substring(0, 20);
  }

  // 更新对应字段的值
  if (field === "activityLimitPeople") {
    activityModel.value.activityLimitPeople = filteredValue;
  }
};

/**
 * 返回上一页
 */
const goBack = () => {
  router.go(-1);
};

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!ruleFormRef.value) return;

  // 如果选择正常用户方式且有未上传的图片，阻止提交
  if (activityModel.value.uploadImgType === 1 && hasUnuploadedImages.value) {
    ElMessage.warning("请等待图片上传完成后再提交");
    return;
  }

  await ruleFormRef.value.validate(async valid => {
    if (valid) {
      const [activityStartDate, activityEndDate] = activityModel.value.activityTimeRange || [];
      // 活动时间：开始日期传当天 00:00:00，结束日期传当天 23:59:59
      const startTime = activityStartDate ? `${activityStartDate} 00:00:00` : "";
      const endTime = activityEndDate ? `${activityEndDate} 23:59:59` : "";
      const auditParam = {
        text: `${activityModel.value.activityName}, ${activityModel.value.imgDescribe || ""}`,
        image_urls: [titleImageUrl.value, detailImageUrl.value]
      };
      const params: any = {
        activityType: activityModel.value.activityType,
        activityName: activityModel.value.activityName,
        startTime,
        endTime,
        uploadImgType: activityModel.value.uploadImgType,
        storeId: localGet("createdId"),
        groupType: localGet("businessSection"),
        status: 1, // 1-待审核
        auditParam: JSON.stringify(auditParam)
      };

      // 根据活动类型添加不同的字段，确保只提交对应类型的字段
      if (activityModel.value.activityType === "MARKETING") {
        // 营销活动：只添加营销活动相关字段；报名时间开始传当天 00:00:00，结束传当天 23:59:59
        const [signupStartDate, signupEndDate] = activityModel.value.signupTimeRange || [];
        params.signupStartTime = signupStartDate ? `${signupStartDate} 00:00:00` : "";
        params.signupEndTime = signupEndDate ? `${signupEndDate} 23:59:59` : "";
        params.activityLimitPeople = activityModel.value.activityLimitPeople;
        params.activityDetails = activityModel.value.activityDetails;
        // 确保不包含评论有礼的字段
        delete params.participationLimit;
        delete params.rewardType;
        delete params.couponId;
        delete params.couponQuantity;
      } else if (activityModel.value.activityType === "COMMENT") {
        // 评论有礼：只添加评论有礼相关字段
        params.participationLimit = activityModel.value.participationLimit;
        params.rewardType = activityModel.value.rewardType; // 'COUPON'-优惠券，'VOUCHER'-代金券
        // 根据 rewardType 提交对应的字段
        if (activityModel.value.rewardType === "VOUCHER") {
          params.voucherId = activityModel.value.voucherId;
          params.voucherQuantity = activityModel.value.voucherQuantity;
        } else {
          params.couponId = activityModel.value.couponId;
          params.couponQuantity = activityModel.value.couponQuantity;
        }
        // 确保不包含营销活动的字段
        delete params.signupStartTime;
        delete params.signupEndTime;
        delete params.activityLimitPeople;
        delete params.activityDetails;
      }

      // 根据上传图片方式设置不同的参数
      if (activityModel.value.uploadImgType === 1) {
        // 正常用户：上传图片
        params.activityTitleImg = {
          imgUrl: titleImageUrl.value,
          imgSort: 0,
          storeId: localGet("createdId")
        };
        params.activityDetailImg = {
          imgUrl: detailImageUrl.value,
          imgSort: 0,
          storeId: localGet("createdId")
        };
      } else if (activityModel.value.uploadImgType === 2) {
        // 使用描述：提交描述文本，但依然保留图片字段，imgUrl为空
        params.imgDescribe = activityModel.value.imgDescribe;
        params.activityTitleImg = {
          imgUrl: "",
          imgSort: 0,
          storeId: localGet("createdId")
        };
        params.activityDetailImg = {
          imgUrl: "",
          imgSort: 0,
          storeId: localGet("createdId")
        };
      }

      try {
        let res: any;
        if (type.value == "add") {
          res = await addActivity(params);
        } else {
          params.id = id.value;
          res = await updateActivity(params);
        }

        if (res && res.code == 200) {
          ElMessage.success(type.value == "add" ? "新增成功" : "编辑成功");
          goBack();
        } else {
          ElMessage.error(res?.msg || "操作失败");
        }
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};
</script>

<style lang="scss" scoped>
/* 页面容器 */
.table-box {
  display: flex;
  flex-direction: column;
  height: auto !important;
  min-height: 100%;
}

/* 头部区域 */
.header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 24px;
  background-color: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgb(0 0 0 / 2%);
}
.title {
  flex: 1;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  text-align: center;
}

/* 表单内容区域 */
.form-content {
  padding: 24px;
  background-color: #ffffff;
}

/* 表单包装器 */
.form-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #ffffff;
  .form-wrapper-main {
    width: 100%;
    max-width: 800px;
  }
}

/* 上传项容器 */
.upload-item-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-start;
  width: 100%;
}
.upload-hint {
  margin-top: 4px;
  font-size: 12px;
  line-height: 1.5;
  color: #909399;
}

/* 规则表格容器 */
.rule-table-container {
  margin-top: 20px;
}

/* 底部按钮区域 */
.button-container {
  display: flex;
  gap: 20px;
  justify-content: center;
  padding-bottom: 15px;
  background-color: #ffffff;
}
.upload-area {
  width: 100%;
  :deep(.el-upload--picture-card) {
    width: 100%;
    height: 180px;
  }
  :deep(.el-upload-list--picture-card) {
    width: 100%;
    .el-upload-list__item {
      width: 100%;
      height: 180px;
      margin: 0;
    }
  }
  :deep(.el-upload-list--picture-card .el-upload-list__item:hover .el-upload-list__item-status-label) {
    display: inline-flex !important;
    opacity: 1 !important;
  }
  :deep(.el-upload-list__item.is-success:focus .el-upload-list__item-status-label) {
    display: inline-flex !important;
    opacity: 1 !important;
  }
  :deep(.el-upload-list--picture-card .el-icon--close-tip) {
    display: none !important;
  }
  &.upload-full {
    :deep(.el-upload--picture-card) {
      display: none !important;
    }
  }

  // 21:9横向图片样式
  &.upload-area-horizontal-21-9 {
    :deep(.el-upload--picture-card) {
      width: 100%;
      height: auto;
      aspect-ratio: 21 / 9;
    }
    :deep(.el-upload-list--picture-card) {
      width: 100%;
      .el-upload-list__item {
        width: 100%;
        height: auto;
        aspect-ratio: 21 / 9;
        margin: 0;
      }
    }
  }

  // 竖版图片样式
  &.upload-area-vertical {
    :deep(.el-upload--picture-card) {
      width: 150px;
      height: 150px;
    }
    :deep(.el-upload-list--picture-card) {
      .el-upload-list__item {
        width: 150px;
        height: 150px;
        margin: 0;
      }
    }
  }
}
.upload-trigger-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 28px;
  color: #8c939d;
}

/* el-upload 图片预览铺满容器 */
:deep(.el-upload-list--picture-card) {
  .el-upload-list__item {
    margin: 0;
    overflow: hidden;
    .el-upload-list__item-thumbnail {
      width: 100%;
      height: 100%;

      //object-fit: fill;
    }
  }
  .el-upload-list__item[data-status="ready"],
  .el-upload-list__item.is-ready {
    position: relative;
    pointer-events: none;
    cursor: not-allowed;
    opacity: 0.6;
    &::after {
      position: absolute;
      inset: 0;
      z-index: 1;
      content: "";
      background-color: rgb(0 0 0 / 30%);
    }
    .el-upload-list__item-actions {
      pointer-events: none;
      opacity: 0.5;
    }
  }
  .el-upload-list__item:hover .el-upload-list__item-status-label {
    display: inline-flex !important;
    opacity: 1 !important;
  }
  .el-upload-list__item.is-success:focus .el-upload-list__item-status-label {
    display: inline-flex !important;
    opacity: 1 !important;
  }
  .el-icon--close-tip {
    display: none !important;
  }
}
</style>
