/**
 * Created by chenyucai on 2017/4/19.
 */

/* eslint-disable */
import 'whatwg-fetch';
import store from './storage';
import config from './config';
import Md5 from './Md5';
import signature from './signature';

import Vue from 'vue';
import iView from 'iview';

Vue.use(iView);

const Vm = new Vue();

// 设置请求超时时间(sec)
const TIME_OUT = 15;

// 设置需要重新登陆的code
const NEED_RELOGIN_CODE = ['A00006', 'A00007', 'A00008'];

const BUCKET_RCST = 'rcst'; // oss不需要验签
const BUCKET_RCFS = 'rcfs'; // oss需要验签

const OSS_RCST_HOST = 'http://rcst.oss-cn-shanghai.aliyuncs.com/'; // rcst 域名

const request = {
  /**
	 * @url 接口地址
	 * @params 请求的参数
	 * @callback 回调函数
	 */
	post(url, params, callback) {
    this.beforeSend();
    let timer = setTimeout(() => { this.timeout(); }, TIME_OUT * 1000);

		let data = Object.assign({}, params);

    let requestHeader = signature.getRequestHeader();
    let pa = signature.cover(data, requestHeader, requestHeader['X-Client-Time']);

    let options = {
      method: 'POST',
      headers: requestHeader,
      body: JSON.stringify(pa)
    };

		fetch(url, options).then((response) => {
      clearTimeout(timer);
      this.complete();
      return response.json();
    }).then((responseJson) => {
				if (NEED_RELOGIN_CODE.indexOf(responseJson.code) !== -1) {
					window.location = "/#/login"
				}else {
					if (!responseJson.result) {
						Vm.$Message.error({
							content: responseJson.msg,
							duration: 5
						});
					}
					callback(responseJson);
				}
		}).catch((error) => {
      console.log('request failed ---- ' + error);
    });
	},

  /**
   * 返回blob
   */
  blob(url, params) {
    this.beforeSend();

    let data = Object.assign({}, params);

    let requestHeader = signature.getRequestHeader();
    let pa = signature.cover(data, requestHeader, requestHeader['X-Client-Time']);

    let options = {
      method: 'POST',
      headers: requestHeader,
      body: JSON.stringify(pa)
    };

    return new Promise((resolve, reject) => {
      fetch(url, options).then((response) => {
        this.complete();
        resolve(response.blob());
      });
    });
  },

  beforeSend() { iView.LoadingBar.start(); },

  complete() { iView.LoadingBar.finish(); },

  timeout() { Vm.$Message.error('请求超时'); },

  ossRCST(url, fileKey) {
    return this.pushOss(url, fileKey, BUCKET_RCST);
  },

  ossRCFS(url, fileKey) {
    return this.pushOss(url, fileKey, BUCKET_RCFS);
  },

  ossRCFSPreview(url, fileKey) {
    this.beforeSend();
    let timer = setTimeout(() => { this.timeout(); }, TIME_OUT * 1000);

    let params = { bucket: BUCKET_RCFS, fileKey: fileKey };
    let requestHeader = signature.getRequestHeader();
    let pa = signature.cover(params, requestHeader);

    let options = {
      method: 'POST',
      headers: requestHeader,
      body: JSON.stringify(pa)
    };

    return new Promise((resolve, reject) => {
      fetch(url, options).then((response) => {
        clearTimeout(timer);
        this.complete();
        resolve(response.blob());
      });
    });
  },

  ossRCSTPreview(fileKey) {
    return OSS_RCST_HOST + fileKey;
  },

  pushOss(url, fileKey, bucket) {
    return new Promise((resolve, reject) => {
      let params = { bucket: bucket, fileKey: fileKey };
      this.post(url, params, (res) => {
        let formData = this.initOssFormData(res.data);
        resolve(formData);
      });
    });
  },

  initOssFormData(data) {
    let formData = {};
    formData['OSSAccessKeyId'] = data.accessId;
    formData['policy'] = data.policy;
    formData['Signature'] = data.signature;
    formData['success_action_status'] = '200';
    formData['key'] = data.fileKey;
    formData['upLocation'] = data.upLocation;
    return formData;
  },
};

export default request;
