import errorCode from './errorCode' import baseInfo from './baseInfo' import {PRICE_IS_ROUND} from './config' import userInfo from "../../../backendEle/src/utils/userInfo"; let tool = { /** * 设置JS存在客户端的Storage值 * @param key * @param value */ setStorage(key, value) { localStorage.setItem(key, value) }, /** * 获取Storage值 * @param key * @returns {string | null} */ getStorage(key) { return localStorage.getItem(key) }, /** * 移除Storage值 * @param key */ removeStorage(key) { localStorage.removeItem(key) }, /** * 获取当前时间戳(精确到秒) * @returns {number} */ getTimestamp(date = null) { let days = baseInfo.daysDiff() let dateObj if (date !== null) { dateObj = new Date(date) } else { dateObj = new Date() } return Math.round(dateObj.getTime() / 1000 + (days * 86400)) }, formatDate(timestamp, withTime = true) { let newDate = new Date() timestamp = parseInt(timestamp) if (timestamp) { newDate.setTime(timestamp * 1000) } else { return '' } let Y = newDate.getFullYear() + '-' let M = (newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1) + '-' let D = (newDate.getDate() < 10 ? '0' + (newDate.getDate()) : newDate.getDate()) + ' ' let h = (newDate.getHours() < 10 ? '0' + newDate.getHours() : newDate.getHours()) + ':' let m = (newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes()) + ':' let s = (newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds()) if (withTime) return Y + M + D + h + m + s return Y + M + D }, /** * 处理错误结果 * @param error * @returns {{message: string, todo: *}} */ errorHandle(error) { let message = '' let status = 0 let todo if (errorCode.has(error)) { let errorResult = errorCode.get(error) message = errorResult.message status = errorResult.status ? errorResult.status : 0 todo = errorResult.todo } else { message = error.message todo = null status = error.data.status ? error.data.status : 0 } if (todo || status === 401) { message = todo ? 'Not authorized, please log in again.' : (message === 'Your request was made with invalid credentials.' ? 'Not authorized, please log in again.' : message) userInfo.logout() } if (todo || status === 402) { message = todo ? 'No operation has been performed for a long time,please log in again.':(message === 'Connection not operated for too long' ? 'No operation has been performed for a long time,please log in again.' : message) // 长时间未进行操作,请重新登录 userInfo.logout() } return {message, todo, status} }, /** * 解析URL地址 * @param url * var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top'); myURL.file; // = 'index.html' myURL.hash; // = 'top' myURL.host; // = 'abc.com' myURL.query; // = '?id=255&m=hello' myURL.params; // = Object = { id: 255, m: hello } myURL.path; // = '/dir/index.html' myURL.segments; // = Array = ['dir', 'index.html'] myURL.port; // = '8080' myURL.protocol; // = 'http' myURL.source; // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top' * @returns {{source: *, protocol: string, host: string, port: string, query: string, params, file: string | *, hash: string, path: string, relative: string | *, segments: string[]}} */ parseURL(url) { let a = document.createElement('a') a.href = url return { source: url, protocol: a.protocol.replace(':', ''), host: a.hostname, port: a.port, query: a.search, params: (function () { let waitUrl = a.hash.replace(/^#\/[\-_a-zA-Z0-9]+\?/, '\?') || a.search let ret = {}, seg = waitUrl.replace(/^\?/, '').split('&'), len = seg.length, i = 0, s for (; i < len; i++) { if (!seg[i]) { continue } s = seg[i].split('=') ret[s[0]] = s[1] } return ret })(), file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1], hash: a.hash.replace('#', ''), path: a.pathname.replace(/^([^\/])/, '/$1'), relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1], segments: a.pathname.replace(/^\//, '').split('/') } }, removeFromArr(arr, item) { for (let i = arr.length - 1; i >= 0; i--) { if (arr[i] === item) { arr.splice(i, 1) return arr } } }, isInArray(arr, value) { for (let i in arr) { if (value === arr[i]) { return true } } return false }, isString(val) { return typeof val === 'string' || val instanceof String }, /** * 格式化金额数值为两位小数,是否四舍五入 * @param val * @returns {string} */ formatPrice(val) { val = Number.parseFloat(val) if (PRICE_IS_ROUND) { return val.toFixed(2) } else { val = val.toFixed(3) return val.substring(0, val.lastIndexOf('.') + 3) } }, /** * 根据状态返回颜色 * @param val * @returns {string} */ statusType(val) { switch (val) { case '0': return 'info' break case '1': return '' break case '2': return 'danger' break case '3': return 'warning' break case '4': return 'success' break default: return 'info' } }, sum(arr) {//求数组总和 var s = 0; for (var i=arr.length-1; i>=0; i--) { s += arr[i]; } return s; }, /** * 获取table显示高度 * @param hasStatusBar * @returns {number} */ getTableHeight(hasStatusBar = false) { if (hasStatusBar) return window.innerHeight - 320 return window.innerHeight - 260 }, // 计算商品税额 calculateTax(amount, taxRate, count = 1) { let taxAmount = (amount - amount / (1 + taxRate / 100)) * count return Math.round(taxAmount * 100) / 100 }, } export default tool