request
import axios from 'axios'
import { ElNotification } from 'element-plus'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
const pendingMap = new Map();
function apiHandler(domain) {
let service = axios.create({
baseURL: domain || location.origin,
timeout: 5000,
})
service.interceptors.request.use(
config => {
if (getToken()) config.headers['Authorization'] = getToken();
removePending(config);
addPending(config);
return config
},
error => Promise.reject(error)
)
service.interceptors.response.use(
response => {
removePending(response.config);
return response.data
},
error => {
httpErrorStatusHandle(error)
return Promise.reject(error)
}
)
return service
}
function httpErrorStatusHandle(error) {
if (axios.isCancel(error)) return console.error('请求的重复请求:' + error.message);
let message = '';
if (error && error.response) {
switch (error.response.status) {
case 302: message = '接口重定向了!'; break;
case 400: message = '参数不正确!'; break;
case 401: message = '您未登录,或者登录已经超时,请先登录!'; break;
case 403: message = '您没有权限操作!'; break;
case 404: message = `请求地址出错: ${error.response.config.url}`; break;
case 408: message = '请求超时!'; break;
case 409: message = '系统已存在相同数据!'; break;
case 500: message = '服务器内部错误!'; break;
case 501: message = '服务未实现!'; break;
case 502: message = '网关错误!'; break;
case 503: message = '服务不可用!'; break;
case 504: message = '服务暂时无法访问,请稍后再试!'; break;
case 505: message = 'HTTP版本不受支持!'; break;
default: message = '异常问题,请联系管理员!'; break
}
}
if (error.message.includes('timeout')) message = '网络请求超时!';
if (error.message.includes('Network')) message = window.navigator.onLine ? '服务端异常!' : '您断网了!';
ElNotification({
position: 'bottom-right',
title: '提示',
message: error.response?.data?.message || message,
type: 'error',
})
if ([401, 403].indexOf(error.response?.status) >= 0) {
removeToken()
window.sessionStorage.removeItem('userInfo')
router.push({ name: 'login' })
}
}
function getPendingKey(config) {
let { url, method, params, data } = config;
if (typeof data === 'string') data = JSON.parse(data);
return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&');
}
function addPending(config) {
const pendingKey = getPendingKey(config);
config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
if (!pendingMap.has(pendingKey)) {
pendingMap.set(pendingKey, cancel);
}
});
}
function removePending(config) {
const pendingKey = getPendingKey(config);
if (pendingMap.has(pendingKey)) {
const cancelToken = pendingMap.get(pendingKey);
cancelToken(pendingKey);
pendingMap.delete(pendingKey);
}
}
export default apiHandler
auth
import { ElNotification } from 'element-plus';
export function parseTime(time, cFormat) {
if (arguments.length === 0 || !time) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string')) {
if ((/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else {
time = time.replace(new RegExp(/-/gm), '/')
}
}
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]
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
return value.toString().padStart(2, '0')
})
return time_str
}
export function get_time_diff(time) {
var diff = '';
var time_diff = new Date().getTime() - time;
var days = Math.floor(time_diff / (24 * 3600 * 1000));
if (days > 0) {
diff += days + '天';
}
var leave1 = time_diff % (24 * 3600 * 1000);
var hours = Math.floor(leave1 / (3600 * 1000));
if (hours > 0) {
diff += hours + '小时';
} else {
if (diff !== '') {
diff += hours + '小时';
}
}
var leave2 = leave1 % (3600 * 1000);
var minutes = Math.floor(leave2 / (60 * 1000));
if (minutes > 0) {
diff += minutes + '分';
} else {
if (diff !== '') {
diff += minutes + '分';
}
}
var leave3 = leave2 % (60 * 1000);
var seconds = Math.round(leave3 / 1000);
if (seconds > 0) {
diff += seconds + '秒';
} else {
if (diff !== '') {
diff += seconds + '秒';
}
}
return diff;
}
export const isBoolean = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean';
};
export const isObj = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Object';
};
export const isArray = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Array';
};
export const isPass = (s) => {
const PASS_REG = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$)([^\u4e00-\u9fa5\s]){6,20}$/
return PASS_REG.test(s);
};
export const storage = {
setLocal: (key, value) => {
if (isArray(value) || isObj(value) || isBoolean(value)) {
window.localStorage.setItem(key, JSON.stringify(value));
} else {
window.localStorage.setItem(key, value);
}
},
getLocal: (key) => {
let value = window.localStorage.getItem(key);
if (value) {
return JSON.parse(value);
} else {
return value;
}
},
clearOneLocal: (key) => {
window.localStorage.removeItem(key);
},
clearAllLocal: () => {
const indexDBStore = storage.getLocal('indexDBStore');
window.localStorage.clear();
storage.setLocal('indexDBStore', JSON.stringify(indexDBStore));
},
setSession: (key, value) => {
if (isArray(value) || isObj(value) || isBoolean(value)) {
window.sessionStorage.setItem(key, window.btoa(window.encodeURIComponent(JSON.stringify(value))));
} else {
window.sessionStorage.setItem(key, window.btoa(window.encodeURIComponent(value)));
}
},
appendSession: (key, value) => {
let getValue = window.sessionStorage.getItem(key);
if (getValue) {
let oldValue = JSON.parse(getValue);
let newValue = Object.assign(oldValue, value);
window.sessionStorage.setItem(key, JSON.stringify(newValue));
} else {
window.sessionStorage.setItem(key, JSON.stringify(value));
}
},
getSession: (key) => {
let value = window.sessionStorage.getItem(key);
if (!value) {
return value;
} else {
try {
if (
isArray(JSON.parse(window.decodeURIComponent(window.atob(value)))) ||
isObj(JSON.parse(window.decodeURIComponent(window.atob(value))))
) {
return JSON.parse(window.decodeURIComponent(window.atob(value)));
} else {
if (window.decodeURIComponent(window.atob(value)) == 'true') {
return true;
} else if (window.decodeURIComponent(window.atob(value)) == 'false') {
return false;
} else {
return window.decodeURIComponent(window.atob(value));
}
}
} catch (e) {
return window.decodeURIComponent(window.atob(value));
}
}
},
clearOneSession: (key) => {
window.sessionStorage.removeItem(key);
},
clearAllSession: () => {
window.sessionStorage.clear();
}
};
export function uniqueArray(array, key) {
var result = [];
for (var i = 0; i < array.length; i++) {
var item = array[i];
var repeat = false;
for (var j = 0; j < result.length; j++) {
if (item[key] == result[j][key]) {
repeat = true;
break;
}
}
if (!repeat && item[key]) {
result.push(item);
}
}
return result;
}
export function copyUrl(url, isNotice = true) {
if (url) {
var input = document.createElement('input');
document.body.appendChild(input);
input.setAttribute('value', url);
input.select();
document.execCommand("copy");
if (document.execCommand('copy')) {
document.execCommand('copy');
}
if (isNotice) {
ElNotification({
position: 'bottom-right',
title: '提示',
type: 'success',
message: '复制成功'
})
}
document.body.removeChild(input);
} else {
ElNotification({
position: 'bottom-right',
title: '提示',
type: 'warning',
message: '不能复制空'
})
}
}
export function formatFileSize(bytes, decimalPoint = 2) {
if (bytes == 0) return "0 Bytes";
let k = 1000,
sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
i = Math.floor(Math.log(bytes) / Math.log(k));
return (
parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPoint)) + " " + sizes[i]
);
}
export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result
const later = function () {
const last = +new Date() - timestamp
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
if (!immediate) {
result = func.apply(context, args)
if (!timeout) context = args = null
}
}
}
return function (...args) {
context = this
timestamp = +new Date()
const callNow = immediate && !timeout
if (!timeout) timeout = setTimeout(later, wait)
if (callNow) {
result = func.apply(context, args)
context = args = null
}
return result
}
}
export function throttle(fn, delay) {
var ctx;
var args;
var previous = Date.now();
var later = function () {
fn.apply(ctx, args);
};
return function () {
ctx = this;
args = arguments;
var now = Date.now();
var diff = now - previous - delay;
if (diff >= 0) {
previous = now;
setTimeout(later, delay);
}
};
}
export function GroupingToArray(array, key, resKey = "list") {
if (!key) return array;
var aMap = [];
var aResult = [];
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (aMap.indexOf(item[key]) === -1) {
var oItem = {};
oItem[resKey] = [item];
oItem[key] = item[key];
aResult.push(oItem);
aMap.push(item[key]);
} else {
var index = aMap.indexOf(item[key]);
aResult[index][resKey].push(item);
}
}
return aResult;
}
export function datedifference([sDate1, sDate2]) {
var dateSpan, tempDate, iDays;
sDate1 = typeof sDate1 == 'number' ? sDate1 : Date.parse(sDate1);
sDate2 = typeof sDate2 == 'number' ? sDate2 : Date.parse(sDate2);
dateSpan = sDate2 - sDate1;
dateSpan = Math.abs(dateSpan);
iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
return iDays;
}
export function getDay(day) {
const doHandleMonth = month => {
var m = month;
if (month.toString().length == 1) {
m = "0" + month;
}
return m;
};
var today = new Date();
var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
today.setTime(targetday_milliseconds);
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
tMonth = doHandleMonth(tMonth + 1);
tDate = doHandleMonth(tDate);
return tYear + "-" + tMonth + "-" + tDate;
}
let a = 0
async function getreadMessage() {
console.log('轮询', ++a);
}
const STATUS_INTERVAL = 1.5 * 1000
const queryOrderStatus = () => {
setTimeout(async () => {
await getreadMessage()
queryOrderStatus();
}, STATUS_INTERVAL);
};
index
import { removeRouteList } from '@/router/index'
import { useRouterList } from '@/stores/modules/routerList'
import { useUserInfo } from '@/stores/modules/userInfo'
import { ElMessage, ElMessageBox } from 'element-plus'
import Decimal from 'decimal.js'
import { h } from 'vue'
import { useRouter } from 'vue-router'
export function times(data: number, flag = 0) {
const time = Number(data)
const d = Math.floor(time / 86400)
let h: number | string = Math.floor((time % 86400) / 3600)
let m: number | string = Math.floor(((time % 86400) % 3600) / 60)
const s = ((time % 86400) % 3600) % 60
if (flag === 1) {
d > 0 && (h += d * 24)
return (h ? h + '时' : '') + (m ? m + '分' : '') + (s ? s + '秒' : '')
} else if (flag === 2) {
d > 0 && (h += d * 24)
m = m < 10 ? '0' + m : m
h = h < 10 ? '0' + h : h
return (h ? h : '') + (m ? ':' + m : '') + (s ? ':' + s : '')
}
return (d > 0 ? d + '天' : '') + (h ? h + '时' : '') + (m ? m + '分' : '') + (s ? s + '秒' : '')
}
export function parseTime(
time: number | Date | string,
cFormat: string = '{y}-{m}-{d} {h}:{i}:{s}'
) {
if (arguments.length === 0 || !time) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if (typeof time === 'string') {
if (/^[0-9]+$/.test(time)) {
time = parseInt(time)
} else {
time = time.replace(new RegExp(/-/gm), '/')
}
}
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: string) => {
const value = formatObj[key]
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
return value.toString().padStart(2, '0')
})
return time_str
}
export const changeByte = (byte: number) => {
let size = ''
if (byte < 1 * 1024) {
size = `${byte.toFixed(2)}B`
} else if (byte < 1 * 1024 * 1024) {
size = `${(byte / 1024).toFixed(2)}KB`
} else if (byte < 1 * 1024 * 1024 * 1024) {
size = `${(byte / (1024 * 1024)).toFixed(2)}MB`
} else if (byte < 1 * 1024 * 1024 * 1024 * 1024) {
size = `${(byte / (1 * 1024 * 1024 * 1024)).toFixed(2)}GB`
} else {
size = `${(byte / (1024 * 1024 * 1024 * 1024)).toFixed(2)}TB`
}
const sizeStr = `${size}`
const index = sizeStr.indexOf('.')
const dou = sizeStr.substr(index + 1, 2)
if (dou == '00') {
return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
}
return size
}
export const changebyte = (byte: number) => {
let size = ''
if (byte < 1 * 1024) {
size = `${byte.toFixed(2)}b`
} else if (byte < 1 * 1024 * 1024) {
size = `${(byte / 1024).toFixed(2)}Kb`
} else if (byte < 1 * 1024 * 1024 * 1024) {
size = `${(byte / (1024 * 1024)).toFixed(2)}Mb`
} else if (byte < 1 * 1024 * 1024 * 1024 * 1024) {
size = `${(byte / (1 * 1024 * 1024 * 1024)).toFixed(2)}G`
} else {
size = `${(byte / (1024 * 1024 * 1024 * 1024)).toFixed(2)}Tb`
}
const sizeStr = `${size}`
const index = sizeStr.indexOf('.')
const dou = sizeStr.substr(index + 1, 2)
if (dou == '00') {
return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
}
return size
}
export function curTime() {
var date: string | any = new Date()
let month: number | any = date.getMonth() + 1
let strDate: number | any = date.getDate()
month = month < 10 ? '0' + month : month
if (strDate >= 0 && strDate <= 9) {
strDate = '0' + strDate
}
let getTimes: string | number =
date.getFullYear() +
'-' +
month +
'-' +
strDate +
' ' +
date.getHours() +
':' +
date.getMinutes() +
':' +
date.getSeconds()
var date: string | any = new Date(getTimes)
const time3 = Date.parse(date)
getTimes = Number(time3 / 1000)
return getTimes
}
export function timePicker(time: number, flag = false, string = false) {
let timeSu = null
if (string) {
timeSu = new Date(time).valueOf()
} else {
timeSu = time
}
let length = (timeSu + '').length
const times = new Date(length > 10 ? timeSu : timeSu * 1000)
let date = !flag
? `${times.getFullYear()}-${
times.getMonth() < 10 ? '0' + (times.getMonth() + 1) : times.getMonth() + 1
}-${times.getDate() < 10 ? '0' + times.getDate() : times.getDate()}${' '}${
times.getHours() < 10 ? '0' + times.getHours() : times.getHours()
}:${times.getMinutes() < 10 ? '0' + times.getMinutes() : times.getMinutes()}:${
times.getSeconds() < 10 ? '0' + times.getSeconds() : times.getSeconds()
}`
: `${times.getFullYear()}-${
times.getMonth() < 10 ? '0' + (times.getMonth() + 1) : times.getMonth() + 1
}-${times.getDate() < 10 ? '0' + times.getDate() : times.getDate()}`
return date
}
const fallbackCopyTextToClipboard = (text: string) => {
let textArea = document.createElement('textarea')
textArea.value = text
textArea.style.top = '0'
textArea.style.left = '0'
textArea.style.position = 'fixed'
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
try {
var successful = document.execCommand('copy')
var msg = successful ? 'successful' : 'unsuccessful'
ElMessage.success('复制成功')
console.log('Fallback: Copying text command was ' + msg)
} catch (err) {
ElMessage.error('复制失败')
console.error('Fallback: Oops, unable to copy', err)
}
document.body.removeChild(textArea)
}
export function copyTextToClipboard(text: string) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text)
return
}
navigator.clipboard.writeText(text).then(
function () {
ElMessage.success('复制成功')
console.log('Async: Copying to clipboard was successful!')
},
function (err) {
ElMessage.error('复制失败')
console.error('Async: Could not copy text: ', err)
}
)
}
export const getTimeRangeTimestamp = (range: string) => {
const now = new Date()
now.setHours(0, 0, 0, 0)
const startTimestamp = now.getTime()
switch (range) {
case 'day':
const nowTime = new Date()
return [startTimestamp, Math.floor(nowTime.getTime() / 1000) * 1000 - 1000]
case 'dayAll':
const endTimestamp = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
23,
59,
59
).getTime()
return [startTimestamp, endTimestamp]
case 'today':
const yesterday = new Date(startTimestamp - 24 * 60 * 60 * 1000)
yesterday.setHours(0, 0, 0, 0)
return [yesterday.getTime(), startTimestamp - 1000]
case 'toweek':
return [startTimestamp - 6 * 24 * 60 * 60 * 1000, startTimestamp + 24 * 60 * 60 * 1000 - 1000]
case 'threemonth':
return [
startTimestamp - 14 * 24 * 60 * 60 * 1000,
startTimestamp + 24 * 60 * 60 * 1000 - 1000
]
case 'tomonth':
return [
startTimestamp - 29 * 24 * 60 * 60 * 1000,
startTimestamp + 24 * 60 * 60 * 1000 - 1000
]
default:
return null
}
}
let loginOutTimer: any
function debounce(func: () => void, delay: number) {
return function () {
const context = this
const args = arguments
clearTimeout(loginOutTimer)
loginOutTimer = setTimeout(() => {
func.apply(context, args)
}, delay)
}
}
const debounceLoginOut = debounce((): void => {
useRouterList().removeCacheList()
useUserInfo().removeUserInfo()
removeRouteList()
}, 100)
export const loginOut = debounceLoginOut
export const decimal_up = (num: number | string, s: number = 2) => {
return Number(new Decimal(num || 0).toFixed(s, Decimal.ROUND_UP))
}
export const decimal_mul = function (...args: (number | Decimal | string)[]) {
if (args.length === 0) {
return 0
}
const result = args.reduce((accumulator, currentValue) => {
if (typeof currentValue === 'number' || typeof currentValue === 'string') {
return new Decimal(accumulator as number).mul(new Decimal(currentValue))
} else {
return accumulator
}
}, 1)
return result
}
export const decimal_round_half = function (num: number | string | null | undefined) {
if (!num) {
return 0
}
return new Decimal(num).toFixed(2, Decimal.ROUND_HALF_UP).toString()
}
export const decimal_round_Fixed = function (
num: number | string | null | undefined,
a: number | string = 1,
sum: number = 2
) {
if (!num) {
return 0
}
return new Decimal(decimal_mul(num, a)).toFixed(sum, Decimal.ROUND_DOWN).toString()
}
export const defaultTimeSelect: [Date, Date] = [
new Date(2000, 1, 1, 0, 0, 0),
new Date(2000, 2, 1, 23, 59, 59)
]
const elementButtonType = {
danger: {
confirmButtonClass: 'el-button--danger',
icon: 'iconfont icon-changguitishi message-icon-danger'
},
primary: {
confirmButtonClass: 'el-button--primary',
icon: 'iconfont icon-changguitishi message-icon message-icon-primary'
},
info: {
confirmButtonClass: 'el-button--primary',
icon: 'iconfont icon-toastjinggao message-icon message-icon-info'
},
warning: {
confirmButtonClass: 'el-button--primary',
icon: 'iconfont icon-toastjinggao message-icon-warning'
}
}
export const myMessage = (
{
msg,
title = '删除',
successText,
error,
type = 'danger'
}: {
msg: string
title: string
successText?: string
error?: (err: any) => void
type?: 'primary' | 'danger' | 'warning'
},
confirm?: () => Promise<any>
) => {
ElMessageBox({
title: title,
message: h('div', null, [
h(
'div',
{
class: 'dialog-box',
style: 'display:flex; justify-content: center;align-items: center;'
},
[
h('span', {
class: elementButtonType[type].icon,
'aria-hidden': 'true',
style: 'margin-right:10px'
}),
h('span', null, msg)
]
)
]),
showCancelButton: true,
confirmButtonText: '确定',
confirmButtonClass: elementButtonType[type].confirmButtonClass,
cancelButtonText: '取消',
beforeClose: (action, instance, done) => {
if (action === 'confirm') {
instance.confirmButtonLoading = true
instance.cancelButtonLoading = true
confirm &&
confirm()
.then((res) => {
ElMessage.success(successText || '删除成功')
done()
})
.catch((err) => {
error && error(err)
})
.finally(() => {
instance.confirmButtonLoading = false
instance.cancelButtonLoading = false
})
} else {
done()
}
}
})
}
export const payType: any = {
wechat: {
label: '微信支付',
icon: '#icon-weixin',
title: '微信'
},
ali_pay: {
label: '支付宝',
icon: '#icon-zhifubao',
title: '支付宝'
},
e_bank: {
label: '网银',
icon: '#icon-wangyin',
title: '网银'
},
USDT: {
label: 'USDT',
icon: '#icon-usdt',
title: 'USDT'
},
dcep: {
label: '数字人名币',
icon: '#icon-usdt',
title: '数字人名币'
}
}
export const getPayType = (type: string, icon: boolean = false) => {
return payType[type]
}
export const rulesObj = {
userNameRule: function (rule: any, value: string, callback: (arg0?: Error | undefined) => void) {
if (/^[A-Za-z0-9-\u4e00-\u9fa5]{4,30}$/.test(value) == false) {
callback(new Error('不能输入特殊符号和空格'))
} else {
callback()
}
},
urlRules: function (rule: any, value: string, callback: (arg0?: Error | undefined) => void) {
if (/[\u4e00-\u9fa5]/.test(value) == true) {
callback(new Error('请输入合法字符'))
} else {
callback()
}
}
}
export const getParamsByAction = (array: Array<any>, param: any) => {
array.forEach((item: any) => {
if (item.keys instanceof Array) {
item.keys.forEach((key: string, index: number) => {
if (item.type === 'date') param[key] = Number(item.value[index]) || null
else {
param[key] = item.value[index]
}
})
} else {
if (item.type === 'number') param[item.key] = Number(item.value)
else param[item.key] = item.value
}
})
}
export const pathToUrl = (path: string, query?: { [key: string]: string }) => {
const router = useRouter()
console.log(router)
if (path)
router.push({
path,
query
})
}