<template>
  <div class="upload-container">
    <el-upload
      v-model:file-list="fileList"
      :before-upload="handleBeforeUpload"
      :http-request="handleUpload"
      :limit="limit"
      :show-file-list="false"
      class="img-box"
      list-type="picture-card"
    >
      <i-ep-plus />
    </el-upload>
    <div v-for="(item, index) in fileList" :key="index" class="img-container">
      <img :src="item.url" class="img-box" object-fit="cover" />
      <Delete class="delete-icon" @click="deleteImg(index)" />
    </div>
  </div>

  <el-dialog v-model="dialogVisible">
    <img :src="previewImgUrl" alt="Preview Image" w-full />
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  UploadRawFile,
  UploadRequestOptions,
  UploadUserFile,
} from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import { uploadFileApi } from "@/api/file";

const emit = defineEmits(["update:modelValue"]);

const props = defineProps({
  /**
   * 文件路径集合
   */
  modelValue: {
    type: Array<string>,
    default: () => [],
  },
  /**
   * 文件上传数量限制
   */
  limit: {
    type: Number,
    default: 10,
  },
});

const previewImgUrl = ref("");
const dialogVisible = ref(false);

const fileList = ref([] as UploadUserFile[]);
const urlList = ref([] as string[]); // 上传成功后的图片路径集合,要传给父组件

/**
 * 自定义图片上传
 *
 * @param params
 */
async function handleUpload(options: UploadRequestOptions): Promise<any> {
  // 上传API调用
  const res: any = await uploadFileApi(options.file);
  urlList.value.push(res.data.fileUrl);
  emit("update:modelValue", urlList.value);
}

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于2M");
    return false;
  }
  return true;
}

const deleteImg = (index: number) => {
  fileList.value.splice(index, 1);
  urlList.value.splice(index, 1);
  emit("update:modelValue", urlList.value);
};

/**
 * 预览图片
 */
// const previewImg: UploadProps["onPreview"] = (uploadFile) => {
//   previewImgUrl.value = uploadFile.url!;
//   dialogVisible.value = true;
// };
</script>

<style lang="scss" scoped>
.upload-container {
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
}

.img-container {
  position: relative;
}

.img-box {
  width: 148px;
  height: 148px;
  display: block;
  margin-right: 10px;
  margin-top: 10px;
  border-radius: 4px;
}

.delete-icon {
  position: absolute;
  width: 20px;
  height: 20px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: red;
  cursor: pointer;
}
</style>
