util.js 5.29 KB
import md5 from 'md5'
import sha1 from 'sha1'
import qs from 'qs'
import Http from './http'
export const Util = {
  /**
   * 校验手机号码格式
   */
  checkPhone: function (mobile) {
    let myreg = /^(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9]|14[0-9])[0-9]{8}$/
    return myreg.test(mobile)
  },

  /**
   * 校验固定电话
   */
  validationTel: function (tel) {
    let reg = /^0[\d]{2,3}-[\d]{7,8}$/
    return reg.test(tel)
  },

  /**
   * 是否特殊字符
   */
  isSpecialLetter: function (str) {
    let reg = new RegExp("[`~!@#$^&*=|{}':;',\\[\\]<>?~!@#¥……&*——|{}【】‘;:”“'。,、? ]")
    return reg.test(str)
  },

  /**
   * 获取浏览器参数
   */
  getUrlParams: function (name) {
    let vars = [],
      hash
    let oParams = {}
    let hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')
    for (let i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=')
      vars.push(hash[0])
      oParams[hash[0]] = hash[1]
    }
    console.log(vars)
    if (name) {
      return oParams[name]
    } else {
      return oParams
    }
  },

  /**
   * 字段截取
   */
  cutStr: function (str, num) {
    if (!str) {
      return ''
    }

    let m = 10
    let n = str
    if (num) {
      m = num
    }
    if (str.length > m) {
      n = str.slice(0, m) + '...'
    }

    return n
  },

  /**
   * 深克隆 所有原型链上的对象和属性
   * 例: const bar=deepClone(foo)
   * console.log(bar===foo) false
   * @param {*} obj
   */
  deepClone: function (obj) {
    // Handle the 3 simple types, and null or undefined or function
    if (obj == null || typeof obj !== 'object') return obj
    // Handle Date
    if (obj instanceof Date) {
      const copy = new Date()
      copy.setTime(obj.getTime())
      return copy
    }
    // Handle Array or Object
    if ((obj instanceof Array) | (obj instanceof Object)) {
      const copy = obj instanceof Array ? [] : {}
      for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) {
          copy[attr] = Util.deepClone(obj[attr])
        }
      }
      return copy
    }
    throw new Error("Unable to clone obj! Its type isn't supported.")
  },

  genUrlParams: function (param, key, encode) {
    // if (!param || layui.$.isEmptyObject(param)) return ''
    var params = []
    var t = typeof param
    if (t == 'string' || t == 'number' || t == 'boolean') {
      params.push(key + '=' + (encode == null || encode ? encodeURIComponent(param) : param))
    } else {
      for (var i in param) {
        var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
        params.push(Util.genUrlParams(param[i], k, encode))
      }
    }
    return params.join('&')
  },

  isEmptyObject: function (obj) {
    return !obj || JSON.stringify(obj) == '{}'
  },

  debounce: function (fn, timer) {
    var t = null
    return function () {
      if (t) {
        clearTimeout(t)
      }
      if (t == null) {
        fn.apply(this, arguments)
      }
      t = setTimeout(() => {
        t = null
      }, timer)
    }
  },

  throttle: function (fn, delay) {
    var t = null
    var begin = 0
    return function () {
      var cur = new Date().getTime()
      if (t) {
        clearTimeout(t)
      }
      if (cur - begin > delay) {
        fn.apply(this, arguments)
        begin = cur
      } else {
        t = setTimeout(() => {
          fn.apply(this, arguments)
        }, delay)
      }
    }
  },

  // 创建签名
  createSign: function (params, secret, noSignAttr = [], way = 'sha1') {
    delete params.sign
    params.timestamp = new Date().getTime()
    var strQs = qs.stringify(params, { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true })
    const objQs = strQs.split('&')
    const collect = objQs.reduce((collect, item) => {
      const [key, value] = item.split('=')
      if (value === null) {
        value = ''
      } else if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      collect[key] = decodeURIComponent(value)
      return collect
    }, {})
    const keys = Object.keys(collect).sort()
    const str = keys.reduce((col, key) => {
      if (!noSignAttr.includes(key)) {
        col.push(key, collect[key])
      }
      return col
    }, [])
    collect.sign = { sha1, md5 }[way](secret + str.join('') + secret).toUpperCase()
    return collect
  },
  // 转为formData数据
  appendFormData: function (obj) {
    delete obj.sessionId
    const formData = new FormData()
    for (let k in obj) {
      if (obj.hasOwnProperty(k)) {
        formData.append(k, obj[k])
      }
    }
    return formData
  },
  getConfig({ moduleName, mockUrl, env = '', httpOptions = {} }) {
    if (!mockUrl) {
      throw new Error('mockUrl应为必填')
    }
    let url = ''
    if (env == 'test') {
      url = 'https://config-center-backend.test.glsx.com.cn/glsxAdmin/config?moduleUrl='
    } else {
      url = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl='
    }
    const http = new Http(httpOptions)
    return http
      .get(`${url}${moduleName}`)
      .then(res => {
        if (res.code == '-1') {
          throw new Error()
        }
        return res.data ? res.data : res
      })
      .catch(err => {
        return http.get(mockUrl)
      })
  }
}
export const createSign = Util.createSign
export default Util