<template>
  <el-upload v-model:file-list="fileList" ref="uploadRef" action="" :list-type="props.listType" :class="props.classnames"
    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :limit="props.limit"
    :showFileList="false"
    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :auto-upload="false" :on-change="handFileChange"
    :show-file-list="props.showFileList" :accept="props.fileType" :multiple="props.multiple">
    <slot><el-icon>
        <Plus />
      </el-icon></slot>
  </el-upload>

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

<script setup>
import { ref } from "vue";
import { Plus } from "@element-plus/icons-vue";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const emit = defineEmits(["hand-file-change"]);
let fileList = ref([]);
let files = [];
const props = defineProps({
  classnames: { type: String, default: '' },
  fileType: {
    type: String,
    default: "",
  },
  listType: {
    type: String,
    default: "picture-card",
  },
  path: {
    type: String,
    default: "",
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 1,
  },
  showFileList: {
    type: Boolean,
    default: true
  },
  fileList: {
    type: Array,
    default: [],
  },
});
fileList.value = props.fileList;

const handFileChange = async (e) => {
  files.push(e);
  emit("hand-file-change", files);
};
function handleRemove(e) {
  files = files.filter((item) => item.uid !== e.uid);
  emit("hand-file-change", files);
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};

const uploadRef = ref()
defineExpose({
  clearFiles: () => {
    uploadRef.value.clearFiles()
    fileList.value = []
  }
})
</script>

<style lang="scss" scoped>
/* 后面的提示文字颜色 */
[type="file"] {
  font-size: 0;
  width: 100px;
  height: 100px;
  opacity: 0;
}

.add-btn {
  margin-top: 10px;
  margin-left: 10px;
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: #006eff;
  border: 1px solid #006eff;
  text-align: center;
  border-radius: 8px;
  cursor: pointer;
  box-sizing: border-box;

  .inView {
    z-index: -1;
  }
}

/* 主按钮的样式自定义 */
::file-selector-button {
  border: none;
  outline: none;
  background: none;
  box-shadow: none;
}
</style>
