<template>
  <el-image :preview-teleported="true" :preview-src-list="[previewUrl]" v-if="previewUrl?.length>0&&previewUrl!='[]'"
            :src="previewUrl" class="box" />
  <el-upload class="box" action="#" :show-file-list="false" :http-request="upload" :accept="accept">
    <el-icon class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>

  <el-dialog v-model="watchImg" width="50%" :show-close="false">
    <img :src="previewUrl" style="width: 100%" />
  </el-dialog>

</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { fileUpload } from "/@/api/common";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadInstance, UploadProps, UploadRawFile, UploadFile } from "element-plus";
import { genFileId } from "element-plus";
import { ElNotification } from "element-plus/es";
import { log } from "/@/api/backend/routine/AdminInfo";


const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  size: {//上传文件大小限制B
    type: Number,
    default: 1000000
  },
  accept: {//接收文件后缀
    type: String,
    default: ".jpg, .jpeg, .png"
  }
});


watch(() => props.modelValue, (newVal) => {
  previewUrl.value = newVal;
});


onMounted(() => {
  previewUrl.value = props.modelValue;
});

// const emit = defineEmits(["update:fileUrl"]);
const emit = defineEmits(["input","update:modelValue"]);



const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

//上传图片路径
let previewUrl = ref<string>("");

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 = res.data.previewUrl;
    console.log(previewUrl.value);
    // emit("update:fileUrl", previewUrl.value);
    emit("update:modelValue", previewUrl.value);
  });
}

//图片预览
let watchImg = ref(false);
let showUrl = ref("");


</script>

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