/**
 * 获取Url中的参数
 */
const getParamFormUrl = (key, host) => {
  let arr;
  let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
  try {
    let testHost = window.location.href;
    if (host) {
      testHost = host;
    }
    if ((arr = testHost.split('?')[1].match(reg))) {
      return decodeURI(arr[2]);
    }
  } catch (e) {
  }
  return '';
};

/**
 * 判断是否开始
 * @param value
 * @param start
 */
const startWidth = (value, start = '') => {
  return initValue(value, '').substr(0, start.length) === start;
};

/**
 * 是否为空
 * @param value
 * @returns {boolean}
 */
const isEmpty = (value) => {
  return value == undefined || value == null || value == '';
};

/**
 * 设置默认值
 * @param value
 * @param def
 */
const initValue = (value, def) => {
  return isEmpty(value) ? def : value;
};

/**
 * 转换为json
 * @param value
 * @param def = {}
 */
const parseJSON = (value, def) => {
  let obj;
  try {
    obj = JSON.parse(value);
  } catch (e) {
  }
  if (!obj) {
    obj = def;
  }
  return obj;
};


/**
 * 将array中的某个key用sep连接起来
 * @param array
 * @param key
 * @param sep
 */
const arrayKeys = (array = [], key = 'id', sep = ',') => {
  let result = '';
  array.forEach(item => {
    if (typeof item == 'object') {
      result = result + item[key];
    } else {
      result = result + item;
    }
    result = result + sep;
  });
  result = result.substring(0, result.length - sep.length);
  return result;
};

/**
 * 分割对象
 * @param obj
 * @param sep
 */
const splitObj = (obj, sep = ',') => {
  if (obj) {
    return obj.split(sep);
  }
  return [];
};


/**
 * 字符串长度
 * @param val
 * @returns {number}
 */
const length = (val = '') => {
  return isEmpty(val) ? 0 : val.length;
};


const arraySet = (array = [], key) => {
  let obj = {};
  array.forEach(item => {
    obj[item[key]] = item;
  });
  return Object.keys(obj).map(k => (obj[k]));
};

/**
 * 上传图片
 */
const uploadFile = (file) => {
  return new Promise((resolve, reject) => {
    let fileData = new FormData();
    fileData.append('file', file);
    let request = new XMLHttpRequest();
    request.open("POST", "/tools/file/whole_upload");
    request.onreadystatechange = ev => {
      if (ev.currentTarget.readyState === 4) {
        let res = JSON.parse(ev.currentTarget.responseText);
        resolve(res);
      }
    };
    request.send(fileData);
  });
};

export default {
  getParamFormUrl, isEmpty, initValue, startWidth, arraySet,
  parseJSON, arrayKeys, splitObj, length, uploadFile
}


