<template>
  <el-image :preview-teleported="true" :preview-src-list="previewList"
            v-if="fileUrl?.length>0"
            :src="previewList[0]" 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="previewList[0]" style="width: 100%" />
  </el-dialog>

</template>

<script setup lang="ts">
import { computed, 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";
import * as process from "process";


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"
  }
});

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

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


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


let previewList = computed(() => {
  const baseUrl = import.meta.env.VITE_AXIOS_BASE_URL;
  return [baseUrl + "/uploadFile/" + fileUrl.value];
});

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


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


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

//图片预览
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>
