import { parseTime } from './index'

const vueFilter = {

  // 将数字转换成带千分位数字
  formatNumber: function (num, precision, separator) {
    var parts;
    if (!isNaN(parseFloat(num)) && isFinite(num)) {
      num = Number(num);
      num = (typeof precision !== 'undefined' ? num.toFixed(precision) : num).toString();
      parts = num.split('.');
      parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (separator || ','));
      return parts.join('.');
    }
    return '';
  },

  // 将数字转换成带千分位数字
  yLocalString: function (value) {
    var b = parseInt(value).toString();
    if (b === 'NaN') return 0;
    var len = b.length;
    if (len <= 3) { return b; }
    var r = len % 3;
    return r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(",");
  },

  // 将字符串截短至指定长度，并用在最后追加特定字符串（例如：...）
  shortName: function (value, length, append = '...') {
    if (value && value.length > length) {
      return value.substring(0, length) + append
    } else {
      return value
    }
  },

  // 区分考试和课程
  contentType: function (value) {
    let type = '';
    if(value == 1) {
      type = '考';
    } else if(value == 2) {
      type = '学';
    }
    return type;
  },

  //判断中文字与英文字符占位多少
  strLength(str) {
    let len = 0;
    let arr = str.split("");
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].charCodeAt(0) < 299) {
          len++;
        } else {
          len += 2;
        }
    }
    return len;
  },

  // 格式化日期
  formatTime: function (timeStamp, format = '{yyyy}.{mm}.{dd}') {
    return parseTime(timeStamp, format)
  },

  // 格式化文件大小: B  K  M  G
  formatFileSize: function (limitSize) {
    let size = "", limit = limitSize || 0
    if (limit < 0.1 * 1024) {                            //小于0.1KB，则转化成B
      size = limit.toFixed(2) + "B"
    } else if (limit < 0.1 * 1024 * 1024) {            //小于0.1MB，则转化成KB
      size = (limit / 1024).toFixed(2) + "K"
    } else if (limit < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB
      size = (limit / (1024 * 1024)).toFixed(2) + "M"
    } else {                                            //其他转化成GB
      size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "G"
    }

    var sizeStr = size + "";                        //转成字符串
    var index = sizeStr.indexOf(".");                    //获取小数点处的索引
    var dou = sizeStr.substr(index + 1, 2)            //获取小数点后两位的值
    if (dou == "00") {                                //判断后两位是否为00，如果是则删除00                
      return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
    }
    return size;
  },
  formatMoney(money = 0) {
    if(!money) return 0;
    return (money / 100).toFixed(2);
  }

}

export default vueFilter
