<template>
  <div v-for="(item ,index) in previewUrl" style="position:relative;">
    <!-- <img v-if="previewUrl?.length>0" :src="item" class="box" style="cursor: pointer" @click="clickImg(item)"/> -->
    <el-image ref="imageRef" :preview-teleported="true" :preview-src-list="previewUrl" :initial-index="index"
              :src="item" class="box" />
    <el-icon
      style="position: absolute;top: 10px;right: 7px;color: red;cursor: pointer" @click="del(index)">
      <Delete />
    </el-icon>
  </div>
  <el-upload
    class="box"
    action="#"
    :show-file-list="false"
    :http-request="upload"
    accept=".jpg, .jpeg, .png"
    v-if="previewUrl?.length<limit"
  >
    <el-icon class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>

</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, ref, watch } from "vue";
import { fileUpload } from "/@/api/common";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import { ElNotification } from "element-plus/es";


const disabled = ref(false);

const props = defineProps({
  fileUrl: {
    type: String,
    default: ""
  },
  limit: {
    type: Number,
    default: 1
  },
  size: {
    type: Number,
    default: 1000000
  }
});

const imageRef = ref();

onMounted(() => {
  if (props.fileUrl?.length > 0) {
    previewUrl.value = JSON.parse(props.fileUrl);
  } else {
    previewUrl.value = [];
  }
});

watch(() => props.fileUrl, () => {
  if (props.fileUrl?.length > 0) {
    previewUrl.value = JSON.parse(props.fileUrl);
  } else {
    previewUrl.value = [];
  }
});


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


//上传图片路径
let previewUrl = ref<Array<any>>([]);

function upload(file: any) {
  //大小限制为0时为不限制
  if (file.file.size > props.size && props.size > 0) {
    ElNotification({ type: "error", message: "文件大小不能超过1MB" });
    return;
  }
  let fd = new FormData();
  fd.append("file", file.file);
  fileUpload(fd).then(res => {
    previewUrl.value.push(res.data.previewUrl);
    emit("update:fileUrl", JSON.stringify(previewUrl.value));
  });
}

function del(index: number) {
  previewUrl.value.splice(index, 1);
  emit("update:fileUrl", JSON.stringify(previewUrl.value));
}


</script>

<style scoped>
.box {
  height: 90px;
  width: 90px;
  border: #bfc0c2 1px dashed;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 23px 10px 0;
}
</style>
