util.js 12.8 KB
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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
import $router from '../router/index'
import {
  commonApi
} from '../api/api'
/**emoji正则 */
const emojiReg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac])/g
/**
 * 日期格式化
 * let time = new Date().format('yyyy-MM-dd hh:mm:ss') //log   2020-07-31 10:00:00
 */
const getMockConfig = () => {
  return commonApi.getMockConfig()
}
Date.prototype.format = function (fmt) {
  let o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    //季度 
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S": this.getMilliseconds() //毫秒 
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
  }
  return fmt
}
const timeago = dateTimeStamp => {
  let result = '刚刚'
  let minute = 1000 * 60
  let hour = minute * 60
  let day = hour * 24
  let now = new Date().getTime() //获取当前时间毫秒
  let diffValue = now - dateTimeStamp //时间差
  let todayValue = new Date()
  todayValue.setHours(0)
  todayValue.setMinutes(0)
  todayValue.setSeconds(0)
  todayValue.setMilliseconds(0)
  let todayTimeStamp = todayValue.getTime() //获取当天零时毫秒
  if (diffValue < 0) {
    return result
  }
  let diffTodayValue = todayTimeStamp - dateTimeStamp
  //计算时间差的分,时,天,周,月
  let minC = diffValue / minute
  let hourC = diffValue / hour
  let dayC = diffTodayValue / day

  if (diffTodayValue > 0) {
    if (dayC >= 2) {
      return new Date(dateTimeStamp).format('MM月dd日 hh:mm:ss')
    }
    if (dayC >= 1 && dayC < 2) {
      return '前天' + new Date(dateTimeStamp).format(' hh:mm:ss')
    }
    return '昨天' + new Date(dateTimeStamp).format(' hh:mm:ss')
  }
  if (hourC >= 1 && hourC <= 23) {
    return parseInt(hourC) + '小时前'
  }
  if (minC >= 1 && minC <= 59) {
    return parseInt(minC) + '分钟前'
  }
  if (diffValue >= 0 && diffValue <= minute) {
    return '刚刚'
  }
  return new Date(dateTimeStamp).format('MM月dd日 hh:mm:ss')
}
/**
 * 防止重复点击
 */
const showLoading = (title = '') => {
  if (wx.showLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
    wx.showLoading({
      title,
      mask: true
    })
  } else {
    // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
    wx.showToast({
      title,
      icon: 'loading',
      mask: true,
      duration: 20000
    })
  }
}
const hideLoading = () => {
  if (wx.hideLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
    wx.hideLoading()
  } else {
    wx.hideToast()
  }
}
const showToast = val => {
  let obj = {}
  if (val && typeof val === 'string') {
    obj.title = val
    obj.icon = 'none'
  } else {
    obj = val
  }
  return wx.showToast(obj)
}
/**获取节点信息
 * name(id获取class)
 * callBack 回调函数
 * isComponents是否在组件
 */
const getViewInfo = (name, callBack, isComponents) => {
  const query = !isComponents ? wx.createSelectorQuery() : wx.createSelectorQuery().in(isComponents)
  query.select(name).boundingClientRect(res => {
    callBack(res)
  }).exec()
}
/**触底加载 */
const onReachBottom = (obj, callBack) => {
  let _this = $router.getPageInstance()
  let {
    pageNum,
    total,
    pageSize,
    nothing
  } = obj
  if (!total && !pageNum) {
    console.error('total&&pageNum为必传')
    return
  }
  if (!pageSize) pageSize = 10
  if (!nothing) nothing = 'nothing'
  if (Math.ceil(total / pageSize) > pageNum) {
    _this.setData({
      pageNum: pageNum + 1
    })
    callBack()
  } else {
    _this.setData({
      [nothing]: true
    })
  }
}
/**过滤表情 */
const haveEmoji = value => {
  let val = false
  value = value.replace(/\s/g, '').trimStart().trimEnd()
  if (emojiReg.test(value) && !/\s/g.test(value)) {
    showToast({
      icon: 'error',
      title: '不能输入表情'
    })
    val = true
  }
  return val
}
/**替换表情 */
const replaceEmoji = value => {
  let val = value.replace(emojiReg, '')
  return val.trimStart().trimEnd()
}
/**节流 */
const throttle = (fn, gapTime) => {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }
  let _lastTime = null
  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}
/**获取手机信息 */
const getPhoneInfo = callBack => {
  wx.getSystemInfo({
    success(res) {
      callBack(res)
    },
    fail(err) {
      callBack(err)
    }
  })
}
/**num:要转换的数值,fixed:精确几位小数 */
const decimal = (num, fixed = 2) => {
  const pow = Math.pow(10, fixed)
  return Number((Math.round(num * pow) / pow))
}
/**
 * 禁止滑动
 */
const noScroll = () => {}
/**设置粘贴板内容 */
const setCopyData = (data, callBack) => {
  wx.setClipboardData({
    data: data,
    success(res) {
      if (callBack && typeof callBack === 'function') callBack(res)
    }
  })
}
/**是否全面屏 */
const isFullSucreen = (isComponents) => {
  const thisPage = $router.getPageInstance()
  const routerList = $router.getRouterList()
  const router = routerList.find(item => item.url === `/${thisPage.route}`)
  let key = `${router.url.replace('/', '')}.html`
  let val = false
  if (__wxConfig && __wxConfig.page && __wxConfig.page[key]) {
    let {
      navigationStyle
    } = __wxConfig.page[key].window
    wx.getSystemInfo({
      success(res) {
        if (res.platform != 'android') {
          let {
            statusBarHeight,
            screenHeight,
            windowHeight
          } = res
          if (navigationStyle && navigationStyle == 'custom') {
            windowHeight = windowHeight - thisPage.data.navHeight || 0
          }
          //兼容自定义标题
          val = router.isTab ?
            screenHeight - windowHeight - statusBarHeight - 32 > 72 :
            screenHeight - windowHeight > 72
          if (isComponents) val = screenHeight - windowHeight > 72
        }
      },
      fail(err) {
        return false
      }
    })
  }

  return val
}
/** */
const getSessionId = () => {
  return wx.getStorageSync('aicard_sessionId')
}
const setSessionId = sessionId => {
  wx.setStorageSync('aicard_sessionId', sessionId)
}
const removeSystemStorage = () => {
  wx.removeStorageSync('aicard_user_info')
  wx.removeStorageSync('aicard_sessionId')
  wx.removeStorageSync('guest_no')
  wx.removeStorageSync('equity_info')
  wx.removeStorageSync('packageList')
  wx.removeStorageSync('isVIP')
  wx.removeStorageSync('bizjiaUrl')
  wx.removeStorageSync('vip_card_info')
}
const setStorageSync = (key, data) => {
  wx.setStorageSync(key, JSON.stringify(data))
}
const getStorageSync = key => {
  let data = wx.getStorageSync(key) || null
  return JSON.parse(data)
}
/** */
const getSceneId = path => {
  let [_route_, _options_] = path.split('?')
  let [target] = _route_.split('/')
  let name = _route_.split('/').pop()
  let scene = _options_ ? _options_.split('=')[1] : ''
  return {
    name,
    scene,
    target
  }
}
/**
 * 获取url参数
 */
const filterUrlParam = urlSearch => {
  let ret = {}
  let regParam = /([^&=]+)=([\w\W]*?)(&|$|#)/g
  if (urlSearch) {
    var strParam = urlSearch;
    var result
    while ((result = regParam.exec(strParam)) != null) {
      ret[result[1]] = result[2]
    }
  }
  return ret
}
/**拨打电话 */
const phoneCall = phoneNumber => {
  wx.makePhoneCall({
    phoneNumber: `${phoneNumber}`
  })
}
/**获取用户信息 */
const getUserInfo = () => {
  let user = wx.getStorageSync('aicard_user_info') || null
  return JSON.parse(user)
}
/**设置用户信息 */
const setUserInfo = userInfo => {
  wx.setStorageSync('aicard_user_info', JSON.stringify(userInfo))
}
/**IOS时间兼容 */
const iosTimeFormat = time => {
  return time.replace(/\-/g, '/')
}
/**设置标题栏 */
const setNavigationBarTitleText = title => {
  setStorageSync('dj_shopmall_app_title', title)
}
/**获取app标题 */
const getNavigationBarTitleText = () => {
  return getStorageSync('dj_shopmall_app_title')
}
/**删除对象里的null值 */
const clearObjNull = options => {
  let obj = {}
  Object.keys(options).map(e => {
    if (options[e] != null && options[e] != undefined) {
      if (typeof options[e] == 'object') {
        Object.keys(options[e]).map(key => {
          if (options[e][key] == null || options[e][key] == undefined) delete options[e][key]
        })
      }
      obj[e] = options[e]
    }
  })
  return obj
}
/**查看大图 */
const previewImage = params => {
  wx.previewImage(params)
}
/**获取时间段总时长 */
const getScopeTime = (inputTime, curTime) => {
  let obj = {
    text: '-',
    day: 0,
    isDanger: false
  }
  if (!inputTime || arguments.length === 0) return obj
  let time = curTime / 1000 - inputTime / 1000
  if (time < 60) {
    let s = parseInt(time)
    obj.text = `00:00:${s}`
  } else if (time < 3600) {
    let m = parseInt(time / 60)
    let s = parseInt(time % 60)
    m = m < 10 ? `0${m}` : m
    s = s < 10 ? `0${s}` : s
    obj.text = `00:${m}:${s}`
  } else if (time < 86400) {
    let h = parseInt(time / 3600)
    let min = time - h * 3600
    let m = parseInt(min / 60)
    let s = parseInt(time % 60)
    m = m < 10 ? `0${m}` : m
    s = s < 10 ? `0${s}` : s
    obj.text = `${h}:${m}:${s}`
  } else if (time > 86400) {
    let day = parseInt(time / 86400)
    let hour = time - day * 86400
    let h = parseInt(hour / 3600)
    let min = hour - h * 3600
    let m = parseInt(min / 60)
    let s = parseInt(time % 60)
    h = h < 10 ? `0${h}` : h
    m = m < 10 ? `0${m}` : m
    s = s < 10 ? `0${s}` : s
    if (day > 7 || (day == 7 && h > 0)) obj.isDanger = false
    obj.day = day
    obj.text = `${day}天${h}:${m}:${s}`
  }
  return obj.text
}

const deepClone = (target) => {
  const map = new WeakMap()
  
  function isObject(target) {
      return (typeof target === 'object' && target ) || typeof target === 'function'
  }

  function clone(data) {
      if (!isObject(data)) {
          return data
      }
      if ([Date, RegExp].includes(data.constructor)) {
          return new data.constructor(data)
      }
      if (typeof data === 'function') {
          return new Function('return ' + data.toString())()
      }
      const exist = map.get(data)
      if (exist) {
          return exist
      }
      if (data instanceof Map) {
          const result = new Map()
          map.set(data, result)
          data.forEach((val, key) => {
              if (isObject(val)) {
                  result.set(key, clone(val))
              } else {
                  result.set(key, val)
              }
          })
          return result
      }
      if (data instanceof Set) {
          const result = new Set()
          map.set(data, result)
          data.forEach(val => {
              if (isObject(val)) {
                  result.add(clone(val))
              } else {
                  result.add(val)
              }
          })
          return result
      }
      const keys = Reflect.ownKeys(data)
      const allDesc = Object.getOwnPropertyDescriptors(data)
      const result = Object.create(Object.getPrototypeOf(data), allDesc)
      map.set(data, result)
      keys.forEach(key => {
          const val = data[key]
          if (isObject(val)) {
              result[key] = clone(val)
          } else {
              result[key] = val
          }
      })
      return result
  }

  return clone(target)
}

/**
 * 判断是否是空对象
 * @param {*} obj 传进来的对象
 * @returns
 */
 const isEmptyObj = (obj) => {
  return JSON.stringify(obj) === "{}";
};
// 解析参数成对象 "actNum=1&activeNavIdx=0&isShare=true"
const parseString = (str) => {
  // console.log('str: ', str);
  if (!str) return;
  let obj = {};
  let strArr = str.split("&");
  // console.log('strArr: ', strArr);
  strArr.forEach((item) => {
    // console.log("item: ", item);
    let keyArr = item.split("=");
    obj[keyArr[0]] = keyArr[1];
  });
  return obj;
};





const Util = {
  setNavigationBarTitleText,
  getNavigationBarTitleText,
  removeSystemStorage,
  setStorageSync,
  getStorageSync,
  filterUrlParam,
  onReachBottom,
  isFullSucreen,
  iosTimeFormat,
  replaceEmoji,
  previewImage,
  getPhoneInfo,
  getSessionId,
  getScopeTime,
  setSessionId,
  clearObjNull,
  getUserInfo,
  setUserInfo,
  showLoading,
  hideLoading,
  getMockConfig,
  getViewInfo,
  setCopyData,
  getSceneId,
  haveEmoji,
  showToast,
  phoneCall,
  noScroll,
  throttle,
  decimal,
  timeago,
  deepClone,
  isEmptyObj,
  parseString,
}
export default Util