<template>
  <div class="personnel-config-container">
    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button v-if="!hasTitle" type="primary" @click="handleCreateTitle"> 创建标题 </el-button>
      <el-button type="primary" @click="openCreateDialog"> 创建人员 </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-box button-table">
      <div class="table-header-title">
        <span class="table-title">演出人员</span>
        <el-dropdown v-if="hasTitle" trigger="click" @command="handleTitleCommand">
          <el-icon class="table-icon">
            <ArrowDown />
          </el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="edit"> 编辑标题 </el-dropdown-item>
              <el-dropdown-item command="delete"> 删除标题 </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-icon v-else class="table-icon">
          <ArrowDown />
        </el-icon>
      </div>
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
      >
        <template #empty>
          <div class="personnel-config-empty">暂无数据</div>
        </template>
        <template #operation="scope">
          <!-- 待审核（status === 0）：只显示查看详情 -->
          <template v-if="scope.row.status === 0 || scope.row.status === '0'">
            <el-button type="primary" link @click="handleViewDetail(scope.row)"> 查看详情 </el-button>
          </template>

          <!-- 已驳回（status === 2）：显示编辑、删除、查看详情 -->
          <template v-else-if="scope.row.status === 2 || scope.row.status === '2'">
            <el-button type="primary" link @click="editPersonnel(scope.row, 0)"> 编辑 </el-button>
            <el-button type="primary" link @click="deletePersonnelHandler(scope.row.id!, 0)"> 删除 </el-button>
            <el-button type="primary" link @click="handleViewDetail(scope.row)"> 查看详情 </el-button>
          </template>

          <!-- 已通过（status === 1）：显示编辑、下线、置顶/取消置顶、删除、查看详情 -->
          <template v-else-if="scope.row.status === 1 || scope.row.status === '1'">
            <el-button type="primary" link @click="editPersonnel(scope.row, 0)"> 编辑 </el-button>
            <el-button
              v-if="scope.row.onlineStatus === 0 || scope.row.onlineStatus === '0'"
              type="primary"
              link
              @click="handleOffline(scope.row)"
            >
              下线
            </el-button>
            <el-button
              v-else-if="scope.row.onlineStatus === 1 || scope.row.onlineStatus === '1'"
              type="primary"
              link
              @click="handleOnline(scope.row)"
            >
              上线
            </el-button>
            <el-button
              v-if="scope.row.topStatus === 1 || scope.row.topStatus === '1'"
              type="primary"
              link
              @click="handleUnpin(scope.row)"
            >
              取消置顶
            </el-button>
            <el-button v-else type="primary" link @click="handlePin(scope.row)"> 置顶 </el-button>
            <el-button type="primary" link @click="deletePersonnelHandler(scope.row.id!, 0)"> 删除 </el-button>
            <el-button type="primary" link @click="handleViewDetail(scope.row)"> 查看详情 </el-button>
          </template>

          <!-- 其他状态：默认显示查看详情 -->
          <template v-else>
            <el-button type="primary" link @click="handleViewDetail(scope.row)"> 查看详情 </el-button>
          </template>
        </template>
      </ProTable>
    </div>

    <!-- 创建/修改标题弹窗 -->
    <el-dialog v-model="titleDialogVisible" :title="titleDialogTitle" width="500px" @close="resetTitleForm">
      <el-form ref="titleFormRef" :model="titleFormData" :rules="titleRules" label-width="80px">
        <el-form-item label="名称*" prop="name">
          <el-input v-model="titleFormData.name" placeholder="请输入" maxlength="50" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="titleDialogVisible = false"> 取消 </el-button>
          <el-button type="primary" :loading="titleSubmitLoading" @click="handleTitleSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 人员详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="人员详情" width="600px">
      <div v-loading="detailLoading" class="detail-content">
        <template v-if="personnelDetail">
          <div class="detail-item">
            <div class="detail-label">头像：</div>
            <div class="detail-value">
              <img v-if="personnelDetail.staffImage" :src="personnelDetail.staffImage" alt="头像" class="detail-avatar" />
              <span v-else>—</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">姓名/昵称：</div>
            <div class="detail-value">
              {{ personnelDetail.staffName || personnelDetail.name || "—" }}
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">职位：</div>
            <div class="detail-value">
              {{ personnelDetail.staffPosition || "—" }}
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">擅长：</div>
            <div class="detail-value">
              {{ personnelDetail.proficientProjects || "—" }}
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">标签：</div>
            <div class="detail-value">
              <span v-if="personnelDetail.tag">{{
                personnelDetail.tag
                  .split(",")
                  .filter((t: string) => t.trim())
                  .join(", ")
              }}</span>
              <span v-else>—</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">个人简介：</div>
            <div class="detail-value">
              {{ personnelDetail.personalIntroduction || "—" }}
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">背景：</div>
            <div class="detail-value">
              <div v-if="personnelDetail.backgroundUrl" class="background-images">
                <template v-for="(url, index) in getBackgroundImageList(personnelDetail.backgroundUrl)" :key="index">
                  <div
                    v-if="isVideoBackgroundUrl(url)"
                    class="background-media-item background-media-item--video"
                    @click="previewBackgroundImage(url)"
                  >
                    <video :src="url" class="background-image" muted preload="metadata" playsinline />
                    <span class="background-media-video-badge">
                      <el-icon :size="20"><VideoPlay /></el-icon>
                    </span>
                  </div>
                  <img v-else :src="url" alt="背景图片" class="background-image" @click="previewBackgroundImage(url)" />
                </template>
              </div>
              <span v-else>—</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">在线状态：</div>
            <div class="detail-value">
              <span v-if="personnelDetail.onlineStatus === 0 || personnelDetail.onlineStatus === '0'">上线</span>
              <span v-else-if="personnelDetail.onlineStatus === 1 || personnelDetail.onlineStatus === '1'">下线</span>
              <span v-else>—</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">审核状态：</div>
            <div class="detail-value">
              <el-tag v-if="personnelDetail.status === 1 || personnelDetail.status === '1'" type="success"> 已通过 </el-tag>
              <el-tag v-else-if="personnelDetail.status === 2 || personnelDetail.status === '2'" type="danger"> 已驳回 </el-tag>
              <el-tag v-else-if="personnelDetail.status === 0 || personnelDetail.status === '0'" type="info"> 待审核 </el-tag>
              <span v-else>—</span>
            </div>
          </div>
          <div v-if="personnelDetail.status === 2 || personnelDetail.status === '2'" class="detail-item">
            <div class="detail-label">拒绝原因：</div>
            <div class="detail-value">
              {{ personnelDetail.rejectionReason || "—" }}
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">提交时间：</div>
            <div class="detail-value">
              {{ formatTime(personnelDetail.submissionTime || personnelDetail.createTime || personnelDetail.createdTime) || "—" }}
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">审核时间：</div>
            <div class="detail-value">
              {{ formatTime(personnelDetail.auditTime) || "—" }}
            </div>
          </div>
        </template>
        <el-empty v-else-if="!detailLoading" description="暂无数据" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="detailDialogVisible = false"> 关闭 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 背景图片预览弹窗 -->
    <el-image-viewer v-if="previewImageVisible" :url-list="[previewImageUrl]" @close="previewImageVisible = false" />

    <!-- 背景视频放大预览弹窗 -->
    <el-dialog
      v-model="previewVideoVisible"
      title="视频预览"
      width="70%"
      top="5vh"
      destroy-on-close
      align-center
      @close="previewVideoUrl = ''"
    >
      <div class="video-preview-wrap">
        <video v-if="previewVideoUrl" :src="previewVideoUrl" controls autoplay class="video-preview-player" />
      </div>
    </el-dialog>

    <!-- 新建/编辑人员弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="720px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="头像*" prop="avatar">
          <UploadImg
            v-model:image-url="formData.avatar"
            :width="'150px'"
            :height="'150px'"
            :file-size="9999"
            :api="personnelOssUploadAvatar"
            :file-type="['image/jpeg', 'image/png', 'image/gif', 'image/webp']"
            :border-radius="'8px'"
          />
        </el-form-item>
        <el-form-item label="姓名/昵称*" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" maxlength="20" show-word-limit clearable />
        </el-form-item>
        <el-form-item label="人员职位*" prop="position">
          <el-input v-model="formData.position" placeholder="请输入" maxlength="50" clearable />
        </el-form-item>
        <el-form-item label="背景*" prop="backgroundImages">
          <div class="background-upload-three-col">
            <UploadImgs
              :key="uploadComponentKey"
              ref="backgroundImagesUploadRef"
              v-model:file-list="formData.backgroundImages"
              :limit="9"
              :file-size="100"
              :file-type="['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'video/mp4']"
              :width="'150px'"
              :height="'150px'"
              :border-radius="'8px'"
              :compress="true"
              :api="handleCustomUpload"
              :show-success-notification="false"
              :on-success="handleBackgroundImageSuccess"
              :on-video-preview="handleVideoPreviewInForm"
            >
              <template #tip>
                <div class="upload-tip">上传图片或视频 ({{ formData.backgroundImages.length }}/9)，单个文件不超过 100M</div>
              </template>
            </UploadImgs>
          </div>
        </el-form-item>
        <el-form-item label="擅长" prop="specialty">
          <el-input
            v-model="formData.specialty"
            type="textarea"
            :rows="3"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <div class="tags-container">
            <div v-for="(tag, index) in formData.tags" :key="index" class="tag-input-wrapper">
              <el-input v-model="formData.tags[index]" placeholder="请输入" maxlength="20" clearable />
            </div>
            <div class="tag-actions">
              <el-button v-if="formData.tags.length < 3" :icon="Plus" circle @click="addTag" />
              <el-button v-if="formData.tags.length > 1" :icon="Delete" circle @click="removeTag" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="个人简介" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入"
            maxlength="500"
            show-word-limit
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false"> 取消 </el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ editId ? "确定" : "新建" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Picture, Plus, Delete, ArrowDown, VideoPlay } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import UploadImg from "@/components/Upload/Img.vue";
import UploadImgs from "@/components/Upload/Imgs.vue";
import { uploadFileToOss, uploadFilesToOss } from "@/api/upload.js";
import type { UploadUserFile } from "element-plus";
import { localGet } from "@/utils";
import {
  getPersonnelList,
  getStaffConfigList,
  createOrUpdatePersonnel,
  getPersonnelDetail,
  getStaffConfigDetail,
  deletePersonnel,
  createTitle,
  updateTitle,
  getTitleDetail,
  deleteTitle,
  setTopStatus,
  setOnlineStatus
} from "@/api/modules/storeDecoration";

// 人员接口
interface Personnel {
  id?: string | number;
  name: string;
  position: string;
  avatar: string;
  specialty?: string;
  tags?: string[];
  description?: string;
  onlineStatus?: number | string;
  approvalStatus?: number | string;
  submissionTime?: string;
  createdTime?: string;
  isPinned?: boolean;
}

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const editId = ref<string | number | null>(null);
const proTable = ref<ProTableInstance>();
const backgroundImagesUploadRef = ref<any>(null);
const uploadComponentKey = ref(0); // 用于强制重新渲染上传组件

// 详情相关
const detailDialogVisible = ref(false);
const detailLoading = ref(false);
const personnelDetail = ref<any>(null);
const previewImageVisible = ref(false);
const previewImageUrl = ref("");
const previewVideoVisible = ref(false);
const previewVideoUrl = ref("");

// 标题相关
const hasTitle = ref(false); // 是否已有标题
const titleId = ref<string | number | null>(null); // 标题ID
const titleDialogVisible = ref(false);
const titleFormRef = ref<FormInstance>();
const titleSubmitLoading = ref(false);
const titleEditId = ref<string | number | null>(null);
const titleFormData = reactive({
  name: ""
});

// 标题表单校验规则
const titleRules = reactive<FormRules>({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }]
});

// 标题弹窗标题
const titleDialogTitle = computed(() => (titleEditId.value !== null ? "修改标题" : "创建标题"));

// 在线状态枚举 - 0: 上线, 1: 下线
const onlineStatusEnum = [
  { label: "上线", value: 0 },
  { label: "下线", value: 1 }
];

// 审核状态枚举
const approvalStatusEnum = [
  { label: "待审核", value: 0 },
  { label: "已通过", value: 1 },
  { label: "已驳回", value: 2 }
];

/** 列表/详情：统一为 YYYY-MM-DD HH:mm:ss */
const formatTime = (time: string | null | undefined) => {
  if (!time) return "";
  try {
    const date = new Date(time);
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, "0");
    const d = String(date.getDate()).padStart(2, "0");
    const h = String(date.getHours()).padStart(2, "0");
    const min = String(date.getMinutes()).padStart(2, "0");
    const s = String(date.getSeconds()).padStart(2, "0");
    return `${y}-${m}-${d} ${h}:${min}:${s}`;
  } catch {
    return time;
  }
};

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  {
    prop: "index",
    label: "序号",
    width: 80,
    render: (scope: any) => {
      return scope.$index + (proTable.value!.pageable.pageNum - 1) * proTable.value!.pageable.pageSize + 1;
    }
  },
  {
    prop: "name",
    label: "姓名/昵称",
    minWidth: 120,
    search: {
      el: "input",
      props: { placeholder: "请输入" },
      order: 1
    }
  },
  {
    prop: "position",
    label: "职位",
    minWidth: 100,
    search: {
      el: "input",
      props: { placeholder: "请输入" },
      order: 2
    }
  },
  {
    prop: "tags",
    label: "标签",
    minWidth: 150,
    render: (scope: any) => {
      if (scope.row.tags && scope.row.tags.length > 0) {
        return scope.row.tags.filter((tag: string) => tag.trim()).join(", ");
      }
      return "—";
    }
  },
  {
    prop: "onlineStatus",
    label: "在线状态",
    width: 120,
    enum: onlineStatusEnum,
    fieldNames: { label: "label", value: "value" },
    search: {
      el: "select",
      props: { placeholder: "请选择" },
      order: 3
    },
    render: (scope: any) => {
      if (scope.row.onlineStatus === 0 || scope.row.onlineStatus === "0") return "上线";
      if (scope.row.onlineStatus === 1 || scope.row.onlineStatus === "1") return "下线";
      return "—";
    }
  },
  {
    prop: "approvalStatus",
    label: "审核状态",
    width: 120,
    enum: approvalStatusEnum,
    fieldNames: { label: "label", value: "value" },
    tag: true,
    search: {
      el: "select",
      props: { placeholder: "请选择" },
      order: 4
    },
    render: (scope: any) => {
      if (scope.row.approvalStatus === 1 || scope.row.approvalStatus === "1") return "已通过";
      if (scope.row.approvalStatus === 2 || scope.row.approvalStatus === "2") return "已驳回";
      if (scope.row.approvalStatus === 0 || scope.row.approvalStatus === "0") return "待审核";
      return "—";
    }
  },
  {
    prop: "createdTime",
    label: "提交时间",
    width: 190,
    render: (scope: any) => {
      const t = scope.row.submissionTime || scope.row.createdTime;
      return t ? formatTime(t) : "—";
    },
    search: {
      el: "date-picker",
      props: {
        type: "datetimerange",
        "range-separator": "至",
        "start-placeholder": "开始时间",
        "end-placeholder": "结束时间",
        format: "YYYY-MM-DD HH:mm:ss",
        "value-format": "YYYY-MM-DD HH:mm:ss"
      },
      order: 5,
      span: 2
    }
  },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 350 }
]);

// 初始化参数
const initParam = reactive({
  storeId: localGet("geeker-user")?.userInfo?.storeId || localGet("createdId")
});

// 数据处理回调
const dataCallback = (data: any) => {
  // 处理 API 返回的数据格式
  let dataList: any[] = [];
  let total = 0;

  if (Array.isArray(data)) {
    dataList = data;
    total = data.length;
  } else if (data?.data) {
    if (Array.isArray(data.data)) {
      dataList = data.data;
      total = data.total || data.data.length;
    } else if (data.data?.records) {
      // 分页格式
      dataList = data.data.records || [];
      total = data.data.total || 0;
    }
  } else if (data?.list) {
    dataList = data.list;
    total = data.total || data.list.length;
  } else if (data?.records) {
    dataList = data.records;
    total = data.total || 0;
  }

  const list = dataList.map((person: any) => ({
    id: person.id,
    name: person.staffName || person.name || "", // 优先使用 staffName
    position: person.staffPosition || "",
    avatar: person.staffImage || "",
    specialty: person.proficientProjects || "",
    tags: person.tag ? person.tag.split(",").map((tag: string) => tag.trim()) : [],
    description: person.personalIntroduction || "",
    onlineStatus: person.onlineStatus,
    status: person.status, // 审核状态：0 待审核，1 审核通过，2 审核拒绝
    approvalStatus: person.status, // 保留 approvalStatus 用于表格列显示
    submissionTime: person.submissionTime || person.createTime || person.createdTime,
    createdTime: person.createTime || person.createdTime,
    topStatus: person.topStatus, // 置顶状态：0 未置顶，1 已置顶
    isPinned: person.topStatus === 1 || person.topStatus === "1" || person.isPinned || person.isTop || false // 保留 isPinned 用于兼容
  }));

  return {
    list,
    total
  };
};

// 获取表格列表
const getTableList = (params: any) => {
  const userInfo: any = localGet("geeker-user")?.userInfo || {};
  const storeId = params.storeId || userInfo.storeId || localGet("createdId");

  if (!storeId) {
    console.warn("未找到店铺ID");
    return Promise.resolve({ code: 200, data: [], total: 0 });
  }

  const newParams: any = {
    storeId: Number(storeId),
    pageNum: params.page || params.pageNum || 1,
    pageSize: params.size || params.pageSize || 10
  };

  // 处理搜索参数 - 使用新的字段名
  // 姓名昵称 - 模糊搜索（后端自动处理模糊匹配）
  if (params.name && params.name.trim()) {
    newParams.staffName = params.name.trim(); // 姓名昵称 -> staffName（模糊搜索）
  }
  // 职位 - 模糊搜索
  if (params.position && params.position.trim()) {
    newParams.staffPosition = params.position.trim(); // 职位 -> staffPosition（模糊搜索）
  }
  if (params.onlineStatus !== undefined && params.onlineStatus !== null && params.onlineStatus !== "") {
    newParams.onlineStatus = params.onlineStatus; // 在线状态 -> onlineStatus
  }
  if (params.approvalStatus !== undefined && params.approvalStatus !== null && params.approvalStatus !== "") {
    newParams.status = params.approvalStatus; // 审核状态 -> status
  }
  // 提交时间：ProTable 搜索项 prop 为 createdTime，值为 [start, end]
  const submissionRange =
    params.createdTime && Array.isArray(params.createdTime) && params.createdTime.length === 2
      ? params.createdTime
      : params.dateRange && Array.isArray(params.dateRange) && params.dateRange.length === 2
        ? params.dateRange
        : null;
  if (submissionRange) {
    newParams.startCreatedTime = submissionRange[0];
    newParams.endCreatedTime = submissionRange[1];
  }

  // 使用新的搜索接口
  return getStaffConfigList(newParams).catch((error: any) => {
    console.error("获取人员列表失败:", error);
    // 返回空数据，避免显示错误横幅
    return { code: 200, data: [], total: 0 };
  });
};

// 获取背景图片/视频列表
const getBackgroundImageList = (backgroundUrl: string | null | undefined): string[] => {
  if (!backgroundUrl) return [];
  if (typeof backgroundUrl === "string") {
    return backgroundUrl.split(",").filter((url: string) => url.trim());
  }
  return Array.isArray(backgroundUrl) ? backgroundUrl : [];
};

/** 判断背景 URL 是否为视频（用于详情展示与预览） */
const isVideoBackgroundUrl = (url: string) => /\.(mp4|webm|ogg|mov)(\?|$)/i.test(url);

// 预览背景图片/视频（图片用查看器，视频用放大弹窗）
const previewBackgroundImage = (url: string) => {
  if (isVideoBackgroundUrl(url)) {
    previewVideoUrl.value = url;
    previewVideoVisible.value = true;
    return;
  }
  previewImageUrl.value = url;
  previewImageVisible.value = true;
};

// 编辑/新增表单内点击视频「查看」时，复用同一套视频放大弹窗
const handleVideoPreviewInForm = (url: string) => {
  previewVideoUrl.value = url;
  previewVideoVisible.value = true;
};

// 弹窗标题
const dialogTitle = computed(() => (editId.value !== null ? "编辑" : "新建"));

/**
 * 头像上传：兼容 UploadImg（Img.vue）里 `const { data } = await api(formData)` 的解构写法
 */
const personnelOssUploadAvatar = async (formData: FormData): Promise<{ data: { fileUrl: string } }> => {
  const raw = formData.get("file");
  const file = raw instanceof File ? raw : null;
  if (!file) {
    throw new Error("请选择文件");
  }
  const url = await uploadFileToOss(file, "image");
  return { data: { fileUrl: url } };
};

/**
 * 背景图/视频：OSS 直传，返回格式兼容 UploadImgs（读取 response.fileUrl）
 */
const handleCustomUpload = async (formData: FormData): Promise<any> => {
  const raw = formData.get("file");
  const file = raw instanceof File ? raw : null;
  if (!file) {
    throw new Error("请选择文件");
  }
  const isVideo = typeof file.type === "string" && file.type.startsWith("video/");
  const urls = await uploadFilesToOss(file, isVideo ? "video" : "image");
  const fileUrl = urls[0];
  if (!fileUrl) {
    throw new Error("上传失败，未返回地址");
  }
  return {
    fileUrl,
    data: [fileUrl],
    code: 200,
    success: true,
    msg: "操作成功"
  };
};

// 表单数据
const formData = reactive({
  name: "",
  position: "",
  avatar: "",
  backgroundImages: [] as UploadUserFile[],
  specialty: "",
  tags: [""] as string[],
  description: ""
});

// 同步组件内部文件列表到 formData（避免上传中因过滤 blob 导致列表被清空或重复）
const syncFileListFromComponent = async () => {
  if (!backgroundImagesUploadRef.value || !dialogVisible.value) return;

  try {
    const componentInstance = backgroundImagesUploadRef.value;
    if (componentInstance && componentInstance._fileList) {
      const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
      if (Array.isArray(internalFileList)) {
        // 若组件内仍有 blob URL，说明还有文件在上传中，不覆盖 formData，避免清空或重复
        const hasUploading = internalFileList.some((file: UploadUserFile) => file?.url && String(file.url).startsWith("blob:"));
        if (hasUploading) return;

        // 同步内部文件列表到 formData（排除 blob URL，只保留服务器 URL）
        const validFiles = internalFileList
          .filter((file: UploadUserFile) => {
            const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
            const isBlobUrl = hasUrl && (file.url as string).startsWith("blob:");
            return hasUrl && !isBlobUrl;
          })
          .map((file: UploadUserFile) => ({
            ...file,
            url: file.url!.trim(),
            name: file.name || file.url!.split("/").pop() || "image",
            uid: file.uid ?? `file-${Date.now()}-${Math.random()}`
          }));

        // 按 URL 去重，避免同一张图出现多次
        const seenUrls = new Set<string>();
        const uniqueFiles = validFiles.filter((f: { url?: string }) => {
          const u = f.url?.trim();
          if (!u || seenUrls.has(u)) return false;
          seenUrls.add(u);
          return true;
        });

        const currentUrls = formData.backgroundImages
          .filter((f: UploadUserFile) => f && f.url && !(f.url as string).startsWith("blob:"))
          .map((f: UploadUserFile) => f.url!.trim())
          .sort();
        const newUrls = uniqueFiles.map((f: { url?: string }) => (f.url || "").trim()).sort();

        if (formData.backgroundImages.length === 0 && uniqueFiles.length > 0) return;

        if (JSON.stringify(currentUrls) !== JSON.stringify(newUrls)) {
          formData.backgroundImages = [...uniqueFiles] as UploadUserFile[];
          await nextTick();
          if (formRef.value) {
            formRef.value.validateField("backgroundImages");
          }
        }
      }
    }
  } catch (error) {
    console.warn("同步文件列表失败:", error);
  }
};

// 背景图片上传成功回调：用接口返回的服务器 URL 直接修正 formData（把 blob 替换为服务器地址），再触发校验
const handleBackgroundImageSuccess = async (serverUrl: string) => {
  if (!serverUrl || typeof serverUrl !== "string") return;
  const url = serverUrl.trim();
  const list = formData.backgroundImages;
  let replaceIndex = -1;
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (!item) continue;
    const u = item.url && typeof item.url === "string" ? item.url.trim() : "";
    if (!u || u.startsWith("blob:")) {
      replaceIndex = i;
      break;
    }
  }
  if (replaceIndex >= 0) {
    formData.backgroundImages = list.map((item, i) =>
      i === replaceIndex ? { ...item, url, status: "success" as const } : item
    ) as UploadUserFile[];
  } else {
    const hasUrl = list.some((f: UploadUserFile) => f?.url && String(f.url).trim() === url);
    if (!hasUrl) {
      formData.backgroundImages = [
        ...list,
        {
          uid: `bg-${Date.now()}-${Math.random()}`,
          name: url.split("/").pop() || "image",
          url,
          status: "success" as const
        } as unknown as UploadUserFile
      ];
    }
  }
  await nextTick();
  if (formRef.value) {
    formRef.value.validateField("backgroundImages");
  }
};

// 监听背景图片列表变化，确保文件列表正确更新
watch(
  () => formData.backgroundImages,
  async (newList, oldList) => {
    // 延迟执行，避免与组件内部更新冲突
    await nextTick();

    // 如果列表发生变化，尝试从组件同步（确保删除和上传后能同步）
    if (backgroundImagesUploadRef.value && dialogVisible.value) {
      await syncFileListFromComponent();
    }

    // 确保文件列表中的每个文件都有有效的 URL
    if (Array.isArray(newList) && newList.length > 0) {
      const validFiles = newList.filter((file: UploadUserFile) => {
        return file && file.url && typeof file.url === "string" && file.url.trim() !== "";
      });
      // 如果有效文件数量与列表长度不一致，更新列表
      if (validFiles.length !== newList.length && validFiles.length > 0) {
        formData.backgroundImages = validFiles;
      }
      // 触发验证
      nextTick(() => {
        if (formRef.value) {
          formRef.value.validateField("backgroundImages");
        }
      });
    }
  },
  { deep: true, immediate: false }
);

// 监听组件内部文件列表变化（通过定时检查，确保删除和上传后能同步）
let fileListSyncTimer: ReturnType<typeof setInterval> | null = null;
let lastFileListUrls: string[] = [];
let lastFileListLength = 0;

// 启动文件列表同步检查（仅在对话框打开时）
watch(
  () => dialogVisible.value,
  isVisible => {
    if (isVisible) {
      // 对话框打开时，启动定时检查（用于捕获删除和上传后的变化）
      fileListSyncTimer = setInterval(async () => {
        if (backgroundImagesUploadRef.value && dialogVisible.value) {
          try {
            const componentInstance = backgroundImagesUploadRef.value;
            if (componentInstance && componentInstance._fileList) {
              const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
              if (Array.isArray(internalFileList)) {
                const validFiles = internalFileList.filter((file: UploadUserFile) => file && file.url);
                const currentUrls = validFiles.map((file: UploadUserFile) => file.url!.trim()).sort();
                const currentLength = validFiles.length;

                // 如果文件列表发生变化（URL 或数量），立即同步
                const urlsChanged = JSON.stringify(currentUrls) !== JSON.stringify(lastFileListUrls);
                const lengthChanged = currentLength !== lastFileListLength;

                // 未传背景时不以组件内残留数据覆盖：表单为空且组件有项时不同步
                if (formData.backgroundImages.length === 0 && currentLength > 0) return;

                if (urlsChanged || lengthChanged) {
                  lastFileListUrls = currentUrls;
                  lastFileListLength = currentLength;

                  // 按 URL 去重后更新 formData，避免同一张图出现多次
                  const seen = new Set<string>();
                  const mappedFiles = validFiles
                    .map((file: UploadUserFile) => ({ ...file, url: (file.url || "").trim() }))
                    .filter((f: UploadUserFile) => {
                      const u = f?.url;
                      if (!u || seen.has(u)) return false;
                      seen.add(u);
                      return true;
                    });
                  formData.backgroundImages = [...mappedFiles] as UploadUserFile[];

                  // 触发验证
                  await nextTick();
                  if (formRef.value) {
                    formRef.value.validateField("backgroundImages");
                  }
                }
              }
            }
          } catch (error) {
            // 静默处理
          }
        }
      }, 150); // 每150ms检查一次，确保及时同步（缩短间隔以提高响应速度）
    } else {
      // 对话框关闭时，清除定时器
      if (fileListSyncTimer) {
        clearInterval(fileListSyncTimer);
        fileListSyncTimer = null;
      }
      lastFileListUrls = [];
      lastFileListLength = 0;
    }
  },
  { immediate: true }
);

// 表单校验规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入姓名/昵称", trigger: "blur" }],
  position: [{ required: true, message: "请输入人员职位", trigger: "blur" }],
  avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
  backgroundImages: [
    {
      required: true,
      validator: (rule: any, value: UploadUserFile[], callback: any) => {
        // 检查文件列表是否存在
        if (!value || !Array.isArray(value)) {
          callback(new Error("请上传背景图片"));
          return;
        }
        // 检查是否有至少一张已上传成功的图片（有url的图片，且不是blob URL）
        const validImages = value.filter((file: UploadUserFile) => {
          // 检查文件是否有有效的URL，且不是blob URL
          const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
          const isBlobUrl = hasUrl && file.url.startsWith("blob:");
          return hasUrl && !isBlobUrl;
        });
        if (validImages.length === 0) {
          callback(new Error("请上传背景图片"));
        } else {
          callback();
        }
      },
      trigger: ["change", "blur"]
    }
  ]
});

// 检查是否存在标题
const checkTitleExists = async (): Promise<boolean> => {
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId || localGet("createdId");

    if (!storeId) {
      console.warn("未找到店铺ID，跳过标题检查");
      return false; // 如果没有店铺ID，显示创建标题按钮
    }

    // 通过 storeId 查询标题详情
    const res: any = await getTitleDetail({
      storeId: Number(storeId)
    });

    // 如果接口返回成功且有数据
    if (res && (res.code === 200 || res.code === "200")) {
      // 检查返回数据中的 id 字段是否有值
      if (res.data !== null && res.data !== undefined) {
        const titleIdValue = res.data.id || res.data.titleId;

        // 如果 id 有值，说明当前门店有标题，隐藏创建标题按钮
        if (titleIdValue !== null && titleIdValue !== undefined && titleIdValue !== "") {
          // 保存标题ID，用于编辑和删除
          titleId.value = titleIdValue;
          return true; // 标题存在，不显示创建标题按钮
        }
      }
    }
    // 如果 id 没有值，显示创建标题按钮
    titleId.value = null;
    return false;
  } catch (error: any) {
    // 静默处理错误，不显示错误横幅
    console.warn("检查标题失败，默认需要创建标题:", error);
    // 默认返回 false，要求创建标题
    titleId.value = null;
    return false;
  }
};

// 处理标题下拉菜单命令
const handleTitleCommand = (command: string) => {
  if (command === "edit") {
    handleEditTitle();
  } else if (command === "delete") {
    handleDeleteTitle();
  }
};

// 打开创建标题弹窗
const handleCreateTitle = () => {
  titleEditId.value = null;
  resetTitleForm();
  titleDialogVisible.value = true;
};

// 编辑标题
const handleEditTitle = async () => {
  if (!titleId.value) {
    ElMessage.warning("标题ID不存在");
    return;
  }

  try {
    // 获取标题详情
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId || localGet("createdId");

    if (!storeId) {
      ElMessage.error("未找到店铺ID");
      return;
    }

    const res: any = await getTitleDetail({
      storeId: Number(storeId)
    });

    if (res && (res.code === 200 || res.code === "200") && res.data) {
      titleEditId.value = res.data.id || res.data.titleId || titleId.value;
      titleFormData.name = res.data.titleName || res.data.name || "";
      titleDialogVisible.value = true;
    } else {
      ElMessage.error(res?.msg || "获取标题详情失败");
    }
  } catch (error: any) {
    console.error("获取标题详情失败:", error);
    ElMessage.error(error?.msg || "获取标题详情失败，请重试");
  }
};

// 删除标题
const handleDeleteTitle = async () => {
  if (!titleId.value) {
    ElMessage.warning("标题ID不存在");
    return;
  }

  try {
    // 先检查是否有人员关联
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId || localGet("createdId");

    if (!storeId) {
      ElMessage.error("未找到店铺ID");
      return;
    }

    // 获取人员列表，检查是否有人员关联
    const personnelRes: any = await getStaffConfigList({
      storeId: Number(storeId),
      pageNum: 1,
      pageSize: 1
    });

    let hasPersonnel = false;
    if (personnelRes && (personnelRes.code === 200 || personnelRes.code === "200")) {
      let personnelList: any[] = [];
      let total = 0;

      // 处理不同的数据格式
      if (Array.isArray(personnelRes.data)) {
        personnelList = personnelRes.data;
        total = personnelRes.data.length;
      } else if (personnelRes.data?.data) {
        if (Array.isArray(personnelRes.data.data)) {
          personnelList = personnelRes.data.data;
          total = personnelRes.data.data.length;
        } else if (personnelRes.data.data?.records) {
          personnelList = personnelRes.data.data.records || [];
          total = personnelRes.data.data.total || 0;
        }
      } else if (personnelRes.data?.list && Array.isArray(personnelRes.data.list)) {
        personnelList = personnelRes.data.list;
        total = personnelRes.data.total || personnelRes.data.list.length;
      } else if (personnelRes.data?.records && Array.isArray(personnelRes.data.records)) {
        personnelList = personnelRes.data.records;
        total = personnelRes.data.total || 0;
      }

      // 检查是否有人员（通过列表长度或总数判断）
      hasPersonnel = personnelList.length > 0 || total > 0;
    }

    // 如果有人员关联，不允许删除
    if (hasPersonnel) {
      ElMessage.warning("当前门店标题有人员关联，不能删除标题");
      return;
    }

    // 确认删除
    await ElMessageBox.confirm("确认删除该标题吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 调用删除接口
    const res: any = await deleteTitle({ id: titleId.value });
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("删除成功");
      // 更新标题状态
      hasTitle.value = false;
      titleId.value = null;
      // 重新加载表格数据
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除标题失败:", error);
      ElMessage.error(error?.msg || "删除失败，请重试");
    }
  }
};

// 重置标题表单
const resetTitleForm = () => {
  titleFormData.name = "";
  titleEditId.value = null;
  titleFormRef.value?.clearValidate();
};

// 提交标题表单
const handleTitleSubmit = async () => {
  if (!titleFormRef.value) return;

  try {
    await titleFormRef.value.validate();
  } catch (error) {
    ElMessage.warning("请完善必填项");
    return;
  }

  // 检查名称是否为空
  if (!titleFormData.name || titleFormData.name.trim() === "") {
    ElMessage.warning("请输入名称");
    return;
  }

  titleSubmitLoading.value = true;
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      ElMessage.error("未找到店铺ID");
      titleSubmitLoading.value = false;
      return;
    }

    // 构建请求参数
    const params: any = {
      storeId: Number(storeId),
      titleName: titleFormData.name.trim()
    };

    let res: any;
    // 根据是否有编辑ID，调用不同的接口
    if (titleEditId.value) {
      // 修改标题
      params.id = titleEditId.value;
      res = await updateTitle(params);
    } else {
      // 创建标题
      res = await createTitle(params);
    }

    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success(titleEditId.value ? "修改成功" : "创建成功");
      titleDialogVisible.value = false;
      resetTitleForm();
      // 更新标题存在状态和ID
      hasTitle.value = true;
      // 如果是创建，保存标题ID
      if (!titleEditId.value && res.data) {
        titleId.value = res.data.id || res.data.titleId || null;
      }
      // 重新加载表格数据
      proTable.value?.getTableList();
      // 重新检查标题状态（获取最新的标题ID）
      await checkTitleExists();
    } else {
      ElMessage.error(res?.msg || (titleEditId.value ? "修改失败" : "创建失败"));
    }
  } catch (error: any) {
    console.error("操作失败:", error);
    ElMessage.error(error?.msg || "操作失败，请重试");
  } finally {
    titleSubmitLoading.value = false;
  }
};

// 上线
// 上线 - onlineStatus 设置为 0
const handleOnline = async (row: Personnel) => {
  if (!row.id) {
    ElMessage.warning("人员ID不存在");
    return;
  }
  try {
    const res: any = await setOnlineStatus({
      id: row.id,
      onlineStatus: 0
    });
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("上线成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "上线失败");
    }
  } catch (error: any) {
    console.error("上线失败:", error);
    ElMessage.error(error?.msg || "上线失败，请重试");
  }
};

// 下线 - onlineStatus 设置为 1
const handleOffline = async (row: Personnel) => {
  if (!row.id) {
    ElMessage.warning("人员ID不存在");
    return;
  }
  try {
    const res: any = await setOnlineStatus({
      id: row.id,
      onlineStatus: 1
    });
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("下线成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "下线失败");
    }
  } catch (error: any) {
    console.error("下线失败:", error);
    ElMessage.error(error?.msg || "下线失败，请重试");
  }
};

// 置顶
const handlePin = async (row: Personnel) => {
  if (!row.id) {
    ElMessage.warning("人员ID不存在");
    return;
  }

  try {
    const res: any = await setTopStatus({
      id: row.id,
      topStatus: 1
    });

    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("置顶成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "置顶失败");
    }
  } catch (error: any) {
    console.error("置顶失败:", error);
    ElMessage.error(error?.msg || "置顶失败，请重试");
  }
};

// 取消置顶
const handleUnpin = async (row: Personnel) => {
  if (!row.id) {
    ElMessage.warning("人员ID不存在");
    return;
  }

  try {
    const res: any = await setTopStatus({
      id: row.id,
      topStatus: 0
    });

    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("取消置顶成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "取消置顶失败");
    }
  } catch (error: any) {
    console.error("取消置顶失败:", error);
    ElMessage.error(error?.msg || "取消置顶失败，请重试");
  }
};

// 查看详情
const handleViewDetail = async (row: Personnel) => {
  if (!row.id) {
    ElMessage.warning("人员ID不存在");
    return;
  }

  detailLoading.value = true;
  detailDialogVisible.value = true;
  personnelDetail.value = null;

  try {
    const res: any = await getStaffConfigDetail({ id: row.id });
    if (res && (res.code === 200 || res.code === "200")) {
      personnelDetail.value = res.data || res;
    } else {
      ElMessage.error(res?.msg || "获取人员详情失败");
      detailDialogVisible.value = false;
    }
  } catch (error: any) {
    console.error("获取人员详情失败:", error);
    ElMessage.error(error?.msg || "获取人员详情失败，请重试");
    detailDialogVisible.value = false;
  } finally {
    detailLoading.value = false;
  }
};

// 打开新建弹窗
const openCreateDialog = async () => {
  try {
    // 先检查是否存在标题
    const hasTitle = await checkTitleExists();

    if (!hasTitle) {
      ElMessageBox.alert("请先创建标题，再添加新人员", "提示", {
        confirmButtonText: "确定",
        type: "warning"
      }).then(() => {
        // 用户确认后，自动打开创建标题的弹窗
        handleCreateTitle();
      });
      return;
    }

    editId.value = null;
    resetForm();
    uploadComponentKey.value += 1;
    dialogVisible.value = true;
  } catch (error: any) {
    // 如果检查标题时出错，记录错误但允许继续创建人员（避免阻塞用户）
    console.error("检查标题时出错:", error);
    // 如果错误是资源不存在，提示用户先创建标题
    if (error?.response?.status === 404 || error?.message?.includes("不存在")) {
      ElMessageBox.alert("请先创建标题，再添加新人员", "提示", {
        confirmButtonText: "确定",
        type: "warning"
      }).then(() => {
        handleCreateTitle();
      });
      return;
    }
    // 其他错误，允许继续创建（避免因接口问题阻塞用户）
    editId.value = null;
    resetForm();
    uploadComponentKey.value += 1;
    dialogVisible.value = true;
  }
};

// 编辑人员
const editPersonnel = async (person: Personnel, index: number) => {
  if (!person.id) {
    ElMessage.warning("人员ID不存在");
    return;
  }

  try {
    // 调用获取人员详情接口（使用和详情页面相同的接口，确保数据格式一致）
    const res: any = await getStaffConfigDetail({ id: person.id });
    if (res && (res.code === 200 || res.code === "200")) {
      const personDetail = res.data ?? res;
      console.log("编辑时获取的完整人员详情数据:", personDetail);

      editId.value = personDetail.id;
      formData.name = personDetail.staffName || personDetail.name || "";
      formData.position = personDetail.staffPosition || "";
      formData.avatar = personDetail.staffImage || "";

      // 处理背景图片：接口返回 backgroundUrl 逗号分隔，转为 UploadUserFile[]（兼容 background_url 等字段名）
      const backgroundUrlValue =
        personDetail.backgroundUrl ?? personDetail.background_url ?? personDetail.backgroundImages ?? personDetail.background;

      let imageFiles: UploadUserFile[] = [];

      if (backgroundUrlValue) {
        const backgroundImageUrls =
          typeof backgroundUrlValue === "string"
            ? backgroundUrlValue.split(",").filter((url: string) => url.trim())
            : Array.isArray(backgroundUrlValue)
              ? backgroundUrlValue
              : [];

        // 为每个图片创建文件对象
        imageFiles = backgroundImageUrls
          .map((url: string, index: number) => {
            const trimmedUrl = url.trim();
            if (!trimmedUrl) return null;

            const urlParts = trimmedUrl.split("/");
            const fileName = urlParts[urlParts.length - 1] || `background-${index + 1}.jpg`;

            return {
              uid: "bg-" + Date.now() + index,
              name: fileName,
              url: trimmedUrl,
              status: "success",
              response: { fileUrl: trimmedUrl }
            } as unknown as UploadUserFile;
          })
          .filter((file): file is UploadUserFile => file !== null);
      }

      formData.specialty = personDetail.proficientProjects || "";
      formData.tags = personDetail.tag ? personDetail.tag.split(",").map((tag: string) => tag.trim()) : [""];
      formData.description = personDetail.personalIntroduction || "";
      formData.backgroundImages = imageFiles;

      // 强制背景上传组件重新挂载，避免沿用上次的 _fileList 导致数量显示错误
      uploadComponentKey.value += 1;
      // 打开对话框
      dialogVisible.value = true;
    } else {
      ElMessage.error(res?.msg || "获取人员详情失败");
    }
  } catch (error: any) {
    console.error("获取人员详情失败:", error);
    ElMessage.error(error?.msg || "获取人员详情失败，请重试");
  }
};

// 删除人员
const deletePersonnelHandler = async (id: string | number, index: number) => {
  try {
    await ElMessageBox.confirm("确认删除该人员吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 不需要查找人员，直接删除

    const res: any = await deletePersonnel({ id });
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("删除成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除人员失败:", error);
      ElMessage.error(error?.msg || "删除失败，请重试");
    }
  }
};

// 添加标签
const addTag = () => {
  if (formData.tags.length < 5) {
    formData.tags.push("");
  }
};

// 删除标签
const removeTag = () => {
  if (formData.tags.length > 1) {
    formData.tags.pop();
  }
};

// 对话框打开后的回调
// 重置表单
const resetForm = () => {
  formData.name = "";
  formData.position = "";
  formData.avatar = "";
  formData.backgroundImages = [];
  formData.specialty = "";
  formData.tags = [""];
  formData.description = "";
  editId.value = null;
  formRef.value?.clearValidate();
  // 重置上传组件 key，确保下次打开时组件能正确初始化
  uploadComponentKey.value += 1;
};

// 从 DOM 中提取已上传的图片 URL（备用方案）
const extractImagesFromDOM = (): UploadUserFile[] => {
  const images: UploadUserFile[] = [];
  try {
    // 查找上传组件容器
    const uploadContainer = document.querySelector(".el-upload-list--picture-card");
    if (uploadContainer) {
      const imageElements = uploadContainer.querySelectorAll("img.upload-image");
      imageElements.forEach((img: Element, index: number) => {
        const imgElement = img as HTMLImageElement;
        if (imgElement.src && !imgElement.src.includes("data:image")) {
          images.push({
            uid: Date.now() + index,
            name: `image-${index + 1}`,
            url: imgElement.src,
            status: "success"
          } as UploadUserFile);
        }
      });
    }
  } catch (error) {
    console.warn("从 DOM 提取图片失败:", error);
  }
  return images;
};

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

  // 在提交前，强制同步组件内部的文件列表，确保获取最新的图片
  console.log("=== 提交前同步文件列表 ===");
  console.log("同步前 formData.backgroundImages:", formData.backgroundImages);

  await syncFileListFromComponent();
  await nextTick();
  await syncFileListFromComponent(); // 再次同步，确保数据最新
  await nextTick();

  // 强制从组件实例获取最新文件列表（确保获取到删除和上传后的最新状态）
  let latestFileList = formData.backgroundImages;
  if (backgroundImagesUploadRef.value) {
    try {
      const componentInstance = backgroundImagesUploadRef.value;
      if (componentInstance && componentInstance._fileList) {
        const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
        console.log("组件内部文件列表:", internalFileList);

        if (Array.isArray(internalFileList) && internalFileList.length > 0) {
          const validFiles = internalFileList
            .filter((file: UploadUserFile) => {
              const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
              // 排除 blob URL，只保留服务器 URL
              const isBlobUrl = hasUrl && file.url.startsWith("blob:");
              if (!hasUrl) {
                console.warn("过滤掉无效文件:", file);
              } else if (isBlobUrl) {
                console.warn("过滤掉 blob URL 文件:", file.url);
              }
              return hasUrl && !isBlobUrl;
            })
            .map((file: UploadUserFile) => ({
              ...file,
              url: file.url!.trim()
            }));

          console.log("过滤后的有效文件列表（排除 blob）:", validFiles);
          console.log("有效文件数量:", validFiles.length);

          if (validFiles.length > 0) {
            latestFileList = validFiles;
            // 直接更新 formData，确保数据一致
            formData.backgroundImages = [...validFiles];
            console.log("提交前从组件同步的文件列表，数量:", validFiles.length);
            console.log(
              "提交前从组件同步的文件列表，URLs:",
              validFiles.map(f => f.url)
            );
          } else {
            console.warn("组件内部没有有效文件！");
          }
        } else {
          console.warn("组件内部文件列表为空或不是数组");
        }
      } else {
        console.warn("无法访问组件实例或 _fileList");
      }
    } catch (error) {
      console.error("提交前同步文件列表失败:", error);
    }
  } else {
    console.warn("backgroundImagesUploadRef.value 为空");
  }

  console.log("同步后 formData.backgroundImages:", formData.backgroundImages);
  console.log("同步后 latestFileList:", latestFileList);

  // 如果仍然为空，尝试从 DOM 中提取（最后的手段）
  if (latestFileList.length === 0) {
    console.warn("文件列表为空，尝试从 DOM 提取");
    const domImages = extractImagesFromDOM();
    if (domImages.length > 0) {
      latestFileList = domImages;
      formData.backgroundImages = [...domImages];
      console.log("提交前从 DOM 提取的文件列表:", domImages);
    }
  }

  console.log("最终使用的文件列表:", latestFileList);
  console.log("========================");

  // 在验证前，确保 formData.backgroundImages 包含所有有效图片（排除 blob URL）
  if (backgroundImagesUploadRef.value) {
    try {
      const componentInstance = backgroundImagesUploadRef.value;
      if (componentInstance && componentInstance._fileList) {
        const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
        if (Array.isArray(internalFileList) && internalFileList.length > 0) {
          const validFiles = internalFileList
            .filter((file: UploadUserFile) => {
              const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
              const isBlobUrl = hasUrl && file.url.startsWith("blob:");
              return hasUrl && !isBlobUrl;
            })
            .map((file: UploadUserFile) => ({
              ...file,
              url: file.url!.trim()
            }));

          // 更新 formData，确保验证时使用的是有效文件
          if (validFiles.length > 0) {
            formData.backgroundImages = [...validFiles];
            console.log("验证前同步的文件列表，数量:", validFiles.length);
            console.log(
              "验证前同步的文件列表 URLs:",
              validFiles.map(f => f.url)
            );
          } else {
            console.warn("验证前：组件内部没有有效文件（可能都是 blob URL）");
          }
        }
      }
    } catch (error) {
      console.error("验证前同步文件列表失败:", error);
    }
  }

  // 手动验证背景图片字段
  try {
    await formRef.value.validateField("backgroundImages");
  } catch (error) {
    // 如果验证失败，继续执行整体验证以显示所有错误
  }

  try {
    await formRef.value.validate();
  } catch (error) {
    ElMessage.warning("请完善必填项");
    return;
  }

  // 提交前最后一次同步组件内部的文件列表，确保获取最新的图片
  console.log("=== 提交前同步文件列表 ===");
  console.log("同步前 formData.backgroundImages 数量:", formData.backgroundImages.length);
  console.log(
    "同步前 formData.backgroundImages URLs:",
    formData.backgroundImages.map(f => f.url)
  );

  await syncFileListFromComponent();
  await nextTick();
  await syncFileListFromComponent(); // 再次同步，确保数据最新
  await nextTick();

  // 最终检查：确保背景图片有有效的URL
  // 再次从组件实例获取最新文件列表（确保获取到删除和上传后的最新状态）
  let finalFileList = formData.backgroundImages;
  if (backgroundImagesUploadRef.value) {
    try {
      const componentInstance = backgroundImagesUploadRef.value;
      if (componentInstance && componentInstance._fileList) {
        const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
        console.log("提交前组件内部文件列表，数量:", Array.isArray(internalFileList) ? internalFileList.length : 0);
        console.log("提交前组件内部文件列表:", internalFileList);

        if (Array.isArray(internalFileList) && internalFileList.length > 0) {
          // 获取所有有效文件（包括所有有URL的文件，不管状态）
          const validFiles = internalFileList
            .filter((file: UploadUserFile) => {
              const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
              // 排除 blob URL，只保留服务器 URL
              const isBlobUrl = hasUrl && file.url.startsWith("blob:");
              if (!hasUrl) {
                console.warn("提交前过滤掉无效文件:", file);
              } else if (isBlobUrl) {
                console.warn("提交前过滤掉 blob URL 文件:", file.url);
              }
              return hasUrl && !isBlobUrl;
            })
            .map((file: UploadUserFile) => ({
              ...file,
              url: file.url!.trim()
            }));

          console.log("提交前组件内部有效文件，数量:", validFiles.length);
          console.log(
            "提交前组件内部有效文件 URLs:",
            validFiles.map(f => f.url)
          );

          // 获取当前 formData 中的 URLs（排除 blob URL）
          const currentUrls = formData.backgroundImages
            .filter((f: UploadUserFile) => f && f.url && !f.url.startsWith("blob:"))
            .map((f: UploadUserFile) => f.url!.trim());

          console.log("提交前 formData 中的 URLs:", currentUrls);

          // 检查组件内部是否有 formData 中没有的 URL（可能是新上传的）
          const missingUrls = validFiles.map(f => f.url).filter(url => !currentUrls.includes(url));

          if (missingUrls.length > 0) {
            console.warn("⚠️ 发现遗漏的 URL，添加到文件列表:", missingUrls);
            // 将遗漏的文件添加到 formData
            const missingFiles = validFiles.filter(f => missingUrls.includes(f.url));
            formData.backgroundImages = [...formData.backgroundImages, ...missingFiles];
            console.log("添加遗漏文件后的 formData.backgroundImages，数量:", formData.backgroundImages.length);
            console.log(
              "添加遗漏文件后的 formData.backgroundImages URLs:",
              formData.backgroundImages.map(f => f.url)
            );
          } else {
            console.log("✓ 没有发现遗漏的 URL");
          }

          // 强制使用组件内部的文件列表（确保包含所有文件，包括新上传的）
          if (validFiles.length > 0) {
            // 合并 formData 和组件内部的文件，去重
            const allUrls = new Set<string>();
            const mergedFiles: UploadUserFile[] = [];

            // 先添加 formData 中的文件
            // 先添加 formData 中的文件（排除 blob URL）
            formData.backgroundImages.forEach((file: UploadUserFile) => {
              if (file && file.url) {
                const url = file.url.trim();
                // 排除 blob URL，只保留服务器 URL
                if (!url.startsWith("blob:") && !allUrls.has(url)) {
                  allUrls.add(url);
                  mergedFiles.push({
                    ...file,
                    url: url
                  });
                  console.log("从 formData 添加文件（旧图片）:", url);
                } else if (url.startsWith("blob:")) {
                  console.warn("跳过 formData 中的 blob URL:", url);
                }
              }
            });

            // 再添加组件内部的文件（确保新上传的文件被包含，排除 blob URL）
            validFiles.forEach((file: UploadUserFile) => {
              const url = file.url;
              // 排除 blob URL，只保留服务器 URL
              if (url && !url.startsWith("blob:") && !allUrls.has(url)) {
                allUrls.add(url);
                mergedFiles.push(file);
                console.log("从组件内部添加文件（新图片）:", url);
              } else if (url && url.startsWith("blob:")) {
                console.warn("跳过组件内部的 blob URL:", url);
              }
            });

            finalFileList = mergedFiles;
            // 更新 formData，确保数据一致
            formData.backgroundImages = [...mergedFiles];
            console.log("合并后的文件列表，数量:", mergedFiles.length);
            console.log(
              "合并后的文件列表 URLs:",
              mergedFiles.map(f => f.url)
            );
          }
        } else {
          console.warn("⚠️ 组件内部文件列表为空或不是数组");
        }
      } else {
        console.warn("⚠️ 无法访问组件实例或 _fileList");
      }
    } catch (error) {
      console.error("提交前同步文件列表失败:", error);
    }
  } else {
    console.warn("⚠️ backgroundImagesUploadRef.value 为空");
  }

  // 最后一次从组件获取最新文件列表，确保包含所有新上传的图片
  await nextTick();
  if (backgroundImagesUploadRef.value) {
    try {
      const componentInstance = backgroundImagesUploadRef.value;
      if (componentInstance && componentInstance._fileList) {
        const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
        if (Array.isArray(internalFileList) && internalFileList.length > 0) {
          const componentFiles = internalFileList
            .filter((file: UploadUserFile) => {
              const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
              const isBlobUrl = hasUrl && file.url.startsWith("blob:");
              return hasUrl && !isBlobUrl;
            })
            .map((file: UploadUserFile) => ({
              ...file,
              url: file.url!.trim()
            }));

          // 合并 finalFileList 和组件内部的文件，确保包含所有图片
          const allUrls = new Set<string>();
          const mergedFiles: UploadUserFile[] = [];

          // 先添加 finalFileList 中的文件
          finalFileList.forEach((file: UploadUserFile) => {
            if (file && file.url && !file.url.startsWith("blob:")) {
              const url = file.url.trim();
              if (!allUrls.has(url)) {
                allUrls.add(url);
                mergedFiles.push(file);
              }
            }
          });

          // 再添加组件内部的文件（确保新上传的文件被包含）
          componentFiles.forEach((file: UploadUserFile) => {
            const url = file.url;
            if (url && !url.startsWith("blob:") && !allUrls.has(url)) {
              allUrls.add(url);
              mergedFiles.push(file);
              console.log("最后补充添加的文件（新上传的）:", url);
            }
          });

          if (mergedFiles.length > finalFileList.length) {
            finalFileList = mergedFiles;
            formData.backgroundImages = [...mergedFiles];
            console.log("最后合并后的文件列表，数量:", mergedFiles.length);
            console.log(
              "最后合并后的文件列表 URLs:",
              mergedFiles.map(f => f.url)
            );
          }
        }
      }
    } catch (error) {
      console.error("最后同步文件列表失败:", error);
    }
  }

  // 过滤有效文件，排除 blob URL，只保留服务器 URL
  let finalValidFiles = finalFileList.filter((file: UploadUserFile) => {
    const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
    // 排除 blob URL，只保留服务器 URL
    const isBlobUrl = hasUrl && file.url.startsWith("blob:");
    if (isBlobUrl) {
      console.warn("过滤掉 blob URL 文件:", file.url);
    }
    return hasUrl && !isBlobUrl;
  });

  console.log("最终有效文件列表，数量:", finalValidFiles.length);
  console.log(
    "最终有效文件列表 URLs:",
    finalValidFiles.map(f => f.url)
  );
  console.log("========================");
  if (finalValidFiles.length === 0) {
    ElMessage.warning("请上传背景图片");
    formRef.value.validateField("backgroundImages");
    return;
  }

  submitLoading.value = true;
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      ElMessage.error("未找到店铺ID");
      submitLoading.value = false;
      return;
    }

    // 构建请求参数
    // 将背景图片数组转换为逗号分隔的URL字符串
    // 使用最终同步后的文件列表，确保只使用有效的文件 URL

    // 提交前最后一次强制同步，确保获取最新文件列表
    console.log("=== 提交前最后一次同步 ===");
    await syncFileListFromComponent();
    await nextTick();

    // 再次从组件获取最新文件列表
    if (backgroundImagesUploadRef.value) {
      try {
        const componentInstance = backgroundImagesUploadRef.value;
        if (componentInstance && componentInstance._fileList) {
          const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
          if (Array.isArray(internalFileList) && internalFileList.length > 0) {
            const componentFiles = internalFileList
              .filter((file: UploadUserFile) => {
                const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
                // 排除 blob URL，只保留服务器 URL
                const isBlobUrl = hasUrl && file.url.startsWith("blob:");
                return hasUrl && !isBlobUrl;
              })
              .map((file: UploadUserFile) => ({
                ...file,
                url: file.url!.trim()
              }));

            console.log("最后一次同步 - 组件内部文件（排除 blob），数量:", componentFiles.length);
            console.log(
              "最后一次同步 - 组件内部文件 URLs:",
              componentFiles.map(f => f.url)
            );

            // 合并到 finalValidFiles（排除 blob URL）
            const allUrls = new Set<string>();
            const allFiles: UploadUserFile[] = [];

            // 先添加 finalValidFiles 中的文件（排除 blob URL）
            finalValidFiles.forEach(file => {
              const url = file.url;
              if (url && !url.startsWith("blob:") && !allUrls.has(url)) {
                allUrls.add(url);
                allFiles.push(file);
              }
            });

            // 再添加组件内部的文件（确保新上传的文件被包含，排除 blob URL）
            componentFiles.forEach(file => {
              const url = file.url;
              if (url && !url.startsWith("blob:") && !allUrls.has(url)) {
                allUrls.add(url);
                allFiles.push(file);
                console.log("最后一次同步 - 补充添加文件:", url);
              }
            });

            if (allFiles.length > finalValidFiles.length) {
              console.log("最后一次同步 - 更新文件列表，数量:", allFiles.length);
              finalValidFiles = allFiles;
            }
          }
        }
      } catch (error) {
        console.error("最后一次同步失败:", error);
      }
    }

    // 构建 backgroundUrl 前，强制从组件获取最新文件列表，确保包含所有图片（包括新上传的）
    console.log("=== 构建 backgroundUrl 前的最终检查 ===");
    console.log("当前 finalValidFiles 数量:", finalValidFiles.length);
    console.log(
      "当前 finalValidFiles URLs:",
      finalValidFiles.map(f => f?.url)
    );
    console.log("当前 formData.backgroundImages 数量:", formData.backgroundImages.length);
    console.log(
      "当前 formData.backgroundImages URLs:",
      formData.backgroundImages.map(f => f?.url)
    );

    // 多次等待，确保组件内部已完全更新（新上传的图片可能还在更新中）
    await nextTick();
    await nextTick();
    await nextTick();

    // 强制同步一次，确保获取最新数据
    await syncFileListFromComponent();
    await nextTick();
    await syncFileListFromComponent(); // 再次同步
    await nextTick();

    // 强制从组件获取最新文件列表（这是最权威的数据源）
    let componentFiles: UploadUserFile[] = [];
    if (backgroundImagesUploadRef.value) {
      try {
        const componentInstance = backgroundImagesUploadRef.value;
        if (componentInstance && componentInstance._fileList) {
          const internalFileList = componentInstance._fileList.value || componentInstance._fileList;
          if (Array.isArray(internalFileList) && internalFileList.length > 0) {
            console.log("组件内部原始文件列表，数量:", internalFileList.length);
            console.log(
              "组件内部原始文件列表:",
              internalFileList.map(f => ({ url: f?.url, status: f?.status, name: f?.name }))
            );

            // 从组件获取所有有效文件（排除 blob URL）
            componentFiles = internalFileList
              .filter((file: UploadUserFile) => {
                const hasUrl = file && file.url && typeof file.url === "string" && file.url.trim() !== "";
                const isBlobUrl = hasUrl && file.url.startsWith("blob:");
                if (hasUrl && isBlobUrl) {
                  console.warn("组件内部发现 blob URL，已排除:", file.url);
                }
                return hasUrl && !isBlobUrl;
              })
              .map((file: UploadUserFile) => ({
                ...file,
                url: file.url!.trim()
              }));

            console.log("组件内部有效文件列表（排除 blob），数量:", componentFiles.length);
            console.log(
              "组件内部有效文件列表 URLs:",
              componentFiles.map(f => f.url)
            );
          } else {
            console.warn("⚠️ 组件内部文件列表为空或不是数组");
          }
        } else {
          console.warn("⚠️ 无法访问组件实例或 _fileList");
        }
      } catch (error) {
        console.error("构建 backgroundUrl 前获取文件列表失败:", error);
      }
    } else {
      console.warn("⚠️ backgroundImagesUploadRef.value 为空，无法获取最新文件列表");
    }

    // 合并 formData.backgroundImages 和组件内部的文件列表，确保包含所有图片
    const allUrls = new Set<string>();
    const mergedFiles: UploadUserFile[] = [];

    // 先添加 formData 中的文件（旧图片）
    formData.backgroundImages.forEach((file: UploadUserFile) => {
      if (file && file.url && !file.url.startsWith("blob:")) {
        const url = file.url.trim();
        if (!allUrls.has(url)) {
          allUrls.add(url);
          mergedFiles.push({
            ...file,
            url: url
          });
          console.log("从 formData 添加文件:", url);
        }
      }
    });

    // 再添加组件内部的文件（确保新上传的文件被包含）
    componentFiles.forEach((file: UploadUserFile) => {
      const url = file.url;
      if (url && !url.startsWith("blob:") && !allUrls.has(url)) {
        allUrls.add(url);
        mergedFiles.push(file);
        console.log("从组件内部添加文件（新上传的）:", url);
      }
    });

    // 使用合并后的列表作为最终数据源
    if (mergedFiles.length > 0) {
      finalValidFiles = mergedFiles;
      formData.backgroundImages = [...mergedFiles];
      console.log("✅ 合并后的最终文件列表，数量:", mergedFiles.length);
      console.log(
        "✅ 合并后的最终文件列表 URLs:",
        mergedFiles.map(f => f.url)
      );
    } else if (componentFiles.length > 0) {
      // 如果合并后为空，但组件内部有文件，使用组件内部的文件
      finalValidFiles = componentFiles;
      formData.backgroundImages = [...componentFiles];
      console.log("✅ 使用组件内部文件列表，数量:", componentFiles.length);
      console.log(
        "✅ 使用组件内部文件列表 URLs:",
        componentFiles.map(f => f.url)
      );
    } else {
      console.warn("⚠️ 没有找到有效文件");
    }

    // 构建 URL 字符串前，最后一次确保包含所有图片
    console.log("=== 构建 backgroundUrl ===");
    console.log("finalValidFiles 数量:", finalValidFiles.length);
    console.log(
      "finalValidFiles URLs:",
      finalValidFiles.map(f => f?.url)
    );
    console.log("formData.backgroundImages 数量:", formData.backgroundImages.length);
    console.log(
      "formData.backgroundImages URLs:",
      formData.backgroundImages.map(f => f?.url)
    );

    // 最后一次合并，确保包含所有图片（包括新上传的）
    const finalUrls = new Set<string>();
    const allValidFiles: UploadUserFile[] = [];

    // 先添加 finalValidFiles 中的文件
    finalValidFiles.forEach((file: UploadUserFile) => {
      if (file && file.url && !file.url.startsWith("blob:")) {
        const url = file.url.trim();
        if (!finalUrls.has(url)) {
          finalUrls.add(url);
          allValidFiles.push(file);
        }
      }
    });

    // 再添加 formData 中的文件（确保没有遗漏，特别是新上传的）
    formData.backgroundImages.forEach((file: UploadUserFile) => {
      if (file && file.url && !file.url.startsWith("blob:")) {
        const url = file.url.trim();
        if (!finalUrls.has(url)) {
          finalUrls.add(url);
          allValidFiles.push(file);
          console.log("从 formData 补充添加文件:", url);
        }
      }
    });

    console.log("最终合并后的文件列表，数量:", allValidFiles.length);
    console.log(
      "最终合并后的文件列表 URLs:",
      allValidFiles.map(f => f.url)
    );

    const backgroundImageUrls = allValidFiles
      .map((file: UploadUserFile, index: number) => {
        // 确保 URL 存在且有效
        const url = file?.url;
        if (url && typeof url === "string") {
          const trimmedUrl = url.trim();
          // 排除 blob URL，只保留服务器 URL
          if (trimmedUrl && !trimmedUrl.startsWith("blob:")) {
            console.log(`✓ 文件 ${index + 1} URL:`, trimmedUrl);
            return trimmedUrl;
          } else if (trimmedUrl.startsWith("blob:")) {
            console.warn(`✗ 文件 ${index + 1} 是 blob URL，已排除:`, trimmedUrl);
            return null;
          }
        }
        console.warn(`✗ 文件 ${index + 1} 无效:`, file);
        return null;
      })
      .filter((url: string | null): url is string => url !== null && url !== "") // 过滤空值
      .join(",");

    console.log("构建后的 backgroundImageUrls:", backgroundImageUrls);
    console.log("构建后的 backgroundImageUrls（分割后）:", backgroundImageUrls.split(","));
    console.log("========================");

    console.log("=== 提交表单时的数据 ===");
    console.log("提交时的文件数量:", finalValidFiles.length);
    console.log("提交时的文件列表:", finalValidFiles);
    console.log("提交时的背景图片URL列表:", backgroundImageUrls);
    console.log("提交时的背景图片URL列表（分割后）:", backgroundImageUrls.split(","));
    console.log("提交时的背景图片URL列表长度:", backgroundImageUrls.length);

    // 验证 backgroundImageUrls 是否为空
    if (!backgroundImageUrls || backgroundImageUrls.trim() === "") {
      console.error("❌ 错误：backgroundImageUrls 为空！");
      ElMessage.error("背景图片URL为空，请重新上传");
      submitLoading.value = false;
      return;
    }

    // 验证 URL 数量
    const urlCount = backgroundImageUrls.split(",").filter(url => url.trim()).length;
    console.log("backgroundUrl 中的 URL 数量:", urlCount);
    if (urlCount === 0) {
      console.error("❌ 错误：backgroundUrl 中没有有效的 URL！");
      ElMessage.error("背景图片URL无效，请重新上传");
      submitLoading.value = false;
      return;
    }

    const params: any = {
      storeId: Number(storeId),
      name: formData.name,
      staffPosition: formData.position,
      staffImage: formData.avatar,
      backgroundUrl: backgroundImageUrls, // 背景图片URL字符串，逗号分隔
      proficientProjects: formData.specialty || "",
      tag: formData.tags.filter(tag => tag.trim() !== "").join(","),
      personalIntroduction: formData.description || ""
    };

    // 如果是编辑，添加id
    if (editId.value) {
      params.id = editId.value;
    }

    // 最终验证参数
    console.log("=== 最终提交参数 ===");
    console.log("完整参数对象:", params);
    console.log("backgroundUrl 值:", params.backgroundUrl);
    console.log("backgroundUrl 类型:", typeof params.backgroundUrl);
    console.log("backgroundUrl 长度:", params.backgroundUrl?.length);
    console.log("backgroundUrl 分割后:", params.backgroundUrl?.split(","));
    console.log("========================");

    const res: any = await createOrUpdatePersonnel(params);
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success(editId.value ? "编辑成功" : "新建成功");
      dialogVisible.value = false;

      // 保存编辑的人员ID，用于刷新详情
      const editedPersonnelId = editId.value;

      resetForm();

      // 重新加载人员列表
      proTable.value?.getTableList();

      // 如果详情对话框是打开的，且是编辑操作，刷新详情数据
      if (detailDialogVisible.value && editedPersonnelId && personnelDetail.value?.id === editedPersonnelId) {
        try {
          const detailRes: any = await getStaffConfigDetail({ id: editedPersonnelId });
          if (detailRes && (detailRes.code === 200 || detailRes.code === "200")) {
            personnelDetail.value = detailRes.data || detailRes;
            console.log("编辑后刷新详情数据成功，背景图片:", personnelDetail.value.backgroundUrl);
          }
        } catch (error) {
          console.warn("刷新详情数据失败:", error);
        }
      }
    } else {
      ElMessage.error(res?.msg || (editId.value ? "编辑失败" : "新建失败"));
    }
  } catch (error: any) {
    console.error("操作失败:", error);
    ElMessage.error(error?.msg || "操作失败，请重试");
  } finally {
    submitLoading.value = false;
  }
};

// 页面初始化
onMounted(async () => {
  // ProTable 会自动加载数据
  // 检查标题是否存在
  hasTitle.value = await checkTitleExists();
});
</script>

<style scoped lang="scss">
.personnel-config-container {
  min-height: 100%;
  padding: 20px;
  background-color: white;
  .action-section {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  .table-box {
    .table-header-title {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      .table-title {
        margin-right: 8px;
      }
      .table-icon {
        font-size: 16px;
        color: var(--el-text-color-regular);
        cursor: pointer;
        transition: transform 0.3s;
        &:hover {
          color: var(--el-color-primary);
        }
      }
    }

    /* 列表为空时去掉空状态残留图形/背景，仅显示「暂无数据」文字 */
    :deep(.el-table__empty-block) {
      background: transparent !important;
      background-image: none !important;
      .table-empty {
        display: flex;
        flex-direction: column;
        gap: 8px;
        align-items: center;
        justify-content: center;
        padding: 24px 0;
        img {
          display: none !important;
        }
      }

      /* 隐藏可能存在的默认空状态插图（如 Element Plus 自带的 SVG） */
      svg {
        display: none !important;
      }
    }
    .personnel-config-empty {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
  .tags-container {
    width: 100%;
    .tag-input-wrapper {
      margin-bottom: 10px;
      &:last-of-type {
        margin-bottom: 0;
      }
    }
    .tag-actions {
      display: flex;
      gap: 10px;
      margin-top: 10px;
    }
  }
  .detail-content {
    min-height: 200px;
    .detail-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 20px;
      &:last-child {
        margin-bottom: 0;
      }
      .detail-label {
        flex-shrink: 0;
        width: 120px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
      .detail-value {
        flex: 1;
        color: var(--el-text-color-regular);
        word-break: break-word;
        .detail-avatar {
          width: 100px;
          height: 100px;
          object-fit: cover;
          border-radius: 8px;
        }
        .background-images {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 10px;
          margin-top: 8px;
          .background-image {
            width: 100%;
            max-width: 120px;
            height: 120px;
            cursor: pointer;
            object-fit: cover;
            border-radius: 8px;
            transition: transform 0.2s;
            &:hover {
              box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
              transform: scale(1.05);
            }
          }
          .background-media-item {
            position: relative;
            width: 100%;
            max-width: 120px;
            height: 120px;
            overflow: hidden;
            cursor: pointer;
            border-radius: 8px;
            transition: transform 0.2s;
            &:hover {
              box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
              transform: scale(1.05);
              .background-media-video-badge {
                opacity: 1;
              }
            }
            .background-image {
              width: 100%;
              height: 100%;
            }
            .background-media-video-badge {
              position: absolute;
              bottom: 6px;
              left: 6px;
              display: flex;
              align-items: center;
              justify-content: center;
              width: 28px;
              height: 28px;
              color: #ffffff;
              background: rgb(0 0 0 / 55%);
              border-radius: 6px;
              opacity: 0.9;
            }
          }
        }
      }
    }
  }
}

/* 编辑弹窗：背景图片/视频上传区域一行显示三个 */
.background-upload-three-col {
  :deep(.upload-box .upload) {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
  }
  :deep(.el-upload-list--picture-card) {
    display: contents;
  }
}
.video-preview-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  background: #000000;
  .video-preview-player {
    width: 100%;
    max-width: 100%;
    max-height: 75vh;
  }
}
</style>
