/*
 * @Author: lijianzhang
 * @Date: 2018-11-01 16:25:11
 * @Last Modified by: lijianzhang
 * @Last Modified time: 2019-02-16 17:09:50
 * oss 服务封装
 */
import request from '../request';
const namespace = 'gaoding/';
export default class OSS {
  async getToken(file) {
    const promise = request.post('/api/tokens', {
      type: 'oss',
      file_type: 'image',
      key: this.getKey(file)
    });
    this._cancel = promise.cancel;
    return promise;
  }

  getKey(file) {
    let now = new Date();
    let filename = now.getFullYear();
    filename += ('00' + (now.getMonth() + 1)).slice(-2);
    filename += ('00' + now.getDate()).slice(-2);
    filename += '-';
    filename += ('00' + now.getHours()).slice(-2);
    filename += ('00' + now.getMinutes()).slice(-2);
    filename += ('00' + now.getSeconds()).slice(-2);
    filename += ('00' + now.getTime()).slice(-3);
    filename += `-${Math.random().toString(16).slice(-6)}`;
    filename += '.' + file.type.slice(file.type.lastIndexOf('/') + 1);
    return namespace + filename;
  }

  async uploadFile(file, options) {
    return this.getToken(file).then(async ({
      data: token
    }) => {
      const formData = new FormData();
      formData.append('key', token.key);
      formData.append('policy', token.policy);
      formData.append('Signature', token.signature);
      formData.append('OSSAccessKeyId', token.access_key);
      formData.append('success_action_status', 200);
      formData.append('OSSUploadAction', token.oss_action);
      formData.append('file', file);
      const promise = request.post('//image-uploader.dancf.com/', formData, {
        onUploadProgress(e) {
          e.percent = 100 * e.loaded / e.total;

          if (options.onProgress) {
            options.onProgress(e);
          }
        },

        withCredentials: false
      });
      this._cancel = promise.cancel;
      return promise.then(() => token.oss_action + '/' + token.key);
    }).catch(error => {
      throw error;
    });
  }

  cancel(message) {
    if (this._cancel) {
      this._cancel(message);

      this._cancel = null;
    }
  }

}