/*
 * @Description: 工具函数
 */

/*
 * @description 获取地址栏hash参数
 */
export const getUrlHash = paramName => {
  const urlParams = {};
  const url = window.location.href;
  const idx = url.indexOf("#");
  if (idx === -1) {
    return false;
  }
  let params = url.substring(url.indexOf("#") + 1);
  params = params.split("&");
  params.forEach(item => {
    const param = item.split("=");
    urlParams[param[0]] = decodeURIComponent(param[1]);
  });
  if (paramName) {
    return urlParams[paramName];
  }
  return urlParams;
};

/**
 * 倒计时
 * @param {String} target 目标时间
 */
export const countDown = target => {
  const oDate = new Date(); // 获取日期对象
  const oldTime = oDate.getTime(); // 现在距离1970年的毫秒数
  const newDate = new Date(
    isIE() && String(target).match("-") ? target.replace("-", "/") : target
  );
  const newTime = newDate.getTime(); // 2019年距离1970年的毫秒数
  if (newTime >= oldTime) {
    let second = Math.floor((newTime - oldTime) / 1000); // 未来时间距离现在的秒数
    const day = Math.floor(second / 86400); // 整数部分代表的是天；一天有24*60*60=86400秒 ；
    second %= 86400; // 余数代表剩下的秒数；
    const hour = Math.floor(second / 3600); // 整数部分代表小时；
    second %= 3600; // 余数代表 剩下的秒数；
    const minute = Math.floor(second / 60);
    second %= 60;
    return {
      day,
      hour,
      minute,
      second
    };
  }
  return false;
};

/**
 * 文件流导出
 */
export const downloadBlob = (res, filename) => {
  const blob = new Blob([res], {
    type: "application/vnd.ms-excel"
  });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    const oA = document.createElement("a");
    oA.href = URL.createObjectURL(blob);
    oA.download = filename;
    oA.click();
  }
};

// 计算数组对象的总数量和总价格,传列表，num，price可传可不传
export const countNumPrice = (list, num, price) => {
  if (!num) {
    num = "ordCnt";
  }
  if (!price) {
    price = "purcAmt";
  }
  var amount = { num: 0, price: 0 };
  list.forEach(item => {
    if (item[num]) {
      amount.num += parseFloat(item[num]);
    }
    if (item[price]) {
      amount.price += parseFloat(item[price]);
    }
  });
  amount.price = amount.price.toFixed(2);

  return amount;
};

// 计算采购金额=数量*单价，传数量和单价
export const getTotalAmount = (num, price) => {
  if (num && price) {
    let prices = 0;
    prices += parseFloat(num) * parseFloat(price);
    prices = prices.toFixed(2);
    return prices;
  } else {
    return "";
  }
};
// 获取截止日期前三个月的日期
export const getThreeMonthAgoDate = deadline => {
  const year = deadline.getFullYear();
  const month = deadline.getMonth() + 1;
  const day = deadline.getDate();
  const days =
    parseInt(month) < 3
      ? new Date(year - 1, month + 12 - 3, 0)
      : new Date(year, month - 3, 0);
  const maxDays = days.getDate(); //对应的三个月前的month，这个月的最大天数
  const yearAgo = parseInt(month) < 3 ? year - 1 : year;
  const monthAgo = parseInt(month) < 3 ? month + 9 : month - 3;
  const dayAgo = parseInt(maxDays) < parseInt(day) ? maxDays : day;
  const threeMonthsAgoDate = yearAgo + "-" + monthAgo + "-" + dayAgo;
  return threeMonthsAgoDate;
};
//表单验证错误直接滚动到错误位置
export const moveToError = () => {
  let isError = document.getElementsByClassName("is-error");
  if (isError.length) {
    isError[0].scrollIntoView({
      block: "center",
      behavior: "smooth"
    });
  }
};
//汉字转中文
export const numberToChineseAmount = money => {
  var cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  // 基本单位
  var cnIntRadice = ["", "拾", "佰", "仟"];
  // 对应整数部分扩展单位
  var cnIntUnits = ["", "万", "亿", "兆"];
  // 对应小数部分单位
  var cnDecUnits = ["角", "分", "毫", "厘"];
  // 整数金额时后面跟的字符
  var cnInteger = "整";
  // 整型完以后的单位
  var cnIntLast = "元";
  // 最大处理的数字
  var maxNum = 999999999999999.9999;
  // 金额整数部分
  var integerNum;
  // 金额小数部分
  var decimalNum;
  // 输出的中文金额字符串
  var chineseStr = "";
  // 分离金额后用的数组，预定义
  var parts;
  if (money == "") {
    return "";
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    // 超出最大处理数字
    return "";
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  // 转换为字符串
  money = money.toString();
  if (money.indexOf(".") == -1) {
    integerNum = money;
    decimalNum = "";
  } else {
    parts = money.split(".");
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        // 归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  // 小数部分
  if (decimalNum != "") {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == "") {
    chineseStr += cnInteger;
  }
  return chineseStr;
};
