<template>
  <div class="payment-upload-wrap">
    <div class="img-upload-browse-wrap">
      <Button
        :id="`img-upload-browse${rd}`"
        :loading="loading"
        :disabled="disabled"
        type="ghost"
        icon="ios-cloud-upload-outline"
      >
        {{ btnText }}
      </Button>
    </div>
  </div>
</template>
<script>
export default {
  name: 'FileUpload',
  components: {},
  directives: {},
  props: {
    btnText: {
      type: String,
      default: '上传附件'
    },
    // 上传路径
    uploadUrl: {
      type: String,
      default: ''
    },
    // 如果有传入 action 则上传路径为 actionUrl
    action: {
      type: String,
      default() {
        return '';
      }
    },
    max: {
      type: Number,
      default() {
        return -1;
      }
    },
    params: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      loading: false,
      disabled: false,
      uploader: null,
      images: [],
      files: [],
      uploadResolve: null,
      rd: new Date().getTime()
    };
  },
  computed: {
    displayBrowse() {
      return !~this.max || (!!~this.max && this.files.length < this.max);
    },
    actionUrl() {
      if (this.action) {
        let origin = '';
        if (location.origin != location.href.split('/#')[0]) {
          origin = location.href.split('/#')[0];
        } else {
          origin = location.origin;
        }
        let url = '';
        url = `${origin}/ems-base-application/baseData/file/upload${this.action}`;
        return url;
      }
      return '';
    }
  },
  watch: {},
  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 = [];
      const rd = this.rd;

      this.uploader = new plupload.Uploader({
        // 实例化一个plupload上传对象
        browse_button: `img-upload-browse${rd}`, // rd 页面有可能存在多个上传按钮 - V
        url: this.actionUrl || this.uploadUrl,
        multi_selection: true,
        headers: {
          crctoken: sessionStorage.crctoken
        },
        multipart_params: {
          name: 'file',
          ...this.params
        }
      });
      this.uploader.init();
      this.uploader.bind('FilesAdded', (uploader, files) => {
        for (var i = 0, len = files.length; i < len; i++) {
          const file_name = files[i].name.split('.');
          const suffix = file_name[file_name.length - 1];
          this.files.push(files[i]);
        }
        this.start();
      });
      this.uploader.bind('Error', (uploader, errObject) => {
        this.$emit('Error', {
          uploader,
          response: JSON.parse(errObject.response)
        });
      });
      this.uploader.bind('UploadProgress', (uploader, files) => {
        this.$emit('UploadProgress', {
          uploader,
          files
        });
      });
      this.uploader.bind('FileUploaded', (uploader, file, responseObject) => {
        console.log('responseObject', responseObject);
        this.$emit('FileUploaded', {
          uploader,
          file,
          response: JSON.parse(responseObject.response)
        });
      });
      this.uploader.bind('UploadComplete', (uploader, files) => {
        this.$emit('UploadComplete', {
          uploader,
          files
        });
        this.loading = false;
        this.disabled = false;
        this.images = [];
        this.uploadResolve();
        this.uploader.disableBrowse(false);
      });
    },
    start() {
      return new Promise(resolve => {
        if (this.files.length > 0) {
          this.uploader.disableBrowse(true);
          this.loading = true;
          this.disabled = true;
          this.uploadResolve = resolve;
          this.uploader.start();
        } else {
          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;
    }
  }
};
</script>
<style lang="less">
.payment-upload-wrap {
  display: inline-block;
}
.payment-upload-item {
  height: 38px;
  line-height: 38px;
  position: relative;
  padding-left: 20px;
  i {
    position: absolute;
    top: 12px;
    left: 0;
    cursor: pointer;
  }
}
</style>
