import { Decimal } from "decimal.js";

/**
 * [pageTitle 页面标题]
 * @param  {[type]} title [标题]
 * @return {[type]}       [返回新标题]
 */
export function pageTitle(title) {
  title = title ? title + "- 基础后台管理系统" : "基础后台管理系统";
  window.document.title = title;
}

/**
 * [pageRedirect 页面重定向]
 * @return {[type]} [返回对应的路由]
 */
export function pageRedirect(page = "/") {
  const redirect = vm.$route.query.redirect;
  if (redirect) {
    vm.$router.push(decodeURIComponent(redirect));
  } else {
    vm.$router.replace(page);
  }
}

/**
 * [getByteLength 使用字符unicode判断，获取字符字节长度]
 * @param  {[type]} char [字符]
 * @return {[type]}      [description]
 */
export function getByteLength(char) {
  char = char.trim();
  let char_len = 0;
  for (let i = 0, len = char.length; i < len; i++) {
    let code = char[i].charCodeAt();
    if (code >= 0 && code <= 128) {
      char_len += 1;
    } else {
      char_len += 2;
    }
  }
  return char_len;
}

/**
 * [exportTable 导出excel表格]
 * @param  {[arry]} tableData [excel表格数据]
 * @param  {[type]} fileName  [excel文件名称]
 * @return {[type]}           [description]
 */
export function exportTable(tableData, fileName) {
  // [['标题1','标题2'],['数据1','数据2']]
  if (Object.prototype.toString.call(tableData) == "[object Array]") {
    let csvContent = "data:text/csv;charset=utf-8,";
    tableData.forEach((arry, index) => {
      let row = arry.join(",");
      csvContent += row + "\r\n";
    });
    let encodedUri = encodeURI(csvContent);
    let link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", fileName + ".csv");
    document.body.appendChild(link); // Required for FF
    link.click();
    document.body.removeChild(link);
  } else {
    console.log("表格数据类型错误");
  }
}

/**
 * [getObjectURL 把文件转换成可读URL]
 * @param  {[type]} file [description]
 * @return {[type]}      [description]
 */
export function getObjectURL(file) {
  let url = null;
  if (file) {
    if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file);
    }
  }
  return url;
}

/**
 * [download 资源文件下载]
 * @param  {[type]} url      [文件地址]
 * @param  {[type]} filename [文件名]
 * @return {[type]}          [description]
 */
export function downloadFile(url, filename) {
  let a = document.createElement("a");
  let xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function() {
    if (this.status == 200) {
      let blob = this.response;
      // for IE
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        // for Non-IE (chrome, firefox etc.)
        a.href = window.URL.createObjectURL(blob);
        a.download = filename;
        document.body.appendChild(a); // Required for FF
        a.click();
        window.URL.revokeObjectURL(a.href);
        document.body.removeChild(a);
      }
    }
  };
  xhr.send();
}

/**
 * [objectDot 对象平铺]
 * @param  {[type]} object [对象]
 * @return {[type]}       [一维对象]
 */
export function objectDot(object, prepend = "") {
  let results = {};

  for (let k in object) {
    if (typeof object[k] == "object" && Object.keys(object[k]).length) {
      results = Object.assign(results, objectDot(object[k], prepend + k + "."));
    } else {
      if (object[k] || object[k] === 0) {
        results[prepend + k] = object[k];
      }
    }
  }

  return results;
}

/**
 * 合计数组对象
 * @param {Array}} array
 * @param {String} key
 */
export function sumBy(array, key) {
  return array.reduce((acc, cur) => {
    return add(acc, Number(cur[key]));
  }, 0);
}

/**
 * 精确加法
 * @param {Number} num1
 * @param {Number} num2
 */
export function add(num1, num2) {
  num1 = new Decimal(num1);
  num2 = new Decimal(num2);
  return num1.add(num2).toFixed(2);
}
