import http from './request';
import 'whatwg-fetch';
import { ossConfig } from './config';

const oss = {};

/* 不需要验签 rcst */
/* 需要验签 rcfs */

/* 验签,拿fileKey(阿里云存放文件的地址) */
oss.signature = (bucket, fileKey, url) => {
  return new Promise((resolve, reject) => {
    http.post(url, { bucket, fileKey }, (res) => {
      resolve(res);
    });
  });
};

/* 预览 */
oss.preview = (bucket, fileKey, url) => {
  if (bucket === ossConfig.BUCKET_RCST) {
    return Promise.resolve(ossConfig.RCST_HOST + fileKey + '?' + new Date().getTime());
  } else {
    return new Promise((resolve, reject) => {
      http.blob(url, { bucket, fileKey }).then((res) => {
        resolve(window.URL.createObjectURL(res)); // blob -> url
      });
    });
  }
};

/**
 * 上传文件
 * @param bucket
 * @param fileKey
 * @param url
 * @param file
 */
oss.upload = (bucket, fileKey, url, file) => {
  let prefileKey = fileKey;
  return new Promise((resolve, reject) => {
    oss.signature(bucket, fileKey, url).then((res) => {
      // 创建一个form对象
      let form = new FormData();
      // 使用FormData.append来添加键/值对到表单里面;
      form.append('OSSAccessKeyId', res.data.accessId);
      form.append('policy', res.data.policy);
      form.append('Signature', res.data.signature);
      form.append('success_action_status', '200');
      form.append('key', oss.suffix(res.data.fileKey, file, prefileKey));
      form.append('upLocation', res.data.upLocation);
      form.append('file', file);

      let fKey = oss.suffix(res.data.fileKey, file, prefileKey);
      fetch(res.data.upLocation, {
        method: 'POST',
        body: form
      }).then((res) => {
        if (res.status === 200) {
          resolve({fileKey: fKey});
        }
      });
    });
  });
};

/* 初始化formData,传入iView的upload组件 */
oss.getFormData = (bucket, fileKey, url, file) => {
  let prefileKey = fileKey;
  return new Promise((resolve, reject) => {
    oss.signature(bucket, fileKey, url).then((res) => {
      // 创建一个form对象
      let formData = {};
      formData['OSSAccessKeyId'] = res.data.accessId;
      formData['policy'] = res.data.policy;
      formData['Signature'] = res.data.signature;
      formData['success_action_status'] = '200';
      formData['key'] = oss.suffix(res.data.fileKey, file, prefileKey);
      formData['upLocation'] = res.data.upLocation;
      resolve(formData);
    });
  });
};

/* 处理文件后缀名 */
oss.suffix = (fileKey, file, prefileKey) => {
  if (prefileKey && prefileKey !== '') {
    return fileKey;
  } else {
    let fileName = file.name;
    let lastDotIndex = fileName.lastIndexOf('.');
    return fileKey + fileName.substring(lastDotIndex, fileName.length);
  }
};

export default oss;
