/*
 * @Author: zhujian 
 * @Date: 2017-08-31 11:05:12 
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-07-16 11:33:21
 *公共方法
 */

window.utils = {
  isValidURL(url) {
    if (!url) {
      return false;
    }
    if (url.indexOf('http') !== -1) {
      return true;
    }
    return false;
  },
  // 只截取两位数，多余的去掉，不足的补0
  _fillTwo(str) {
    const temArr = str.split("");
    const newArr = [];

    for (let i = 0; i < 2; i++) {
      if (temArr[i]) {
        newArr.push(temArr[i]);
      } else {
        newArr.push(0);
      }
    }

    return newArr.join("");
  },
  limitFloatTwo(val, digit = 99) {
    if (val === "") {
      return "";
    } else {
      const regExp = new RegExp("(\\d+)\\.(\\d+)?$");
      const result = regExp.exec(val);
      let inter = ""; // 整数部分
      let decimal = ""; // 小数部分

      if (result) {
        inter = result[1];
        decimal = this._fillTwo(result[2] || '');
        return `${inter.substr(0, digit)}.${decimal}`;
      }
      return val
    }
  },
  filterNumber(value) {
    let _value;

    if (value != '' && value.substr(0, 1) === '.') {
      return "";
    }
    _value = value.replace(/^0*(0\.|[1-9])/, '$1'); //解决 粘贴不生效
    _value = _value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    _value = _value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的

    return _value;
  },
  // 限制7位整数和两位小数
  limitNum(value) {
    let _value = this.filterNumber(value);

    _value = _value.replace(/(\d+)(\.\d*)?/, function ($1, $2, $3) {
      if ($3) {
        return $2.substr(0, 7) + $3.substr(0, 3);
      }
      return $2.substr(0, 7);
    });
    return _value;
  },
  /**
   * 限制位数可配置, 比如限制n位整数和m位小数
   * @param {*} 需要限制的数值 
   * @param {*} 需要限制的整数位数 
   * @param {*} 需要限制的小数位数 
   */
  setLimitNum(value, digit, decimal) {
    let _value = this.filterNumber(value);

    _value = _value.replace(/(\d+)(\.\d*)?/, function ($1, $2, $3) {
      if ($3) {
        return `${$2.substr(0, digit)}${$3.substr(0, decimal + 1)}`;
      }
      return $2.substr(0, digit);
    });
    return _value;
  },
  getNumRange(value, min, max) {
    let _value = this.setLimitNum(value, 8, 2);

    if (_value < min) {
      return min;
    } else if (_value > max) {
      return max;
    }
    return getNumberFormat(_value);
  },
  // 数组去重
  unique(arr, u_key) {
    let map = new Map();

    arr.forEach((item) => {
      if (!map.has(item[u_key])) {
        map.set(item[u_key], item)
      }
    });
    return [...map.values()];
  },
  formatString(str, n) {
    const string = str || '';
    const numberList = string.replace(/./g, (item) => {
      if (item.match(/[^\x00 -\xff]/)) {
        return '2';
      } else {
        return '1';
      }
    });
    let number = 0;
    for (let i = 0; i < string.length; i++) {
      number += parseInt(numberList[i], 10);
      if (number >= n * 2) {
        return string.substring(0, i + 1).trim() + '…'
      }
    }
    return str;
  },
  removeSpecialCharacter(str) {
    return (str || '').replace(/[^\u4e00-\u9fa5a-zA-Z0-9_\-—~\(\)\[\]\{\}+（）【】「」《》，。,\.\*%#@\&:：""''“”‘’\/ ]/g, '');
  }
};

const isUndefined = (value) => {
  return value === void 0 || value === null;
}

const randomString = (len = 32) => {
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  const maxPos = chars.length;
  let pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

// 限制字数
const getEllipsText = (text, limitNum) => {
  const limitText = text.replace(/\n/g, ' ');

  if (limitText.length > limitNum) {
    return `${limitText.substr(0, limitNum)}...`;
  }
  return limitText;
}
const shareTemplate = (str, place) => {
  return str.replace(/\{\$(.*?)\}/g, (full, key) => {
    return place[key] || full
  })
}

const transformPhoneNumer = (phoneNum, hasPermission) => {
  if (!phoneNum) return phoneNum;
  if (hasPermission) return phoneNum;
  const newPhoneArr = String(phoneNum).split('');
  newPhoneArr.splice(3, 4, '****');
  return newPhoneArr.join('');
}
export {
  randomString,
  isUndefined,
  getEllipsText,
  shareTemplate,
  transformPhoneNumer
}