export const Arithmetic = {
  methods: {
    // 乘法
    accMul(arg1, arg2) {
      var m = 0, s1 = arg1.toString(), s2 = arg2.toString()
      try {
        m += s1.split('.')[1].length
      } catch (e) {
      }
      try {
        m += s2.split('.')[1].length
      } catch (e) {
      }
      return (Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m))
    },
    // 减法
    accSub(arg1, arg2) {
      if (isNaN(arg1)) {
        arg1 = 0
      }
      if (isNaN(arg2)) {
        arg2 = 0
      }
      arg1 = Number(arg1)
      arg2 = Number(arg2)

      var r1, r2, m, n
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2))  //动态控制精度长度
      n = (r1 >= r2) ? r1 : r2
      return ((this.accMul(arg1, m) - this.accMul(arg2, m)) / m)
    },
    // 除法
    accDiv(arg1, arg2) {
      var t1 = 0,
        t2 = 0,
        r1, r2
      try {
        t1 = arg1.toString().split('.')[1].length
      } catch (e) {
      }
      try {
        t2 = arg2.toString().split('.')[1].length
      } catch (e) {
      }
      r1 = Number(arg1.toString().replace('.', ''))
      r2 = Number(arg2.toString().replace('.', ''))
      return (r1 / r2) * Math.pow(10, t2 - t1)
    },
    /**
     * 返回小于等于x的最大整数
     * @param data
     * @returns {number}
     */
    fix(data) {
      return this.accDiv(Math.floor(this.accMul(data,100)), 100)
    },

    /**
     * 返回小于等x的最大整数并且+1
     * @param data
     */
    fix1(data){
      var d;
      try {
        d = data.toString().split(".")[1].length;
      } catch (e) {
        d = 0;
      }
      if(d<=2){
        return this.accDiv(Math.floor(this.accMul(data,100)), 100)
      }
      return this.accDiv(this.numAdd(Math.floor(this.accMul(data,100)),1), 100)
    },
    /**
     * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
     * @param num1
     * @param num2
     * @returns {number}
     */
    numAdd(num1, num2) {
      var baseNum, baseNum1, baseNum2;
      try {
        baseNum1 = num1.toString().split(".")[1].length;
      } catch (e) {
        baseNum1 = 0;
      }
      try {
        baseNum2 = num2.toString().split(".")[1].length;
      } catch (e) {
        baseNum2 = 0;
      }
      baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
      return (this.accMul(num1,baseNum) + this.accMul(num2,baseNum)) / baseNum;
    },
    //金额统计转换成字符串、自动拼接俩位小数
    returnFloat(value){
      var value = Math.round(parseFloat(value)*100)/100;
      var s = value.toString().split(".");
      if(s.length == 1){
        value = value.toString()+".00";
        return value;
      }
      if(s.length > 1){
        if(s[1].length < 2){
          value = value.toString()+"0";
        }
        return value;
      }
    },
  }

}