<template>
  <div class="imgViewBox" v-for="(item ,index) in previewUrl">
    <!-- <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" />
    <div class="imgDeleteBtn">
      <el-icon
        style="color: red;font-weight: bold;cursor: pointer" @click="del(index)">
        <Delete />
      </el-icon>
    </div>

  </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({
  modelValue: {
    type: String,
    default: ""
  },
  limit: {
    type: Number,
    default: 1
  },
  size: {
    type: Number,
    default: 1000000
  }
});

const imageRef = ref();

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

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


const emit = defineEmits(["input"]);


//上传图片路径
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("input", JSON.stringify(previewUrl.value));
  });
}

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


</script>

<style scoped lang="scss">

.box {
  height: 88px;
  width: 88px;
  border: #bfc0c2 1px dashed;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 23px 10px 0;
}

.imgViewBox {
  position: relative;
  height: 90px;
  width: 90px;

  .imgDeleteBtn {
    display: none;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
    //display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.5);
  }

  &:hover {
    .imgDeleteBtn {
      display: flex;
    }
  }
}
</style>
