import StrKit from '@/utils/str-kit'

const strFilter = {
  /**
   * 功能描述：剪切字符串过滤器
   * 使用方式：
   * {{item.deviceName | cutStr(14)}}
   * @param value
   * @param len
   * @param placeholder
   * @returns {*}
   */
  cutStr (value, len, placeholder) {
    if (!value) {
      return ''
    }
    len = len || 18
    placeholder = placeholder || '...'

    let count = 0
    const titleLenOld = StrKit.getByteLen(value)
    let titleLenNew = 0 // 初始化重新构造的title的长度

    for (var i = 0; i < value.length; i++) {
      if (titleLenNew < len) {
        ++count
        if (value[i].match(/[^x00-xff]/ig) !== null) { // 全角
          titleLenNew += 2
        } else {
          titleLenNew += 1
        }
      } else {
        break
      }
    }
    value = value.substring(0, count) + (titleLenOld <= len ? '' : placeholder)
    return value
  },

  /**
   * 功能描述：格式化手机号码
   * 使用方式：
   * {{item.deviceName | fmtPhoneNumber}}
   * @param val
   * @returns {string|string | *}
   */
  fmtPhoneNumber (val) {
    if (!val) {
      return ''
    }

    val = val.replace(/[^\d]/g, '').substr(0, 11)
    if (val.length <= 3) {
      return val
    } else if (val.length <= 7) {
      val = val.replace(/(\d{3})(\d{0,4})/, '$1-$2')
    } else {
      val = val.replace(/(\d{3})(\d{0,4})(\d{0,4})/, '$1-$2-$3')
    }

    return val
  },

  // 全局安装器
  install (Vue) {
    Vue.filter('cutStr', this.cutStr)
    Vue.filter('fmtPhoneNumber', this.fmtPhoneNumber)
  }
}

export default strFilter
