<!-- 图片上传 -->
<script>
export default {
  name: "ImageUpload",
  props: {
    value: [String, Object, Array],
    maxCount: {
      type: [Number, String],
      default: 9,
    },
    fileType: {
      type: Array,
      default: () => ["jpg", "jpeg", "png"],
    },
    // fileSize: {
    //   type: Number,
    // },
  },
  data() {
    return {
      fileList: [],
    };
  },
  computed: {
    accept: {
      get() {
        const { fileType } = this.$props;
        const typeList = fileType.reduce((str, item) => {
          return (str += "." + item + ",");
        }, "");
        return typeList;
      },
      set() {},
    },
  },
  methods: {
    afterRead(file) {
      let {
        fileList,
        $props: { maxCount },
      } = this;
      this.$emit("input", fileList);

      if (fileList.length === maxCount) {
        this.$toast(`最多可上传${maxCount}个文件`);
      }
    },
    useDelete(file) {
      this.$emit("input", this.fileList);
    },
    beforeRead(file, detail) {
      const fileTypeList = file.type.split("/");
      const fileExt = fileTypeList[fileTypeList.length - 1];
      const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
      console.log(isTypeOk, "isTypeOk");
      if (!isTypeOk) {
        this.$toast(
          `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
        );
        return false;
      }
      return true;
      // const { fileSize, accept } = this.$props;
      // const imgformat = /image\/(png|jpg|jpeg)$/;
      // if (!imgformat.test(file.type)) {
      //   this.$toast.fail(`请上传 ${accept} 格式图片`);
      //   return false;
      // }
    },
  },
  created() {},
};
</script>

<template>
  <div class="upload-image">
    <van-uploader
      v-model="fileList"
      multiple
      preview-size="60px"
      :accept="accept"
      :max-count="maxCount"
      :after-read="afterRead"
      :before-read="beforeRead"
      @delete="useDelete"
    />
  </div>
</template>
