index.js 5.06 KB
Newer Older
wangdanlei's avatar
wangdanlei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
import moment from 'moment'
// import { Message, Notification, MessageBox } from 'element-ui'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}
/**
 * @Description: 树id,pid方式转children方式
 * @author lyk
 * @date 2019/6/18
 */
export function generateTree(nodes, config) {
  const id = config && config.id || 'id'
  const pid = config && config.pid || 'pid'
  const children = config && config.children || 'children'
  const idMap = {}
  const jsonTree = []
  nodes.forEach((v) => {
    v && (idMap[v[id]] = v)
  })
  nodes.forEach((v) => {
    if (v) {
      const parent = idMap[v[pid]]
      if (parent) {
        !parent[children] && (parent[children] = [])
        parent[children].push(v)
      } else {
        jsonTree.push(v)
      }
    }
  })
  return jsonTree
}
/**
 * @Description: form表单提交处理
 * @author cxg
 * @date 2019/12/10
 */
export function transformRequest(data) {
  let ret = ''
  for (const it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  ret = ret.substring(0, ret.lastIndexOf('&'))
  return ret
}
export function formatDate(time, formatPattern) {
  const date = 'YYYY-MM-DD'
  return moment(time).format(formatPattern || date)
}
// export function showMessage(msg, type) {
//   let t = 'info'
//   if (['info', 'success', 'warning', 'error'].includes(type)) {
//     t = type
//   }
//   Message({
//     dangerouslyUseHTMLString: true,
//     showClose: true,
//     message: msg,
//     type: t,
//     duration: 5000
//   })
// }

export function showNotification(msg, title, type) {
  let t = 'info'
  if (['info', 'success', 'warning', 'error'].includes(type)) {
    t = type
  }
  Notification({
    title: title,
    message: msg,
    duration: 5000,
    position: 'bottom-left',
    type: t
  })
}

// export function showMessageSuccess(msg) {
//   showMessage(msg, 'success')
// }

// export function showMessageError(msg) {
//   showMessage(msg, 'error')
// }

// export function showMessageInfo(msg) {
//   showMessage(msg, 'info')
// }

// export function showMessageWarning(msg) {
//   showMessage(msg, 'warning')
// }

// export function showConfirm(msg, title, type, confirmButtonText, cancelButtonText, successCallback, cancelCallback, confirmButtonClass) {
//   let t = 'info'
//   if (['info', 'success', 'warning', 'error'].includes(type)) {
//     t = type
//   }
//   MessageBox({
//     title: title,
//     message: msg,
//     showConfirmButton: !!confirmButtonText,
//     showCancelButton: !!cancelButtonText,
//     showClose: false,
//     confirmButtonText: confirmButtonText,
//     cancelButtonText: cancelButtonText,
//     type: t
//   }).then(() => {
//     successCallback && successCallback()
//   }).catch(() => {
//     cancelCallback && cancelCallback()
//   })
// }
export default {
  transformRequest,
  generateTree,
  param2Obj,
  formatTime,
  parseTime,
  formatDate
}