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

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

/**
 * 设置超时时间
 * 秒
 */
const TIME_OUT = 15;

const secret = 'kLnANE';

/**
 * 验签
 */
const getRequestHeader = () => {
  let r = config.requestHeader;

  let sort = ['Content-Type', 'X-Reply-Type', 'X-Vnum', 'X-Channel', 'X-Device', 'X-Udid', 'X-Client-Time', 'X-Pub-Key', 'X-Signature'];

  let requestHeader = {};
  requestHeader['Content-Type'] = r.ContentType;
  requestHeader['X-Reply-Type'] = r.ReplyDataType;
  requestHeader['X-Vnum'] = r.Vnum;
  requestHeader['X-Channel'] = r.Channel;
  requestHeader['X-Device'] = r.Device;
  requestHeader['X-Udid'] = r.Udid();
  requestHeader['X-Client-Time'] = r.ClientTime();
  requestHeader['X-Pub-Key'] = r.PubKey();
  requestHeader['X-Signature'] = r.Signature();

  let authArray = [];
  for (let i = 0; i < sort.length; i++) {
    authArray.push("\"" + sort[i] + '\":\"' + requestHeader[sort[i]] + "\"");
  }
  let authStr = '{' + authArray.join(',') + '}';
  requestHeader['X-Authorization'] = r.Authorization(authStr);

  return requestHeader;
}

const FetchUtil = {
  /**
	 * 转换参数
	 */
  toQueryString(obj){
		//    encodeURIComponent(key)
		return obj ? Object.keys(obj).sort().map((key)=> {
			var val = obj[key];
			if (Array.isArray(val)) {
				return val.sort().map(function (val2) {
					return key + '=' + val2;
				}).join('&');
			}
			return key + '=' + val;
		}).join('&') : '';
	},
  /**
	 * 加密参数
	 *
	 */
	signParam(param) {
		var array = new Array();
		for (var p in param) {
			if (p != "sign") {
				array.push(p);
			}
		}
		var keys = array.sort();
		//console.log("*********sort",array.sort());
		var signString = secret;
		for (var i = 0; i < keys.length; i++) {
			signString += (keys[i] + param[keys[i]]);
		}
		signString += secret;
		param["sign"] = Md5.hex_md5(signString);
		return param;
	},
  /**
   * 请求超时回调
   */
  timeout() {
    // Indicator.close();
    // Toast('请求超时');
  },
  /**
   * 请求前回调
   */
  beforeSend() {
    // Indicator.open();
  },
  /**
   * 请求结束回调
   */
  complete() {
    // Indicator.close();
  },
  /**
	 * GET
	 * 参数 - URL上
	 * 返回 - Json
	 */
	fetchGetJson(url, params, callback, err) {
    this.beforeSend();
    var timer = setTimeout(() => {
      this.timeout();
    }, TIME_OUT * 1000);
		fetch(
			url + '?' + this.toQueryString(params),
			{
				method: 'get',
				headers: {
					'Accept': 'application/json'
				}
			}
		).then((response) => {
      clearTimeout(timer);
      return response;
    }).then((response) => {
        this.complete();
				if (response.ok)
					return response.json();
				else
          err && err(response);
			}
		).then((responseJson) => {
      callback(responseJson);
		}).catch((error) => {
      console.log('request failed ---- ' + error);
    });
	},
  /**
   * 只支持简单数据的提交，暂不支持数据和对象的嵌套
	 * POST
	 * 参数 - FormData
	 * 返回 - Json
	 */
	fetchFormPostJson(url, params, callback, err) {
    this.beforeSend();
    var timer = setTimeout(() => {
      this.timeout();
    }, TIME_OUT * 1000);
		fetch(
      url,
      {
        method: 'POST',
        headers: {
        },
        body: this.toQueryString(params)
      }
		).then((response) => {
      clearTimeout(timer);
      this.complete();
      return response;
    }).then((response) => {
				if (response.ok)
					return response.json();
				else
          err && err(response);
			}
		).then((responseJson) => {
      callback(responseJson);
		}).catch((error) => {
      console.log('request failed ---- ' + error);
    });
	},
  /**
   * 主要使用这种方式提交数据
	 * POST
	 * 参数 - Json
	 * 返回 - Json
	 */
	fetchJsonPostJson(url, params, callback, err) {
    this.beforeSend();
    var timer = setTimeout(() => {
      this.timeout();
    }, TIME_OUT * 1000);
    let requestHeader = getRequestHeader();

    /**
     * 奇偶+掩值验签
     */
    params = params || 'N/A';
    let data = params === 'N/A' ? params : JSON.stringify(params);
    let time = new Date().getTime();
    let keyt = time % 2 === 0
      ? requestHeader['X-Vnum'] + '￥' + data + '￥' + requestHeader['X-Udid']
      : requestHeader['X-Udid'] + '￥' + data + '￥' + requestHeader['X-Vnum'];
    let pa = {
      time: time,
      keyt: Md5.hex_md5(keyt).toUpperCase(),
      data: data
    };

    // console.log(params);

		fetch(
      url,
      {
        method: 'POST',
        headers: {
          ...requestHeader
        },
        body: JSON.stringify(pa)
      }
		).then((response) => {
      clearTimeout(timer);
      this.complete();
      return response;
    }).then((response) => {
				if (response.ok)
					return response.json();
				else
          err && err(response);
			}
		).then((responseJson) => {
		    if (responseJson.result) {
          callback(responseJson);
        } else {
          window.location = "/#/login";
        }
		}).catch((error) => {
      console.log('request failed ---- ' + error);
    });
	}
};

export default FetchUtil;
