import router from '../router';

let _isDev = process.env.NODE_ENV === "development"; // eslint-disable-line

// 防抖
export const _debounce = (fn, delay) => {
  let _delay = delay || 200;
  let timer;
  return function() {
    let that = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function() {
      timer = null;
      fn.apply(that, args);
    }, _delay);
  };
};
// 节流
export const _throttle = (fn, delay) => {
  let timer = null;
  let remaining = 0; // eslint-disable-line
  let previous = new Date(); // eslint-disable-line

  return function() {
    const now = new Date();
    const remaining = now - previous;
    const args = arguments;
    const context = this; // eslint-disable-line

    if (remaining >= delay) {
      if (timer) {
        clearTimeout(timer);
      }

      fn.apply(context, args);
      previous = now;
    } else {
      if (!timer) {
        timer = setTimeout(function() {
          fn.apply(context, args);
          previous = new Date();
        }, delay - remaining);
      }
    }
  };
};
/**
 * 开发输出log
 * @param {消息} msg
 */
export const log = msg => {
  if (_isDev && console && console.log) {
    // console.log(msg);
  }
};

/**
 * 补零
 * @param {String/Number} num
 * @return {String/Number}
 */
export const fillZero = num => {
  num = num * 1;
  if (num < 10) {
    return '0' + num;
  } else {
    return num;
  }
};

/**
 * 处理时间
 * @param {Date} date
 * @param {String} type
 * @param {Boolean} newline
 * @return {string}
 */
export const formatDateTimeByType = (
  date,
  type = 'yyyy-MM-dd-HH-mm-ss',
  newline = false
) => {
  if (!date) {
    return newline ? { y: '', h: '' } : '';
  }
  if (typeof date === 'number' || typeof date === 'string') {
    date = new Date(date);
  }
  try {
    if (typeof date === 'string') {
      return newline ? { y: date, h: '' } : date;
    } else {
      let year = type.indexOf('yyyy') >= 0 ? fillZero(date.getFullYear()) : '';
      let month =
        type.indexOf('MM') >= 0 ? '-' + fillZero(date.getMonth() + 1) : '';
      let day =
        type.indexOf('dd') >= 0 ? '-' + fillZero(date.getDate()) + '' : '';
      let hours =
        type.indexOf('HH') >= 0 ? ' ' + fillZero(date.getHours()) : '';
      let min =
        type.indexOf('mm') >= 0 ? ':' + fillZero(date.getMinutes()) : '';
      let sec =
        type.indexOf('ss') >= 0 ? ':' + fillZero(date.getSeconds()) : '';
      if (newline) {
        return { y: year + month + day, h: hours + min + sec };
      }
      return year + month + day + hours + min + sec;
    }
  } catch (e) {
    return newline ? { y: date, h: '' } : date;
  }
};

/**
 * 处理为带小数点的数值格式
 * @param {String/Number} s 传入的金额
 * @param {String/Number} n 保留的小数位
 * @return {String}
 */
export const fmoney = (s, n = 2) => {
  try {
    if (n > 0) {
      s = s.toFixed(n);
    }
  } catch (e) {
    return s;
  }

  let str = s.toString();
  let reg =
    str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
  return str.replace(reg, '$1,');
};

/**
 * 清空对象的所有属性
 * @param {Object} obj 需要清空的对象
 * @return {Object} 返回新的object
 */
export const clearObj = obj => {
  let o = {};
  Object.keys(obj).forEach(v => {
    if (obj.constructor === Array) {
      o[v] = [];
    } else if (typeof obj === 'object') {
      o[v] = {};
    } else {
      o[v] = '';
    }
  });

  return {};
};

/**
 * 输出列表显示时间
 * @param {String时间} time
 * @return {String} 返回html
 */
export const listTime = time => {
  if (!time) {
    return '--';
  }
  return `<p class="cell-time">${ formatDateTimeByType(time, 'yyyy-MM-dd-HH-mm-ss', true).y }</p>
          <p class="cell-time">${ formatDateTimeByType(time, 'yyyy-MM-dd-HH-mm-ss', true).h }</p>
          `;
};

/**
 * 强制跳转路由
 * 该方法会给route上加上timeStamp
 */
export const reRreshRoute = () => {
  const _route = router.app._route;
  let rQuery = { ..._route.query };
  delete rQuery.areaId;
  const query = {
    ...rQuery,
    timestamp: new Date().getTime()
  };
  // 清空url中的areaId参数，避免刷新又被反赋值
  router.push({ path: _route.fullPath, query });
  // router.push({ name: 'compile', params: { url: { path: _route.fullPath, query } } });
};

/**
 * 序列化反序列化法 深拷贝对象
 * @param {Object} obj
 * @return {Object} 返回新的Object
 */
export const deepClone = obj => {
  return JSON.parse(JSON.stringify(obj));
};

/**
 * 传入参数 向url后追加 返回新的url
 * @param {string} uri 原始url
 * @param {string} key 追加的key
 * @param {string/Number} value 追加的key的value
 * @return {String} 返回新的url
 */
export const updateQueryStringParameter = (uri, key, value) => {
  if (!value) {
    return uri;
  }
  let re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
  let separator = uri.indexOf('?') !== -1 ? '&' : '?';
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + '=' + value + '$2');
  } else {
    return uri + separator + key + '=' + value;
  }
};

/**
 * 获取url参数
 * @param {string} variable
 * @return {String/Boolean} 返回url query中指定target值（如无返回false)
 */
export const getQueryVariable = variable => {
  const query = window.location.search.substring(1);
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
};

/**
 * base64转blob
 * @param {String} code base64
 * @return {*}
 */
export const base64ToBlob = code => {
  let parts = code.split(';base64,');
  let contentType = parts[0].split(':')[1];
  let raw = window.atob(parts[1]);
  let rawLength = raw.length;

  let uInt8Array = new Uint8Array(rawLength);

  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([ uInt8Array ], { type: contentType });
};

/**
 * 下载文件
 * @param {String} fileName
 * @param {*} content
 */
export const downloadFile = (fileName, content) => {
  let aLink = document.createElement('a');
  let blob = base64ToBlob(content); // new Blob([content]);
  let evt = document.createEvent('HTMLEvents');
  evt.initEvent('click', true, true); // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
  aLink.download = fileName;
  aLink.href = URL.createObjectURL(blob);
  // aLink.dispatchEvent(evt);
  // aLink.click()
  aLink.dispatchEvent(
    new MouseEvent('click', { bubbles: true, cancelable: true, view: window })
  ); // 兼容火狐
};

/**
 * 判断传入字符是否为空
 * @param {*} str
 * @return {Boolean}
 */
export const isEmpty = (str) => {
  return str === '' || str == null;
};

// 交换数组元素
function swapItems(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
}

/**
 * 数组上移
 * @param {Array} arr
 * @param {Number} $index
 */
export const upRecord = function(arr, $index) {
  if ($index == 0) {
    return;
  }
  swapItems(arr, $index, $index - 1);
};

/**
 * 数组下移
 * @param {Array} arr
 * @param {Number} $index
 */
export const downRecord = function(arr, $index) {
  if ($index == arr.length - 1) {
    return;
  }
  swapItems(arr, $index, $index + 1);
};


/**
 * 对简单的数组去重
 * @param {Array} arr
 * @return {Array} 返回去重数组
 */
export const easyUnique = (arr) => {
  let x = new Set(arr);
  return [ ...x ];
};

