<template>
  <div class="upload-box" :class="{ 'hide-upload-trigger': shouldHideUploadTrigger }">
    <el-upload
      v-model:file-list="_fileList"
      action="#"
      list-type="picture-card"
      :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
      :multiple="true"
      :disabled="self_disabled"
      :limit="limit"
      :http-request="handleHttpUpload"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-success="showSuccessNotification ? uploadSuccess : undefined"
      :on-error="uploadError"
      :on-change="handleFileListChange"
      :drag="drag"
      :accept="fileType.join(',')"
    >
      <div class="upload-empty">
        <slot name="empty">
          <el-icon><Plus /></el-icon>
          <!-- <span>请上传图片</span> -->
        </slot>
      </div>
      <template #file="{ file }">
        <video
          v-if="isVideoFile(file) && file.url"
          :src="file.url"
          :poster="(file as any).coverUrl || undefined"
          class="upload-image"
          muted
          preload="metadata"
          playsinline
        />
        <img
          v-else-if="file.url && file.uid !== undefined && !imageLoadError.has(file.uid)"
          :src="file.url"
          class="upload-image"
          @error="handleImageError"
          @load="handleImageLoad"
        />
        <div v-else class="upload-image-placeholder">
          <el-icon><Picture /></el-icon>
          <span>{{ isVideoFile(file) ? "视频预览" : "图片预览" }}</span>
        </div>
        <div class="upload-handle" @click.stop>
          <div class="handle-icon" @click="handlePictureCardPreview(file)">
            <el-icon><ZoomIn /></el-icon>
            <span>查看</span>
          </div>
          <div v-if="!self_disabled" class="handle-icon" @click="handleRemove(file)">
            <el-icon><Delete /></el-icon>
            <span>删除</span>
          </div>
        </div>
      </template>
    </el-upload>
    <div class="el-upload__tip">
      <slot name="tip" />
    </div>
    <el-image-viewer v-if="imgViewVisible" :url-list="[viewImageUrl]" @close="imgViewVisible = false" />
  </div>
</template>

<script setup lang="ts" name="UploadImgs">
import { ref, computed, inject, watch, nextTick } from "vue";
import { Plus, Picture } from "@element-plus/icons-vue";
import { uploadImg } from "@/api/modules/upload";
import type { UploadProps, UploadFile, UploadUserFile, UploadRequestOptions } from "element-plus";
import { ElNotification, formContextKey, formItemContextKey } from "element-plus";

interface UploadFileProps {
  fileList: UploadUserFile[];
  api?: (params: any) => Promise<any>; // 上传图片的 api 方法，一般项目上传都是同一个 api 方法，在组件里直接引入即可 ==> 非必传
  drag?: boolean; // 是否支持拖拽上传 ==> 非必传（默认为 true）
  disabled?: boolean; // 是否禁用上传组件 ==> 非必传（默认为 false）
  limit?: number; // 最大图片上传数 ==> 非必传（默认为 5张）
  fileSize?: number; // 图片大小限制 ==> 非必传（默认为 5M）
  fileType?: string[]; // 接受的 MIME（图片 + 可选视频）==> 非必传
  height?: string; // 组件高度 ==> 非必传（默认为 150px）
  width?: string; // 组件宽度 ==> 非必传（默认为 150px）
  borderRadius?: string; // 组件边框圆角 ==> 非必传（默认为 8px）
  onSuccess?: (url: string) => void;
  onVideoPreview?: (url: string) => void; // 点击视频「查看」时的回调，用于父级弹窗放大预览（不传则新标签页打开）
  showSuccessNotification?: boolean; // 是否显示上传成功通知 ==> 非必传（默认为 true）
  hideUploadTrigger?: boolean; // 是否隐藏上传入口（达限或自定义隐藏时使用）==> 非必传（默认为 false）
}

const props = withDefaults(defineProps<UploadFileProps>(), {
  fileList: () => [],
  drag: true,
  disabled: false,
  limit: 5,
  fileSize: 5,
  fileType: () => ["image/jpeg", "image/png", "image/gif", "video/mp4", "video/webm", "video/quicktime", "video/ogg"],
  height: "150px",
  width: "150px",
  borderRadius: "8px",
  showSuccessNotification: true,
  hideUploadTrigger: false
});

// 上传入口是否隐藏（达限或显式传入 hideUploadTrigger 时）
const shouldHideUploadTrigger = computed(() => props.hideUploadTrigger || (props.fileList?.length ?? 0) >= props.limit);

// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 判断是否禁用上传和删除
const self_disabled = computed(() => {
  return props.disabled || formContext?.disabled;
});

const _fileList = ref<UploadUserFile[]>(props.fileList);

// 标记是否正在从 props 同步，避免循环更新
let isSyncingFromProps = false;

// 监听 props.fileList 列表默认值改变
watch(
  () => props.fileList,
  (n: UploadUserFile[]) => {
    isSyncingFromProps = true;
    _fileList.value = n;
    nextTick(() => {
      isSyncingFromProps = false;
    });
  }
);

// 监听 _fileList 的变化，自动同步到父组件（排除从 props 同步的情况）
// 注意：on-change 事件已经处理了大部分情况，这个 watch 作为备用
watch(
  () => _fileList.value,
  (newList, oldList) => {
    if (!isSyncingFromProps && newList !== oldList) {
      // 延迟执行，避免与 on-change 重复
      nextTick(() => {
        if (!isSyncingFromProps) {
          emit("update:fileList", [...newList]);
        }
      });
    }
  },
  { deep: true, immediate: false }
);

// 记录正在上传的文件数量（使用 Set 跟踪文件 UID，更可靠）
const uploadingFiles = new Set<string | number>();
// 标记是否已经显示过成功提示，防止重复提示
let hasShownSuccessNotification = false;
// 记录图片加载失败的 UID
const imageLoadError = ref<Set<string | number>>(new Set());

/** 判断是否为视频文件（按 raw.type 或 url/name 后缀） */
const isVideoFile = (file: UploadFile) => {
  const type = file.raw?.type;
  if (type && typeof type === "string" && type.startsWith("video/")) return true;
  const url = file.url || file.name || "";
  return /\.(mp4|webm|ogg|mov)(\?|$)/i.test(String(url));
};

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  const acceptVideo = props.fileType.some(t => String(t).startsWith("video/"));
  const byNameVideo = /\.(mp4|m4v|webm|ogg|mov)(\?.*)?$/i.test(rawFile.name || "");
  const mimeVideo = typeof rawFile.type === "string" && rawFile.type.startsWith("video/");
  const looseVideoMime =
    acceptVideo && byNameVideo && (!rawFile.type || rawFile.type === "application/octet-stream" || mimeVideo);
  const typeListed = props.fileType.includes(rawFile.type);
  const okType = typeListed || looseVideoMime;
  if (!okType)
    ElNotification({
      title: "温馨提示",
      message: "上传文件不符合所需的格式！",
      type: "warning"
    });
  if (!imgSize)
    setTimeout(() => {
      ElNotification({
        title: "温馨提示",
        message: `上传文件大小不能超过 ${props.fileSize}M！`,
        type: "warning"
      });
    }, 0);
  return okType && imgSize;
};

/**
 * @description 图片上传
 * @param options upload 所有配置项
 * */
const handleHttpUpload = async (options: UploadRequestOptions) => {
  // 开始上传，记录文件 UID
  const fileUid = options.file.uid;
  // 如果这是新的一批上传（Set 为空），重置成功提示标志
  if (uploadingFiles.size === 0) {
    hasShownSuccessNotification = false;
  }
  uploadingFiles.add(fileUid);
  let formData = new FormData();
  formData.append("file", options.file);
  try {
    const api = props.api ?? uploadImg;
    const response = await api(formData);
    // 从 response.fileUrl / response.data.fileUrl 取值
    const fileUrl = response?.fileUrl || response?.data?.fileUrl || "";

    if (fileUrl) {
      const coverUrlRaw =
        (response as any)?.coverUrl ?? (response as any)?.data?.coverUrl ?? (response as any)?.data?.cover ?? "";
      const coverUrl = typeof coverUrlRaw === "string" && coverUrlRaw.trim() ? coverUrlRaw.trim() : "";

      // 更新 options.file（Element Plus 传入的文件对象）
      (options.file as unknown as UploadFile).url = fileUrl;
      (options.file as unknown as UploadFile).status = "success";
      (options.file as unknown as UploadFile).response = response;
      if (coverUrl) {
        (options.file as any).coverUrl = coverUrl;
      }

      // 同步更新 _fileList 中对应的文件
      const fileIndex = _fileList.value.findIndex(item => item.uid === fileUid);
      if (fileIndex !== -1) {
        _fileList.value[fileIndex].url = fileUrl;
        _fileList.value[fileIndex].status = "success";
        (_fileList.value[fileIndex] as any).response = response;
        if (coverUrl) {
          (_fileList.value[fileIndex] as any).coverUrl = coverUrl;
        }
      }
    }

    options.onSuccess(response);
    // 传递更新后的 _fileList 给父组件
    emit("update:fileList", _fileList.value);
    if (props.onSuccess) {
      try {
        const result = props.onSuccess(fileUrl);
        // 如果回调返回 Promise，等待它完成（但不影响上传成功状态）
        if (result !== undefined && result !== null && typeof result === "object" && typeof (result as any).then === "function") {
          (result as Promise<any>).catch((callbackError: any) => {
            // 回调失败不影响上传成功状态，只记录错误
            console.error("onSuccess callback error:", callbackError);
          });
        }
      } catch (callbackError) {
        // 回调失败不影响上传成功状态，只记录错误
        console.error("onSuccess callback error:", callbackError);
      }
    }
  } catch (error) {
    // 上传失败，移除文件 UID
    uploadingFiles.delete(fileUid);
    options.onError(error as any);
  }
};

/**
 * @description 图片上传成功
 * @param response 上传响应结果
 * @param uploadFile 上传的文件
 * */
const emit = defineEmits<{
  "update:fileList": [value: UploadUserFile[]];
}>();
const uploadSuccess = (response: { fileUrl: string } | string | string[] | undefined, uploadFile: UploadFile) => {
  // 移除已完成的上传文件
  uploadingFiles.delete(uploadFile.uid);

  // 处理响应数据
  if (response) {
    if (typeof response === "string") {
      uploadFile.url = response;
    } else if (Array.isArray(response)) {
      uploadFile.url = response[0];
    } else if (response.fileUrl) {
      uploadFile.url = response.fileUrl;
    } else {
      // 如果 response 是对象但没有 fileUrl，尝试使用第一个属性值
      const values = Object.values(response);
      uploadFile.url = values[0] as string;
    }
    emit("update:fileList", _fileList.value);
    // 调用 el-form 内部的校验方法（可自动校验）
    formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
  }

  // 当所有文件上传完成时，显示成功提示（只显示一次）
  if (uploadingFiles.size === 0 && !hasShownSuccessNotification) {
    hasShownSuccessNotification = true;
    // 判断是否为视频文件，显示相应的提示语
    const isVideo = isVideoFile(uploadFile);
    ElNotification({
      title: "温馨提示",
      message: isVideo ? "视频上传成功！" : "图片上传成功！",
      type: "success"
    });
  }
};

/**
 * @description 文件列表变化处理
 * @param uploadFile 变化的文件
 * @param uploadFiles 当前文件列表
 */
const handleFileListChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  // 当文件列表变化时，同步到父组件
  if (!isSyncingFromProps) {
    emit("update:fileList", uploadFiles as UploadUserFile[]);
  }
};

/**
 * @description 删除图片
 * @param file 删除的文件
 * */
const handleRemove = (file: UploadFile) => {
  _fileList.value = _fileList.value.filter(item => item.url !== file.url || item.name !== file.name);
  emit("update:fileList", _fileList.value);
  // 移除时清除错误状态
  imageLoadError.value.delete(file.uid);
};

/**
 * @description 图片加载错误处理
 * */
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  // 通过查找对应的文件来获取 UID
  const file = _fileList.value.find(f => f.url === img.src);
  if (file && file.uid !== undefined) {
    imageLoadError.value.add(file.uid);
  }
};

/**
 * @description 图片加载成功处理
 * */
const handleImageLoad = (event: Event) => {
  const img = event.target as HTMLImageElement;
  const file = _fileList.value.find(f => f.url === img.src);
  if (file && file.uid !== undefined) {
    imageLoadError.value.delete(file.uid);
  }
};

/**
 * @description 图片上传错误
 * */
const uploadError = () => {
  ElNotification({
    title: "温馨提示",
    message: "上传失败，请您重新上传！",
    type: "error"
  });
};

/**
 * @description 文件数超出
 * */
const handleExceed = () => {
  ElNotification({
    title: "温馨提示",
    message: `当前最多只能上传 ${props.limit} 个文件，请移除后上传！`,
    type: "warning"
  });
};

/**
 * @description 图片预览
 * @param file 预览的文件
 * */
const viewImageUrl = ref("");
const imgViewVisible = ref(false);
const handlePictureCardPreview: UploadProps["onPreview"] = file => {
  if (!file.url) return;
  if (isVideoFile(file)) {
    if (props.onVideoPreview) {
      props.onVideoPreview(file.url);
    } else {
      window.open(file.url, "_blank");
    }
    return;
  }
  viewImageUrl.value = file.url;
  imgViewVisible.value = true;
};
</script>

<style scoped lang="scss">
.is-error {
  .upload {
    :deep(.el-upload--picture-card),
    :deep(.el-upload-dragger) {
      border: 1px dashed var(--el-color-danger) !important;
      &:hover {
        border-color: var(--el-color-primary) !important;
      }
    }
  }
}
:deep(.disabled) {
  .el-upload--picture-card,
  .el-upload-dragger {
    cursor: not-allowed;
    background: var(--el-disabled-bg-color) !important;
    border: 1px dashed var(--el-border-color-darker);
    &:hover {
      border-color: var(--el-border-color-darker) !important;
    }
  }
}
.upload-box {
  .no-border {
    :deep(.el-upload--picture-card) {
      border: none !important;
    }
  }
  :deep(.upload) {
    .el-upload-dragger {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      padding: 0;
      overflow: hidden;
      border: 1px dashed var(--el-border-color-darker);
      border-radius: v-bind(borderRadius);
      &:hover {
        border: 1px dashed var(--el-color-primary);
      }
    }
    .el-upload-dragger.is-dragover {
      background-color: var(--el-color-primary-light-9);
      border: 2px dashed var(--el-color-primary) !important;
    }
    .el-upload-list__item,
    .el-upload--picture-card {
      width: v-bind(width);
      height: v-bind(height);
      background-color: transparent;
      border-radius: v-bind(borderRadius);
    }
    .upload-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    .upload-image-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      color: var(--el-text-color-secondary);
      background-color: var(--el-fill-color-lighter);
      .el-icon {
        margin-bottom: 8px;
        font-size: 32px;
      }
      span {
        font-size: 12px;
      }
    }
    .upload-handle {
      position: absolute;
      top: 0;
      right: 0;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      cursor: pointer;
      background: rgb(0 0 0 / 60%);
      opacity: 0;
      transition: var(--el-transition-duration-fast);
      .handle-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 0 6%;
        color: aliceblue;
        .el-icon {
          margin-bottom: 15%;
          font-size: 140%;
        }
        span {
          font-size: 100%;
        }
      }
    }
    .el-upload-list__item {
      &:hover {
        .upload-handle {
          opacity: 1;
        }
      }
    }
    .upload-empty {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 12px;
      line-height: 30px;
      color: var(--el-color-info);
      .el-icon {
        font-size: 28px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  .el-upload__tip {
    line-height: 15px;
    text-align: center;
  }

  /* 隐藏上传入口（达限或 hideUploadTrigger 为 true 时），隐藏包含 Plus 图标的触发区域 */
  &.hide-upload-trigger :deep(.el-upload:has(.upload-empty)) {
    display: none;
  }
}
</style>
