<template>
  <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
    :on-change="handleChange"
    :limit="limit"
    :auto-upload="false"
    :show-file-list="false"
  >
    <el-button
      type="primary"
      :loading="loading"
      :disabled="fileList.length >= limit"
      >点击上传文件</el-button
    >
    <template #tip>
      <div class="tip">
        文件类型限制为.jpg,.jpeg,.png,word文档,pdf,大小不超过{{ size }}M
      </div>
    </template>
    <div>
      <el-tag
        class="file-item"
        v-for="(file, index) in fileList"
        :key="file.name"
        closable
        type="success"
        @close="deleteFile(index)"
      >
        {{ file.name }}
      </el-tag>
    </div>
  </el-upload>
</template>
<script lang="ts" setup>
import { ref } from "vue";

const props = defineProps({
  size: {
    type: Number,
    default: 4,
  },
  limit: {
    type: Number,
    default: 1,
  },
  src: {
    type: String,
    default: "",
  },
  srcList: {
    type: Array,
    default: [],
  },
});

const loading = ref(false);

const emit = defineEmits(["update:src", "update:srcList"]);

// 上传文件成功返回的值
const src = useVModel(props, "src", emit); //单文件用这个
const srcList = useVModel(props, "srcList", emit); //多文件用这个

import { UploadFile, UploadFiles, UploadUserFile } from "element-plus";
import { uploadFileApi } from "@/api/file";

// el-upload 绑定的值
const fileList = ref<UploadUserFile[]>([]);

const handleChange = async (uploadFile: UploadFile) => {
  if (uploadFile.size! > props.size * 1048 * 1048) {
    ElMessage.warning(`上传文件不能大于${props.size}M`);
    return;
  }
  loading.value = true;
  uploadFileApi(uploadFile.raw as File)
    .then((res: any) => {
      loading.value = false;
      src.value = res.data.fileUrl;
      srcList.value.push(res.data.fileUrl);
    })
    .catch((err) => {
      ElMessage.error(err.message);
      loading.value = false;
    });
};

const deleteFile = (index: number) => {
  src.value = ""; //删除直接清空src即可，不用考虑是哪个，因为单文件不会有多个
  fileList.value.splice(index, 1);
  srcList.value.splice(index, 1);
};
</script>

<style scoped lang="scss">
.tip {
  font-size: 12px;
  color: #e6a23c;
  margin-top: 5px;
}
.file-item {
  margin-left: 10px;
}
</style>
