<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    action="/api/placeholder"
    accept=".jpg,.png"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    :before-upload="beforeUpload"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件，且不超过500kb
    </div>
  </el-upload>
</template>

<script>
import MD5 from "js-md5";
import { uploadFile } from "@/api/system-info";

export default {
  props: { value: String },
  data() {
    return {
      fileList: [
        {
          name: "",
          url: this.value || "",
        },
      ],
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        this.fileList[0].url = v;
      },
    },
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
      const url = "";
      this.fileList[0].url = url;
      this.$emit("input", url);
      this.$emit("change", url);
    },
    handlePreview(file) {
      console.log(file);
    },
    async beforeUpload(file) {
      console.log(file);
      async function blobToArray(blob) {
        return new Promise((resolve) => {
          var reader = new FileReader();
          reader.addEventListener("loadend", function () {
            // reader.result contains the contents of blob as a typed array
            resolve(reader.result);
          });
          reader.readAsArrayBuffer(blob);
        });
      }
      const ab = await blobToArray(file);
      const md5 = MD5(ab);

      const res = await uploadFile({ file, md5 });
      console.log(res);
      const url = res.data.data.url;
      this.fileList[0].url = url;
      this.$emit("input", url);
      this.$emit("change", url);
      // return Promise.reject("stop upload");
    },
  },
};
</script>

<style></style>
