util.js 8.23 KB
// import Vue from 'vue'
import { Message, MessageBox, Loading } from 'element-ui'
// import moment from 'moment'
import dayjs from 'dayjs'
let loadingInstance = ''

export const Util = {
  /**
   * 简单alert
   * title 标题
   * message 内容
   * className 自定义class
   * showCancelButton 是否展示取消按钮
   * confirmButtonText 确认按钮文案
   * cancelButtonText 取消按钮文案
   * confirmButtonColor 确认按钮颜色
   * cancelButtonColor 取消按钮颜色
   */
  msg: function(options) {
    MessageBox({
      title: options.title || '',
      type: options.type || 'error',
      message: options.message || '',
      className: options.className || '',
      showCancelButton: options.showCancelButton || false,
      confirmButtonText: options.confirmButtonText || '确认',
      cancelButtonText: options.cancelButtonText || '取消',
      confirmButtonColor: options.confirmButtonColor || '#1989fa',
      cancelButtonColor: options.cancelButtonColor || '#000',
      dangerouslyUseHTMLString: true,
      callback: function(action, done) {
        if (action == 'confirm') {
          if (options.success) {
            options.success(done)
          }
        } else {
          console.log(done)
          // done()
        }
      }
    })

    /* Vue.$vux.alert.show({
        title: options.title||'',
        content: options.message||'',
        onShow() {
          options.onShow?(options.onShow)():'';
        },
        onHide() {
          options.onHide?(options.onHide)():'';
        }
      }) */
  },

  /**
   * 提示框
   */
  Info: function(options) {
    Message({
      message: options.message || '提示',
      type: options.type || 'error',
      duration: options.time || 2000,
      onClose: options.onClose || ''
    })
  },

  /**
   * 轻提示
   */
  Tips: function(options) {
    Message({
      message: options.message || '提示',
      duration: options.duration || 3000,
      type: options.type || 'text',
      icon: options.icon || ''
    })
  },

  /**
   * loading
   */
  loading: function(message) {
    loadingInstance = Loading.service({
      text: message || '加载中...'
    })
  },

  /**
   * 关闭loading
   */
  closeLoading: function() {
    loadingInstance.close()
  },

  /**
   * 校验手机号码格式
   */
  checkPhone: function(mobile) {
    const 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) {
    const reg = /^0[\d]{2,3}-[\d]{7,8}$/
    return reg.test(tel)
  },

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

  /**
   * 只能输入英文字母和数字,不能输入中文
   */
  validationInput: function(str) {
    const reg = /[^\w\.\/]/gi // eslint-disable-line
    return reg.test(str)
  },

  /**
   * 获取当前时间
   */
  getCurrentDate: function() {
    const time = new Date()
    const y = time.getFullYear()
    const m = time.getMonth() + 1
    const d = time.getDate()

    return {
      date: y + '/' + m + '/' + d
    }
  },

  /**
   * 获取浏览器参数
   */
  getUrlParams: function(name) {
    const vars = []
    let hash
    const oParams = {}
    const 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
    }
  },

  /**
   * 根据当前时间,计算往后30天的日期
   */
  getAfterDate: function(day) {
    const date1 = new Date()
    const date2 = new Date(date1)
    let time = 30
    if (day) {
      time = day
    }
    date2.setDate(date1.getDate() + time)

    const _date = date2.getFullYear() + '-' + (date2.getMonth() + 1) + '-' + date2.getDate()

    return {
      date: _date,
      year: date2.getFullYear(),
      month: date2.getMonth() + 1,
      day: date2.getDate()
    }
  },

  /**
   * 日期格式转换
   */
  dateFormate: function(str, type) {
    let txt = 'YYYY-MM-DD'
    if (type) {
      txt = type
    }
    const m = dayjs(str).format(txt)
    return m
  },

  /**
   * 字段截取
   */
  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) {
  //   const clone = require('rfdc')({ proto: false, circles: false })
  //   return clone(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 (Object.prototype.hasOwnProperty.call(attr)) {
  //       if (obj.hasOwnProperty(attr)) {
  //         copy[attr] = Util.deepClone(obj[attr])
  //         // console.log("copy[attr] ", copy[attr])
  //       }
  //     }
  //     return copy
  //   }
  //   throw new Error("Unable to clone obj! Its type isn't supported.")
  // },

  // /**
  //  * url下载文件
  //  *
  //  */
  // downLoadFile: function(url) {
  //   // console.log(row)
  //   // return
  //   const Temp = document.createElement('a')
  //   // Temp.href = process.env.VUE_APP_BASE_URL + '/article/export.do?articleId=' + row.id
  //   Temp.href = url + '?timestamp=' + new Date().getTime()
  //   // console.log(url)
  //   // console.log(Temp.href)
  //   document.body.append(Temp)
  //   Temp.click()
  //   document.body.removeChild(Temp)
  // },

  /**
   * @param {Object} json
   * @param {Object} type: 默认不传 ==>全部小写;传1 ==>全部大写;传2 ==>首字母大写
   * 将json的key值进行大小写转换
   */
  jsonKeysToCase: function(json, type) {
    if (typeof json == 'object') {
      var tempJson = JSON.parse(JSON.stringify(json))
      toCase(tempJson)
      return tempJson
    } else {
      return json
    }

    function toCase(json) {
      if (typeof json == 'object') {
        if (Array.isArray(json)) {
          json.forEach(function(item) {
            toCase(item)
          })
        } else {
          for (var key in json) {
            var item = json[key]
            if (typeof item == 'object') {
              toCase(item)
            }
            delete json[key]
            switch (type) {
              case 1:
                // key值全部大写
                json[key.toLocaleUpperCase()] = item
                break
              case 2:
                // key值首字母大写,其余小写
                json[key.substring(0, 1).toLocaleUpperCase() + key.substring(1).toLocaleLowerCase()] = item
                break
              default:
                // 默认key值全部小写
                json[key.toLocaleLowerCase()] = item
                break
            }
          }
        }
      }
    }
  },

  // 判断字段为空时显示
  fieldShow: function(field, show) {
    return field || show
  },
  // 整数补零显示两位小数
  returnFloat: function(num) {
    num = num.toString()
    if (num.indexOf('.') != -1) {
      let newVal = num.split('.')
      if (newVal[1].length == 1) {
        newVal = newVal.join('.')
        newVal += '0'
        num = newVal
      }
    } else {
      num += '.00'
    }
    return num
  }
}

export const showModal = Util.msg
export const showToast = Util.Info
export const showLoading = Util.loading
export const hideLoading = Util.closeLoading
export const deepClone = Util.deepClone
// export const downLoadFile = Util.downLoadFile
export const returnFloat = Util.returnFloat