/*
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2018-10-10 14:44:45
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-09 15:38:27
 */

export default {
  /**
   * @description: 一个汉字算两个字符, 一个英文字母或数字算一个字符
   * @param {String} val
   * @returns {Number}
   * @author: 无尘
   */
  getByteLen: function(val) {
    let valStr = val == '' || val == null ? '' : val;
    let len = 0;
    for (let i = 0; i < valStr.length; i++) {
      let a = valStr.charAt(i);
      if (a.match(/[^\x00-\xff]/gi) != null) {
        len += 2;
      } else {
        len += 1;
      }
    }
    return len;
  },
  /**
   * @description: 一个汉字算一个字, 一个英文字母或数字算半个字
   * @param {String} val
   * @returns {Number}
   * @author: 无尘
   */
  getZhLen: function(val) {
    let valStr = val == '' || val == null ? '' : val;
    let len = 0;
    for (let i = 0; i < valStr.length; i++) {
      let a = valStr.charAt(i);
      if (a.match(/[^\x00-\xff]/gi) != null) {
        len += 1;
      } else {
        len += 0.5;
      }
    }
    return Math.ceil(len);
  },

  /**
   *
   * @description: 暂无用
   * @param {String} str
   * @param {Number} len
   * @param {Number} type
   * @returns {String}
   * @author: 无尘
   */
  cutStr: function(str, len, type) {
    let charLength = 0;
    for (let i = 0; i < str.length; i++) {
      let sonStr = str.charAt(i);
      if (type == 1) {
        encodeURI(sonStr).length > 2 ? (charLength += 1) : (charLength += 0.5);
      }
      if (type == 2) {
        charLength += 1;
      }
      if (charLength >= len) {
        let subLen = charLength == len ? i + 1 : i;
        return str.substr(0, subLen);
      }
    }
  },

  /**
   * @description: 限制字数用, 一个汉字算一个字, 两个英文 / 字母算一个字
   * @param {String} val
   * @param {Number} max
   * @returns {String}
   * @author: 无尘
   */
  getByteVal: function(val, max) {
    let valStr = val == '' || val == null ? '' : val;
    let returnValue = '';
    let byteValLen = 0;
    for (let i = 0; i < valStr.length; i++) {
      if (valStr[i].match(/[^\x00-\xff]/gi) != null) byteValLen += 1;
      else byteValLen += 0.5;
      if (byteValLen > max) break;
      returnValue += valStr[i];
    }
    return returnValue;
  },

  /**
   * @description: 限制字符数用, 一个汉字算两个字符, 一个英文 / 字母算一个字符
   * @param {String} val
   * @param {Number} max
   * @returns {String}
   * @author: 无尘
   */
  getCharVal: function(val, max) {
    let valStr = val == '' || val == null ? '' : val;
    let returnValue = '';
    let byteValLen = 0;
    for (let i = 0; i < valStr.length; i++) {
      if (valStr[i].match(/[^\x00-\xff]/gi) != null) byteValLen += 2;
      else byteValLen += 1;
      if (byteValLen > max) break;
      returnValue += valStr[i];
    }
    return returnValue;
  },

  /**
   * @description: 正则校验, 校验非负数字
   * @param {String} v
   * @returns {Boolean}
   * @author: 无尘
   */
  regPos: function(v) {
    let regTest = /^\d+(\.\d+)?$/;
    return regTest.test(v);
  }
};
