/**
 * @Description: 检测是否为数字
 * @author cr
 * @date 2020/4/18
 * @time 12:01
 */
function isNumber(val: any): boolean {
  const regPos = /^\d+(\.\d+)?$/; //非负浮点数
  const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  return regPos.test(val) || regNeg.test(val);
}

/**
 * @Description: 精度
 * @author cr
 * @date 2020/4/18
 * @time 12:03
 */
function prefixZero(value: number, num: number): string {
  let a, i;
  a = value.toString();
  const b = a.indexOf(".");
  const c = a.length;
  if (num === 0) {
    if (b !== -1) {
      a = a.substring(0, b);
    }
  } else {
    /*如果没有小数点*/
    if (b === -1) {
      a = a + ".";
      for (i = 1; i <= num; i++) {
        a = a + "0";
      }
    } else {
      /*有小数点,超出位数自动截取,否则补0*/
      a = a.substring(0, b + num + 1);
      for (i = c; i <= b + num; i++) {
        a = a + "0";
      }
    }
  }
  return a;
}

/**
 * @Description: 四舍五入
 * @author cr
 * @date 2020/4/18
 * @time 12:02
 */
function roundFixed(num: any, fixed: number): string {
  const pos = num.toString().indexOf(".");
  const decimalPlaces = num.toString().length - pos - 1;
  const _int = num * Math.pow(10, decimalPlaces);
  const divisorOne = Math.pow(10, decimalPlaces - fixed);
  const divisorTwo = Math.pow(10, fixed);
  const value = Math.round(_int / divisorOne) / divisorTwo;
  return prefixZero(value, fixed);
}

/**
 * @Description: 保留小数位数
 * @author cr
 * @date 2020/4/18
 * @time 12:01
 */
function toDecimal(value: any, decimal: number): string {
  if (isNumber(value)) {
    if (isNumber(decimal)) {
      return roundFixed(value, decimal);
    } else {
      return value;
    }
  }
  return "";
}

/**
 * @Description: 加千分位
 * @author cr
 * @date 2020/4/18
 * @time 12:12
 */
function executeLcommafy(val: string) {
  if (!val || !isNumber(val)) {
    return "";
  }
  if (isNumber(val)) {
    val = val.toString();
  }
  if (/^.*\..*$/.test(val)) {
    const pointIndex = val.lastIndexOf(".");
    let intPart = val.substring(0, pointIndex);
    const pointPart = val.substring(pointIndex + 1, val.length);
    intPart = intPart + "";
    const re = /(-?\d+)(\d{3})/;
    while (re.test(intPart)) {
      intPart = intPart.replace(re, "$1,$2");
    }
    val = intPart + "." + pointPart;
  } else {
    const re = /(-?\d+)(\d{3})/;
    while (re.test(val)) {
      val = val.replace(re, "$1,$2");
    }
  }
  return val;
}

/**
 * @Description: 千分位转换
 * @author cr
 * @date 2020/4/18
 * @time 12:05
 */
function encode(value: any, decimal: number) {
  let number = toDecimal(value, decimal);
  number = executeLcommafy(number);
  if (value === "" || (value == null && value !== 0)) {
    return "";
  }
  return number;
}

const thousandBitConvert = (value: any, decimal: number) => {
  return encode(value, decimal);
};

export default thousandBitConvert;