<template>
  <div class="img-upload-wrap">
    <div class="img-upload-item" v-for="(item,index) in images" :key="index" :style="{'background-image':'url('+item.src+')'}">
      <Icon type="close-circled" class="img-upload-item-close" @click.native="remove(index)"></Icon>
    </div>
    <div class="img-upload-browse-wrap">
      <div v-show="displayBrowse">
        <Icon id="img-upload-browse" type="upload"></Icon>
      </div>
    </div>
  </div>
</template>
<style lang="less">
@import "./upload.less";
</style>
<script>
export default {
  name: "img-upload",
  props: {
    action: {
      type: String,
      default() {
        return "";
      }
    },
    max: {
      type: Number,
      default() {
        return -1;
      }
    },
    params: {
      type: Object,
      default: {}
    }
  },
  components: {},
  data() {
    return {
      uploader: null,
      images: [],
      files: [],
      uploadResolve: null
    };
  },
  computed: {
    displayBrowse() {
      return !~this.max || (!!~this.max && this.files.length < this.max);
    }
  },
  created: function() {},
  beforeMount: function() {},
  mounted: function() {
    this.upLoadInit();
  },
  beforeDestroy: function() {},
  destroyed: function() {
    if (!!this.uploader) {
      this.uploader.destroy();
    }
  },
  methods: {
    upLoadInit() {
      if (!!this.uploader) {
        this.uploader.destroy();
      }
      this.images = [];
      let origin = location.origin
        ? location.origin
        : location.href.split("/#")[0];
      this.uploader = new plupload.Uploader({
        //实例化一个plupload上传对象
        browse_button: "img-upload-browse",
        url: `${origin}/${process.env.API.baseURL}${this.action}`,
        multi_selection: false,
        headers: {
          crctoken: sessionStorage.crctoken
        },
        multipart_params: {
          name: "file"
          // ...params
        },
        // multipart: false,
        filters: {
          mime_types: [{ title: "图片文件", extensions: "jpg,gif,png" }],
          max_file_size: "3000kb"
        }
      });
      this.uploader.init();
      this.uploader.bind("FilesAdded", (uploader, files) => {
        for (var i = 0, len = files.length; i < len; i++) {
          let file_name = files[i].name.split(".");
          let suffix = file_name[file_name.length - 1];
          if (this.displayBrowse) {
            this.files.push(files[i]);
            this.previewImage(files[i], imgsrc => {
              this.images.push({
                src: imgsrc,
                suffix
              });
            });
          }
        }
      });
      this.uploader.bind("Error", (uploader, errObject) => {});
      this.uploader.bind("UploadProgress", (uploader, files) => {
        this.$emit("UploadProgress", {
          uploader,
          files
        });
      });
      this.uploader.bind("FileUploaded", (uploader, file, responseObject) => {
        this.$emit("FileUploaded", {
          uploader,
          file,
          response: responseObject.response
        });
      });
      this.uploader.bind("UploadComplete", (uploader, files) => {
        this.$emit("UploadComplete", {
          uploader,
          files
        });
        this.images = [];
        this.uploadResolve();
      });
    },
    start() {
      return new Promise(resolve => {
        if (this.images.length > 0) {
          this.uploadResolve = resolve;
          this.uploader.start();
          return;
        }
        // resolve();
      });
    },
    remove(index) {
      this.images.splice(index, 1);
      this.uploader.removeFile(this.files[index]);
      this.files.splice(index, 1);
    },
    isEmpy() {
      return this.files.length < 1;
    },
    previewImage(file, callback) {
      if (!file || !/image\//.test(file.type)) return; //确保文件是图片
      if (file.type == "image/gif") {
        //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
        var fr = new mOxie.FileReader();
        fr.onload = function() {
          callback(fr.result);
          fr.destroy();
          fr = null;
        };
        fr.readAsDataURL(file.getSource());
      } else {
        var preloader = new mOxie.Image();
        preloader.onload = function() {
          // preloader.downsize(300, 300);//先压缩一下要预览的图片,宽300，高300
          var imgsrc =
            preloader.type == "image/jpeg"
              ? preloader.getAsDataURL("image/jpeg", 80)
              : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
          callback && callback(imgsrc); //callback传入的参数为预览图片的url
          preloader.destroy();
          preloader = null;
        };
        preloader.load(file.getSource());
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
