vue 项目工具类

179 阅读4分钟

import lodash from 'lodash'
/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
import moment from 'moment'
export const Debounce = (fn, t) => {
  const delay = t || 500
  let timer
  return function() {
    const args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fn.apply(this, args)
    }, delay)
  }
}
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
  let last
  let timer
  const interval = t || 500
  return function() {
    const args = arguments
    const now = +new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        fn.apply(this, args)
      }, interval)
    } else {
      last = now
      fn.apply(this, args)
    }
  }
}
/**
 * 获取window的参数
 * 使用场景:
 * sso获取带过来的token
 */
export const getUrlParam = name => {
  const url = decodeURIComponent(window.location.href)
  let reg = new RegExp('(^|\\?|&)' + name + '=([^&]*)(\\s|&|$)', 'i')
  if (reg.test(url)) {
    return unescape(RegExp.$2.replace(/\+/g, ' '))
  } else {
    return false
  }
}
/**
 * 深度拷贝
 */
export const DeepCopy = data => {
  return lodash.cloneDeep(data)
}

export const toFixedNum = (d, index = 4) => {
  if (d) {
    return Number(d).toFixed(index)
  }
  return d
}

/**
 * 1=禁用 2=开启 3=草稿
 * 使用场景:列表中将status转换为文字,并带上css圆点
 * @param {*} d
 * @returns
 */
export const convertListStatus = d => {
  if (d * 1 == 1) {
    return ['red', '禁用']
  } else if (d * 1 == 2) {
    return ['green', '启用']
  } else {
    return ['ing', '草稿']
  }
}

/**
 * 对外提供获取name功能
 * @param {*} type
 * @param {*} key
 * @returns
 * eg: 禁用 = getDictName('EnableStatus', '0')
 */

function getDictName(type, key) {
  if (key === '' || typeof key === 'undefined') {
    return ''
  }
  type = type || []
  let obj = type.find(item => item.enum_value == key || item.enum_code === key)

  return (obj && obj.enum_name) || ''
}

function getDictCodeName(type, key) {
  if (key === '' || typeof key === 'undefined') {
    return ''
  }
  type = type || []
  let obj = type.find(item => item.enum_value == key || item.enum_code === key)
  if (obj && obj.enum_name) {
    return `${obj.enum_code}-${obj.enum_name}`
  } else {
    return ''
  }
  // return (obj && obj.enum_name) || ''
}

export const showMulFile = (dict, v, type) => {
  if (type == 'single') {
    return getDictName(dict, v) || ''
  }
  if (Object.prototype.toString.call(v) !== '[object Array]') {
    return ''
  }

  if (!v || !v.length) return ''
  if (v.length == 1 && !v[0]) return ''
  let text = ''
  v.forEach((m, i) => {
    if (!i) {
      text = getDictName(dict, m) || ''
    } else {
      text += `,${getDictName(dict, m) || ''}`
    }
  })
  return text
}

export const showMulFileCode = (dict, v, type) => {
  if (type == 'single') {
    return getDictCodeName(dict, v) || ''
  }

  if (Object.prototype.toString.call(v) !== '[object Array]') {
    return ''
  }

  if (!v || !v.length) return ''
  if (v.length == 1 && !v[0]) return ''
  let text = ''
  v.forEach((m, i) => {
    if (!i) {
      text = getDictCodeName(dict, m) || ''
    } else {
      text += `,${getDictCodeName(dict, m) || ''}`
    }
  })
  return text
}

export const dealDictExtra = dict => {
  let dicts = []
  dicts = dict.filter((v, i) => {
    return Object.assign(v, {
      key: i + 1,
      dataIndex: v.enumCode,
      name: v.enumCode,
      code: v.enumValue,
      label: v.enumName,
      ClaimDataType: v.enumValue,
      fileName: '',
      value: ''
    })
  })
  return dicts
}

/**
 * 1=禁用 2=开启 3=草稿
 * 使用场景:列表中如果是禁用,则显示启用按钮,如果是启用,则显示禁用,草稿忽略
 * @param {*} d
 * @returns
 */
export const convertActionStatus = d => {
  if (d * 1 == 1) {
    return '启用'
  } else if (d * 1 == 2) {
    return '禁用'
  } else {
    return '草稿'
  }
}

export const StatusColor = d => {
  // 状态 0-未启用 1-启用 2-禁用 3-删除
  if (d == '禁用') {
    return 'red'
  } else if (d == '启用') {
    return 'green'
  } else if (d == '草稿' || d == '未启用') {
    return 'ing'
  } else {
    return ''
  }
}

/**
 * 通知状态(0处理中、1成功、2失败)
 * @param {*} d
 */
export const convertRecordStatus = d => {
  let data = ''
  if (typeof d == 'string' && d != -1) {
    data = Number(d)
  } else if (typeof d == 'number' && d != -1) {
    if (d == 0) {
      data = '处理中'
    } else if (d == 1) {
      data = '成功'
    } else {
      data = '失败'
    }
  }
  return data
}

/**
 *
 * @param {*} t 类型  ''
 * @param {*} d  数据
 */
export const ConverStatus = (d, t) => {
  const OK_STATUS = [
    '已处理',
    '成功',
    '解析成功',
    '审核通过',
    '处理完成',
    '已对账',
    '已提交',
    '已发货',
    '预报成功',
    '拆分成功',
    '是',
    '已拆分',
    '确认完成'
  ]
  const ING_STATUS = ['处理中', '拆分中', '待拆分']
  const WAIT_STATUS = [
    '未提交',
    '未处理',
    '待审核',
    '待对账',
    '对账中',
    '待解析',
    '解析中',
    '待拆分',
    '未发货'
  ]
  const NO_STATUS = [
    '禁用',
    '失败',
    '解析失败',
    '审核驳回',
    '对账失败',
    '对账异常',
    '作废',
    '拆分失败',
    '预报失败',
    '否'
  ]
  if (OK_STATUS.includes(d)) {
    return 'green'
  } else if (WAIT_STATUS.includes(d)) {
    return 'ing'
  } else if (ING_STATUS.includes(d)) {
    return 'ing'
  } else if (NO_STATUS.includes(d)) {
    return 'red'
  } else {
    return 'ing'
  }
}

/**
 * 日期转化为yyyy-mm-dd-hh-mm-ss
 * 使用场景:
 * 后端传过来的日期格式需转化为yyyy-mm-dd-hh-mm-ss
 */
export const getDataFormt = d => {
  const data = new Date(d)
    .toISOString()
    .replace(/T/g, ' ')
    .replace(/\.[\d]{3}Z/, '')
  return data
}

/**
 * 表单提交去左右空格
 * @param {*} values
 */
export const valuesTrim = values => {
  Object.keys(values).map(key => {
    if (Object.prototype.toString.call(values[key]) == '[object String]') {
      values[key] = values[key].trim()
    }
  })
}

/**
 * 将textarea控件中的内容,去掉换行,去掉左右空格,去掉空行,去重,得到字符串数组
 * ["  冒烟2-导入解析模板附件 (1)", "", "  string"]
 * @param {*} v
 */
export const textArrayTrim = text => {
  if (text) {
    text = text.split(/[\s\n+,+,+;+;]+/).filter(i => i !== '')
    return [...new Set(text)]
  }
  return []
}
export const textArraybreak = text => {
  if (text) {
    text = text.split(/[\r\n]+/).filter(i => i !== '')
    let arr = []
    text.forEach(v => {
      arr.push(v.replace(/(^\s*)|(\s*$)/g, '')) //replace(/^\s+|\s+$/g, ''))
    })
    return [...new Set(arr)]
  }
  return []
}

export const textArrayTrimAll = text => {
  // 分割字符为数组
  if (text) {
    return (text = text.split(/[\s\n+,+,+;+;]+/).filter(i => i !== ''))
  }
  return ''
}

// 针对string去空格
export const Trim = str => {
  if (!str) return str
  if (typeof str == 'string') {
    return str.replace(/(^\s*)|(\s*$)/g, '')
  } else {
    return str
  }
}

// 保留三位小数
export const returnFloat = (value, number = 3, type) => {
  let str = Object.prototype.toString.call(value)
  if (str !== '[object Number]') return
  let data = value.toString().split('.')
  let zs = null
  let xs = null
  let add = null
  if (data.length === 1) {
    //整数
    zs = data[0]
    if (number === 3) {
      add = '000'
    } else if (number === 2) {
      add = '00'
    } else if (number === 1) {
      add = '0'
    }
  } else {
    //小数
    if (data.length > 1) {
      zs = data[0]
      xs = data[1]
      if (number === 3) {
        if (xs.length === 1) {
          add = xs + '00'
        } else if (xs.length === 2) {
          add = xs + '0'
        } else if (xs.length === 3) {
          add = xs
        } else if (xs.length > 3) {
          add = xs.slice(0, 3)
        }
      }
      if (number === 2) {
        if (xs.length === 1) {
          add = xs + '0'
        } else if (xs.length === 2) {
          add = xs
        } else if (xs.length === 3) {
          add = xs.slice(0, 2)
        } else if (xs.length > 3) {
          add = xs.slice(0, 2)
        }
      }
      if (number === 1) {
        if (xs.length === 1) {
          add = xs
        } else if (xs.length === 2) {
          add = xs.slice(0, 1)
        } else if (xs.length === 3) {
          add = xs.slice(0, 1)
        } else if (xs.length > 3) {
          add = xs.slice(0, 1)
        }
      }
    }
  }
  if (type === 'string') {
    return `${zs}.${add}` // 如果要 str 就 不用转化
  }
  return parseFloat(`${zs}.${add}`) // 如果要 str 就 不用转化
}

/**
 * 后台取到的毫秒数,函数处理成小时、分钟、秒
 * 使用场景:
 * 后台取到的毫秒数,函数处理成小时、分钟、秒
 */
export const MillisecondToDate = msd => {
  if (msd == null) {
    return ''
  } else {
    if (msd < 1000) {
      return msd + 'ms'
    }
    const val = parseFloat(msd) / 1000
    if (val < 60) {
      if (val % 1 === 0) {
        return val + 's'
      } else {
        return val.toFixed(2) + 's'
      }
    } else {
      var min_total = Math.floor(val / 60) // 分钟
      var sec = Math.floor(val % 60) // 余秒
      if (min_total < 60) {
        return min_total + 'min' + sec + 's'
      } else {
        var hour_total = Math.floor(min_total / 60) // 小时数
        var min = Math.floor(min_total % 60) // 余分钟
        return hour_total + 'h' + min + 'min' + sec + 's'
      }
    }
  }
}

// 列表查询条件,时间范围,有的是默认查询1天,有的是默认查询当前时间往前推30天
export const starttime = moment('00:00:00', 'HH:mm:ss')
  .subtract(0, 'days')
  .format('YYYY-MM-DD HH:mm:ss')
export const endtime = moment('23:59:59', 'HH:mm:ss').format(
  'YYYY-MM-DD HH:mm:ss'
)
export const monthstarttime = moment('00:00:00', 'HH:mm:ss')
  .subtract(30, 'days')
  .format('YYYY-MM-DD HH:mm:ss')

// 全局唯一标识符GUID
export const newGuid = hexDigits => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

export const isRegExp = (params, type) => {
  let reg = ''
  if (!type) return true
  //数字
  if (type === 'number') {
    //^[0-9]*$
    if (!/(^(\-|\+)?\d+(\.\d+)?$)/.test(params)) {
      return true
    }
  }
  // 正整数 含0
  else if (type === 'number+0') {
    if (!/(^[0-9]\d*$)/.test(params)) {
      return true
    }
  }

  return false
}

/**
 * @description 列表时间显示
 */
export const timeShow = data => {
  // 默认时间 为空  具体时间
  if (!data) return data
  if (
    data === '0001-01-01T00:00:00' ||
    data === '0001-01-01T00:00:00Z' ||
    data === '0001-01-01 00:00:00' ||
    data === '0001-01-01 00:00:00Z'
  ) {
    return ''
  } else {
    return moment(new Date(data)).format('YYYY-MM-DD HH:mm:ss')
  }
}
export const UndefinedToNull = d => {
  const type = Object.prototype.toString.call(d)
  if (type == '[object Undefined]') {
    return null
  }
  return d
}

export const isType = d => {
  const type = Object.prototype.toString.call(d)
  if (type == '[object Number]') {
    return 'Number'
  } else if (type == '[object String]') {
    return 'String'
  } else if (type == '[object Object]') {
    return 'Object'
  } else if (type == '[object Null]') {
    return 'Null'
  } else if (type == '[object Undefined]') {
    return 'Undefined'
  } else if (type == '[object Boolean]') {
    return 'Boolean'
  } else if (type == '[object Array]') {
    return 'Array'
  } else if (type == '[object Function]') {
    return 'Function'
  } else if (type == '[object Date]') {
    return 'Date'
  } else if (type == '[object Error]') {
    return 'Error'
  } else if (type == '[object RegExp]') {
    return 'RegExp'
  }
  return 'Null'
}