1058 lines
27 KiB
JavaScript
1058 lines
27 KiB
JavaScript
/* eslint-disable no-unused-vars */
|
||
import CryptoJS from 'crypto-js'
|
||
import JSEncrypt from 'jsencrypt'
|
||
import axios from 'axios'
|
||
import { getIV, getAseKey } from '@/utils/auth'
|
||
import { getToken } from '@/utils/auth'
|
||
import store from '@/store'
|
||
import Router from '@/router'
|
||
const service = axios.create({
|
||
baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
|
||
// withCredentials: true, // send cookies when cross-domain requests
|
||
// timeout: 7000 // request timeout
|
||
})
|
||
/**
|
||
* * 生成一个不重复的ID
|
||
* @param { Number } randomLength
|
||
*/
|
||
export function getUUID(randomLength = 10) {
|
||
return Number(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36)
|
||
}
|
||
/**
|
||
* 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 || !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))) {
|
||
// support "1548221490638"
|
||
time = parseInt(time)
|
||
} else {
|
||
// support safari
|
||
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
|
||
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]
|
||
// Note: getDay() returns 0 on Sunday
|
||
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
|
||
return value.toString().padStart(2, '0')
|
||
})
|
||
return time_str
|
||
}
|
||
|
||
export function getLastYear(yearNum = 1) {
|
||
const today = new Date() // 当天
|
||
today.setFullYear(today.getFullYear() - yearNum)
|
||
return today
|
||
}
|
||
export function getLastMonth(monthNum = 1) {
|
||
const today = new Date() // 当天
|
||
today.setMonth(today.getMonth() - monthNum)
|
||
return today
|
||
}
|
||
export function getLastDay(yearNum = 1) {
|
||
const today = new Date() // 当天
|
||
today.setDate(today.getDate() - yearNum)
|
||
return today
|
||
}
|
||
|
||
/**
|
||
* @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() +
|
||
'分'
|
||
)
|
||
}
|
||
}
|
||
// 节流
|
||
import Vue from 'vue'
|
||
const preventReClick = Vue.directive('preventReClick', {
|
||
inserted: function(el, binding) {
|
||
el.addEventListener('click', () => {
|
||
if (!el.disabled) {
|
||
el.disabled = true
|
||
setTimeout(() => {
|
||
el.disabled = false
|
||
}, 500)
|
||
}
|
||
})
|
||
}
|
||
})
|
||
/**
|
||
* @param {string} url
|
||
* @returns {Object}
|
||
*/
|
||
export function getQueryObject(url) {
|
||
url = url == null ? window.location.href : url
|
||
const search = url.substring(url.lastIndexOf('?') + 1)
|
||
const obj = {}
|
||
const reg = /([^?&=]+)=([^?&=]*)/g
|
||
search.replace(reg, (rs, $1, $2) => {
|
||
const name = decodeURIComponent($1)
|
||
let val = decodeURIComponent($2)
|
||
val = String(val)
|
||
obj[name] = val
|
||
return rs
|
||
})
|
||
return obj
|
||
}
|
||
|
||
/**
|
||
* @param {string} input value
|
||
* @returns {number} output value
|
||
*/
|
||
export function byteLength(str) {
|
||
// returns the byte length of an utf8 string
|
||
let s = str.length
|
||
for (var i = str.length - 1; i >= 0; i--) {
|
||
const code = str.charCodeAt(i)
|
||
if (code > 0x7f && code <= 0x7ff) s++
|
||
else if (code > 0x7ff && code <= 0xffff) s += 2
|
||
if (code >= 0xDC00 && code <= 0xDFFF) i--
|
||
}
|
||
return s
|
||
}
|
||
|
||
/**
|
||
* @param {Array} actual
|
||
* @returns {Array}
|
||
*/
|
||
export function cleanArray(actual) {
|
||
const newArray = []
|
||
for (let i = 0; i < actual.length; i++) {
|
||
if (actual[i]) {
|
||
newArray.push(actual[i])
|
||
}
|
||
}
|
||
return newArray
|
||
}
|
||
|
||
/**
|
||
* @param {Object} json
|
||
* @returns {Array}
|
||
*/
|
||
export function param(json) {
|
||
if (!json) return ''
|
||
return cleanArray(
|
||
Object.keys(json).map(key => {
|
||
if (json[key] === undefined) return ''
|
||
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
|
||
})
|
||
).join('&')
|
||
}
|
||
|
||
/**
|
||
* @param {string} url
|
||
* @returns {Object}
|
||
*/
|
||
export function param2Obj(url) {
|
||
const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
|
||
if (!search) {
|
||
return {}
|
||
}
|
||
const obj = {}
|
||
const searchArr = search.split('&')
|
||
searchArr.forEach(v => {
|
||
const index = v.indexOf('=')
|
||
if (index !== -1) {
|
||
const name = v.substring(0, index)
|
||
const val = v.substring(index + 1, v.length)
|
||
obj[name] = val
|
||
}
|
||
})
|
||
return obj
|
||
}
|
||
|
||
/**
|
||
* @param {string} val
|
||
* @returns {string}
|
||
*/
|
||
export function html2Text(val) {
|
||
const div = document.createElement('div')
|
||
div.innerHTML = val
|
||
return div.textContent || div.innerText
|
||
}
|
||
|
||
/**
|
||
* Merges two objects, giving the last one precedence
|
||
* @param {Object} target
|
||
* @param {(Object|Array)} source
|
||
* @returns {Object}
|
||
*/
|
||
export function objectMerge(target, source) {
|
||
if (typeof target !== 'object') {
|
||
target = {}
|
||
}
|
||
if (Array.isArray(source)) {
|
||
return source.slice()
|
||
}
|
||
Object.keys(source).forEach(property => {
|
||
const sourceProperty = source[property]
|
||
if (typeof sourceProperty === 'object') {
|
||
target[property] = objectMerge(target[property], sourceProperty)
|
||
} else {
|
||
target[property] = sourceProperty
|
||
}
|
||
})
|
||
return target
|
||
}
|
||
|
||
/**
|
||
* @param {HTMLElement} element
|
||
* @param {string} className
|
||
*/
|
||
export function toggleClass(element, className) {
|
||
if (!element || !className) {
|
||
return
|
||
}
|
||
let classString = element.className
|
||
const nameIndex = classString.indexOf(className)
|
||
if (nameIndex === -1) {
|
||
classString += '' + className
|
||
} else {
|
||
classString =
|
||
classString.substr(0, nameIndex) +
|
||
classString.substr(nameIndex + className.length)
|
||
}
|
||
element.className = classString
|
||
}
|
||
|
||
/**
|
||
* @param {string} type
|
||
* @returns {Date}
|
||
*/
|
||
export function getTime(type) {
|
||
if (type === 'start') {
|
||
return new Date().getTime() - 3600 * 1000 * 24 * 90
|
||
} else {
|
||
return new Date(new Date().toDateString())
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @param {Function} func
|
||
* @param {number} wait
|
||
* @param {boolean} immediate
|
||
* @return {*}
|
||
*/
|
||
export function debounce(func, wait, immediate) {
|
||
let timeout, args, context, timestamp, result
|
||
|
||
const later = function() {
|
||
// 据上一次触发时间间隔
|
||
const last = +new Date() - timestamp
|
||
|
||
// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
|
||
if (last < wait && last > 0) {
|
||
timeout = setTimeout(later, wait - last)
|
||
} else {
|
||
timeout = null
|
||
// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
|
||
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
|
||
}
|
||
}
|
||
|
||
/**
|
||
* This is just a simple version of deep copy
|
||
* Has a lot of edge cases bug
|
||
* If you want to use a perfect deep copy, use lodash's _.cloneDeep
|
||
* @param {Object} source
|
||
* @returns {Object}
|
||
*/
|
||
export function deepClone(source) {
|
||
if (!source && typeof source !== 'object') {
|
||
throw new Error('error arguments', 'deepClone')
|
||
}
|
||
const targetObj = source.constructor === Array ? [] : {}
|
||
Object.keys(source).forEach(keys => {
|
||
if (source[keys] && typeof source[keys] === 'object') {
|
||
targetObj[keys] = deepClone(source[keys])
|
||
} else {
|
||
targetObj[keys] = source[keys]
|
||
}
|
||
})
|
||
return targetObj
|
||
}
|
||
|
||
/**
|
||
* @param {Array} arr
|
||
* @returns {Array}
|
||
*/
|
||
export function uniqueArr(arr) {
|
||
return Array.from(new Set(arr))
|
||
}
|
||
|
||
/**
|
||
* @returns {string}
|
||
*/
|
||
export function createUniqueString() {
|
||
const timestamp = +new Date() + ''
|
||
const randomNum = parseInt((1 + Math.random()) * 65536) + ''
|
||
return (+(randomNum + timestamp)).toString(32)
|
||
}
|
||
|
||
/**
|
||
* Check if an element has a class
|
||
* @param {HTMLElement} elm
|
||
* @param {string} cls
|
||
* @returns {boolean}
|
||
*/
|
||
export function hasClass(ele, cls) {
|
||
return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
|
||
}
|
||
/**
|
||
* el-table高度
|
||
*/
|
||
export function getAppHeight(height) {
|
||
return document.body.clientHeight - 49 - 22 - 40 - 10 - height
|
||
}
|
||
/**
|
||
* table自适应高度
|
||
*/
|
||
export function getAutoAppHeight(height, searchHeight) {
|
||
return document.body.clientHeight - searchHeight - 64 - 40 - 20 - height
|
||
}
|
||
/**
|
||
* Add class to element
|
||
* @param {HTMLElement} elm
|
||
* @param {string} cls
|
||
*/
|
||
export function addClass(ele, cls) {
|
||
if (!hasClass(ele, cls)) ele.className += ' ' + cls
|
||
}
|
||
|
||
/**
|
||
* Remove class from element
|
||
* @param {HTMLElement} elm
|
||
* @param {string} cls
|
||
*/
|
||
export function removeClass(ele, cls) {
|
||
if (hasClass(ele, cls)) {
|
||
const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
|
||
ele.className = ele.className.replace(reg, ' ')
|
||
}
|
||
}
|
||
/**
|
||
* 组成树形数据
|
||
*/
|
||
export function getTreeNode(data, fliterData, nodeFilterId = 'id', filterId = 'id', children = 'children') {
|
||
const that = this
|
||
let selectNodes = []
|
||
data.forEach(function(v) {
|
||
const nodes = fliterData.filter(function(x) {
|
||
return x[filterId] === v[nodeFilterId]
|
||
})
|
||
if (nodes.length > 0) {
|
||
selectNodes.push(v)
|
||
}
|
||
const chData = v[children]
|
||
if (chData.length > 0) {
|
||
const sNodes = that.getTreeNode(chData, fliterData, nodeFilterId, filterId, children)
|
||
selectNodes = selectNodes.concat(sNodes)
|
||
}
|
||
})
|
||
return selectNodes
|
||
}
|
||
/**
|
||
* 拆解树为数组,并且不会对原始对象进行修改,原始对象子集列表也不会进行删除。
|
||
* @param tree {Array} 树形数组
|
||
* @param children_key {String} 子集对象 'key'
|
||
* @return {[{}]} 树形被拆解后的数组
|
||
*/
|
||
export function transformTree(array, id_key, parentId_key, isRoot) {
|
||
if (!array) return []
|
||
const idsObj = array.reduce((pre, cur) => Object.assign(pre, { [cur[id_key]]: cur }), {})
|
||
return Object.values(idsObj).reduce((pre, cur) => {
|
||
const parent = idsObj[cur[parentId_key]]
|
||
if (!isRoot(cur, parent)) {
|
||
!parent.children && (parent.children = [])
|
||
const children = parent.children
|
||
!children.includes(cur) && children.push(cur)
|
||
} else {
|
||
pre.push(cur)
|
||
}
|
||
return pre
|
||
}, [])
|
||
}
|
||
// 获取树形数据的某个元素的所有父节点
|
||
// 在methods中写如下函数
|
||
export function getTreePath(tree, func, path, field) {
|
||
if (!tree) return []
|
||
for (const data of tree) {
|
||
path.push(data[field])
|
||
|
||
if (func(data)) return path
|
||
if (data.children) {
|
||
const findChildren = getTreePath(data.children, func, path, field)
|
||
if (findChildren.length) return findChildren
|
||
}
|
||
path.pop()
|
||
}
|
||
return []
|
||
}
|
||
export function encryptPsd(data) {
|
||
const RamKey = getRamNumber()
|
||
const RamIv = getRamNumber()
|
||
const key = CryptoJS.enc.Utf8.parse(RamKey)
|
||
const iv = CryptoJS.enc.Utf8.parse(RamIv)
|
||
const srcs = CryptoJS.enc.Utf8.parse(data)
|
||
var encrypted = CryptoJS.AES.encrypt(srcs, key, {
|
||
iv: iv,
|
||
mode: CryptoJS.mode.CBC,
|
||
padding: CryptoJS.pad.Pkcs7
|
||
})
|
||
|
||
return {
|
||
key: RamKey,
|
||
iv: RamIv,
|
||
password: CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
|
||
}
|
||
}
|
||
export function encryptUpdatePsd(data) {
|
||
const RamKey = getAseKey()
|
||
const RamIv = getIV()
|
||
const key = CryptoJS.enc.Utf8.parse(RamKey)
|
||
const iv = CryptoJS.enc.Utf8.parse(RamIv)
|
||
const srcs = CryptoJS.enc.Utf8.parse(data)
|
||
var encrypted = CryptoJS.AES.encrypt(srcs, key, {
|
||
iv: iv,
|
||
mode: CryptoJS.mode.CBC,
|
||
padding: CryptoJS.pad.Pkcs7
|
||
})
|
||
|
||
return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
|
||
}
|
||
export function getRamNumber() {
|
||
var result = ''
|
||
for (var i = 0; i < 16; i++) {
|
||
result += Math.floor(Math.random() * 16).toString(16)// 获取0-15并通过toString转16进制
|
||
}
|
||
// 默认字母小写,手动转大写
|
||
return result.toUpperCase()// 另toLowerCase()转小写
|
||
}
|
||
export function JSEncryptData(publicKey, iv, key) {
|
||
const encrypt = new JSEncrypt()
|
||
// 将公钥存入内
|
||
encrypt.setPublicKey(publicKey)
|
||
const ivData = encrypt.encrypt(iv)
|
||
const keyData = encrypt.encrypt(key)
|
||
return {
|
||
ivData: ivData,
|
||
keyData: keyData
|
||
}
|
||
}
|
||
export function JSEncryptDataByBigScreen(publicKey) {
|
||
const key = getAseKey()
|
||
const iv = getIV()
|
||
const encrypt = new JSEncrypt()
|
||
// 将公钥存入内
|
||
encrypt.setPublicKey(publicKey)
|
||
const ivData = encrypt.encrypt(iv)
|
||
const keyData = encrypt.encrypt(key)
|
||
return {
|
||
ivData: ivData,
|
||
keyData: keyData
|
||
}
|
||
}
|
||
// 获取myHeaders
|
||
export function getMyHeaders() {
|
||
return {
|
||
authorization: getToken(),
|
||
lang: sessionStorage.getItem('language') === 'en_US' ? 'en_US' : sessionStorage.getItem('language')
|
||
}
|
||
}
|
||
export function handleDownFileByType(url, options, type, callback) {
|
||
return service({
|
||
url: url,
|
||
method: 'post',
|
||
data: options,
|
||
responseType: 'blob',
|
||
headers: {
|
||
authorization: getToken(),
|
||
lang: sessionStorage.getItem('language') === 'en_US' ? 'en_US' : sessionStorage.getItem('language')
|
||
}
|
||
}).then((response) => {
|
||
// 处理返回的文件流
|
||
const blob = new Blob([response.data], { type: type })
|
||
const link = document.createElement('a')
|
||
link.href = URL.createObjectURL(blob)
|
||
link.download = options.title
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
window.setTimeout(function() {
|
||
URL.revokeObjectURL(blob)
|
||
document.body.removeChild(link)
|
||
const resp = {
|
||
code: 0
|
||
}
|
||
callback(resp)
|
||
}, 0)
|
||
}).catch((err) => {
|
||
const resp = {
|
||
code: 1,
|
||
msg: err
|
||
}
|
||
callback(resp)
|
||
})
|
||
}
|
||
export function handleDownFile(url, options, callback) {
|
||
return service({
|
||
url: url,
|
||
method: 'get',
|
||
params: options,
|
||
responseType: 'blob'
|
||
})
|
||
.then((response) => {
|
||
// 处理返回的文件流
|
||
const blob = new Blob([response], { type: 'application/octet-stream' })
|
||
const link = document.createElement('a')
|
||
link.href = URL.createObjectURL(blob)
|
||
link.download = options.title
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
window.setTimeout(function() {
|
||
URL.revokeObjectURL(blob)
|
||
document.body.removeChild(link)
|
||
const resp = {
|
||
code: 0
|
||
}
|
||
callback(resp)
|
||
}, 0)
|
||
})
|
||
.catch((err) => {
|
||
const resp = {
|
||
code: 1,
|
||
msg: err
|
||
}
|
||
callback(resp)
|
||
})
|
||
}
|
||
export function handleNewDownExcel(url, title, options, callback) {
|
||
return service({
|
||
url: url,
|
||
method: 'post',
|
||
data: options,
|
||
responseType: 'blob',
|
||
headers: {
|
||
authorization: getToken(),
|
||
lang: sessionStorage.getItem('language') === 'en_US' ? 'en_US' : sessionStorage.getItem('language')
|
||
}
|
||
}).then((response) => {
|
||
// 处理返回的文件流
|
||
const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
|
||
const link = document.createElement('a')
|
||
link.href = URL.createObjectURL(blob)
|
||
const filename = title.includes('.xls') ? title : title + '.xls'
|
||
link.download = filename
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
window.setTimeout(function() {
|
||
URL.revokeObjectURL(blob)
|
||
document.body.removeChild(link)
|
||
const resp = {
|
||
code: 0
|
||
}
|
||
callback(resp)
|
||
}, 0)
|
||
}).catch((err) => {
|
||
const resp = {
|
||
code: 1,
|
||
msg: err
|
||
}
|
||
callback(resp)
|
||
})
|
||
}
|
||
export function handleDownExcel(url, options, callback) {
|
||
return service({
|
||
url: url,
|
||
method: 'post',
|
||
data: options,
|
||
responseType: 'blob',
|
||
headers: {
|
||
authorization: getToken(),
|
||
lang: sessionStorage.getItem('language') === 'en_US' ? 'en_US' : sessionStorage.getItem('language')
|
||
}
|
||
}).then((response) => {
|
||
// 处理返回的文件流
|
||
const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
|
||
const link = document.createElement('a')
|
||
link.href = URL.createObjectURL(blob)
|
||
// 确保文件名包含扩展名
|
||
const filename = options.title.includes('.xls') ? options.title : options.title + '.xls'
|
||
link.download = filename
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
window.setTimeout(function() {
|
||
URL.revokeObjectURL(blob)
|
||
document.body.removeChild(link)
|
||
const resp = {
|
||
code: 0
|
||
}
|
||
callback(resp)
|
||
}, 0)
|
||
}).catch((err) => {
|
||
const resp = {
|
||
code: 1,
|
||
msg: err
|
||
}
|
||
callback(resp)
|
||
})
|
||
}
|
||
|
||
export function handleDownPdf(url, options, callback) {
|
||
return service({
|
||
url: url,
|
||
method: 'post',
|
||
data: options,
|
||
responseType: 'blob',
|
||
headers: {
|
||
authorization: getToken(),
|
||
lang: sessionStorage.getItem('language') === 'en_US' ? 'en_US' : sessionStorage.getItem('language')
|
||
}
|
||
}).then((response) => {
|
||
// 处理返回的文件流
|
||
const blob = new Blob([response.data], { type: 'application/pdf' })
|
||
const link = document.createElement('a')
|
||
link.href = URL.createObjectURL(blob)
|
||
link.download = options.title
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
window.setTimeout(function() {
|
||
URL.revokeObjectURL(blob)
|
||
document.body.removeChild(link)
|
||
const resp = {
|
||
code: 0
|
||
}
|
||
callback(resp)
|
||
}, 0)
|
||
}).catch((err) => {
|
||
const resp = {
|
||
code: 1,
|
||
msg: err
|
||
}
|
||
callback(resp)
|
||
})
|
||
}
|
||
|
||
export function handleDownPic(url, options, callback) {
|
||
return service({
|
||
url: url,
|
||
method: 'post',
|
||
data: options,
|
||
responseType: 'blob',
|
||
headers: {
|
||
authorization: getToken(),
|
||
lang: sessionStorage.getItem('language') === 'en_US' ? 'en_US' : sessionStorage.getItem('language')
|
||
}
|
||
}).then((response) => {
|
||
// 处理返回的文件流
|
||
const blob = new Blob([response.data], { type: 'text/csv,charset=UTF-8' })
|
||
const link = document.createElement('a')
|
||
link.href = URL.createObjectURL(blob)
|
||
link.download = options.title
|
||
document.body.appendChild(link)
|
||
link.click()
|
||
window.setTimeout(function() {
|
||
URL.revokeObjectURL(blob)
|
||
document.body.removeChild(link)
|
||
const resp = {
|
||
code: 0
|
||
}
|
||
callback(resp)
|
||
}, 0)
|
||
}).catch((err) => {
|
||
const resp = {
|
||
code: 1,
|
||
msg: err
|
||
}
|
||
callback(resp)
|
||
})
|
||
}
|
||
|
||
export function isTimeRange(str) {
|
||
const timeRange = str.toString()
|
||
const timeArray = timeRange.split('-')
|
||
if (timeArray.length !== 2) {
|
||
return false
|
||
}
|
||
var a = timeArray[0].match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/)
|
||
var b = timeArray[1].match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/)
|
||
|
||
if (a == null || b == null) { return false }
|
||
if (a[1] > 24 || a[3] > 60 || a[4] > 60 || b[1] > 24 || b[3] > 60 || b[4] > 60) {
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
/**
|
||
* @param date [beginDateStr] [开始时间]
|
||
* @param date [endDateStr] [结束时间]
|
||
* @param date [targetDate] [判断目标时间]
|
||
* @return Boolean
|
||
*/
|
||
|
||
export function isSelectTime(timeArr, startTime, endTime) {
|
||
try {
|
||
timeArr.forEach(item => {
|
||
var start = time_to_sec(startTime)
|
||
var end = time_to_sec(endTime)
|
||
var beginDate = time_to_sec(item.startTime)
|
||
var endDate = time_to_sec(item.endTime)
|
||
if (start >= beginDate && start <= endDate) { // 开始时间在已选的时间内
|
||
throw new Error('error')
|
||
}
|
||
if (end >= beginDate && end <= endDate) { // 结束时间在已选的时间内
|
||
throw new Error('error')
|
||
}
|
||
if (beginDate >= start && endDate <= end) { // 选择的范围包含了已经选择过的时间
|
||
throw new Error('error')
|
||
}
|
||
return true
|
||
})
|
||
} catch (err) {
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
// 将时分秒转为时间戳
|
||
export function time_to_sec(time) {
|
||
if (time !== null) {
|
||
var s = ''
|
||
var hour = time.split(':')[0]
|
||
var min = time.split(':')[1]
|
||
var sec = time.split(':')[2]
|
||
s = Number(hour * 3600) + Number(min * 60) + Number(sec)
|
||
return s
|
||
}
|
||
}
|
||
// 度转度°分′秒″
|
||
export function ToDegrees(data, type) {
|
||
if (typeof (data) === 'undefined' || data === '') {
|
||
return ''
|
||
}
|
||
const val = data.toString()
|
||
let i = val.indexOf('.')
|
||
const strDu = i < 0 ? val : val.substring(0, i)// 获取度
|
||
let strFen = 0
|
||
let strMiao = 0
|
||
if (i > 0) {
|
||
strFen = '0' + val.substring(i)
|
||
strFen = strFen * 60 + ''
|
||
i = strFen.indexOf('.')
|
||
if (i > 0) {
|
||
strMiao = '0' + strFen.substring(i)
|
||
strFen = strFen.substring(0, i)// 获取分
|
||
strMiao = strMiao * 60 + ''
|
||
i = strMiao.indexOf('.')
|
||
strMiao = strMiao.substring(0, i + 4)// 取到小数点后面三位
|
||
strMiao = parseFloat(strMiao).toFixed(2)// 精确小数点后面两位
|
||
}
|
||
}
|
||
// return strDu + ',' + strFen + ',' + strMiao
|
||
let result = ''
|
||
if (type === 1) {
|
||
result = strDu + '°' + strFen + "'" + 'E'
|
||
} else {
|
||
result = strDu + '°' + strFen + "'" + 'N'
|
||
}
|
||
return result
|
||
}
|
||
|
||
// 度°分′秒″转度
|
||
export function ToDigital(strDu, strFen, strMiao, len) {
|
||
len = (len > 6 || typeof (len) === 'undefined') ? 6 : len// 精确到小数点后最多六位
|
||
strDu = (typeof (strDu) === 'undefined' || strDu === '') ? 0 : parseFloat(strDu)
|
||
strFen = (typeof (strFen) === 'undefined' || strFen === '') ? 0 : parseFloat(strFen) / 60
|
||
strMiao = (typeof (strMiao) === 'undefined' || strMiao === '') ? 0 : parseFloat(strMiao) / 3600
|
||
var digital = strDu + strFen + strMiao
|
||
if (digital === 0) {
|
||
return ''
|
||
} else {
|
||
return digital.toFixed(len)
|
||
}
|
||
}
|
||
|
||
// echarts曲线有功功率和soc的y轴
|
||
export function chartYIndex(value) {
|
||
if (value.name.toLowerCase().includes('pcs') || value.name.includes('有功功率')) {
|
||
return 0
|
||
} else if (value.name.toLowerCase().includes('bms') || value.name.toLowerCase().includes('soc')) {
|
||
return 1
|
||
} else {
|
||
return 0
|
||
}
|
||
}
|
||
// echarts曲线有功和无功的y轴
|
||
export function chartYPowerIndex(value) {
|
||
if (value.name.includes('有功')) {
|
||
return 0
|
||
} else if (value.name.includes('无功')) {
|
||
return 1
|
||
} else {
|
||
return 0
|
||
}
|
||
}
|
||
|
||
// echarts曲线电压和soc的y轴
|
||
export function chartYVoltageIndex(value) {
|
||
if (value.name.includes('压')) {
|
||
return 0
|
||
} else if (value.name.toLowerCase().includes('soc')) {
|
||
return 1
|
||
} else {
|
||
return 0
|
||
}
|
||
}
|
||
|
||
// echarts曲线电压和soc的y轴
|
||
export function chartNewYVoltageIndex(value) {
|
||
if (value.name.includes('功率')) {
|
||
return 0
|
||
} else if (value.name.toLowerCase().includes('soc')) {
|
||
return 1
|
||
} else {
|
||
return 0
|
||
}
|
||
}
|
||
|
||
export function getUrlParams(url) {
|
||
// 通过 ? 分割获取后面的参数字符串
|
||
const urlStr = url.split('?')[1]
|
||
// 创建空对象存储参数
|
||
const obj = {}
|
||
// 再通过 & 将每一个参数单独分割出来
|
||
const paramsArr = urlStr.split('&')
|
||
for (let i = 0, len = paramsArr.length; i < len; i++) {
|
||
// 再通过 = 将每一个参数分割为 key:value 的形式
|
||
const arr = paramsArr[i].split('=')
|
||
obj[arr[0]] = arr[1]
|
||
}
|
||
return obj
|
||
}
|
||
|
||
// 设置table的高度
|
||
export function windowResize() {
|
||
let form
|
||
|
||
setTimeout(() => {
|
||
if (document.getElementById('searchForm')) {
|
||
form = document.getElementById('searchForm').scrollHeight
|
||
store.commit('user/SET_SEARCH_HEIGHT', form)
|
||
}
|
||
|
||
window.onresize = () => {
|
||
form = document.getElementById('searchForm')?.scrollHeight
|
||
store.commit('user/SET_SEARCH_HEIGHT', form)
|
||
}
|
||
}, 500)
|
||
|
||
return form
|
||
}
|
||
|
||
export function changeUrl(oldUrl) {
|
||
var newUrl = oldUrl.replace('http://123.60.162.194:9000', 'https://ecloud.hoenergypower.cn')
|
||
|
||
return newUrl
|
||
}
|
||
|
||
// 导出当前时间
|
||
export function getCurrentDateTime() {
|
||
const now = new Date()
|
||
|
||
const year = now.getFullYear()
|
||
const month = String(now.getMonth() + 1).padStart(2, '0')
|
||
const day = String(now.getDate()).padStart(2, '0')
|
||
|
||
const hours = String(now.getHours()).padStart(2, '0')
|
||
const minutes = String(now.getMinutes()).padStart(2, '0')
|
||
const seconds = String(now.getSeconds()).padStart(2, '0')
|
||
|
||
const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
|
||
|
||
return formattedDateTime
|
||
}
|
||
|
||
export function beforeDayTime() {
|
||
// 获取当前时间
|
||
var now = new Date()
|
||
|
||
// 将时间调整到24小时前
|
||
now.setHours(now.getHours() - 24)
|
||
|
||
// 格式化输出开始时间
|
||
var year_start = now.getFullYear()
|
||
var month_start = now.getMonth() + 1
|
||
month_start = month_start < 10 ? '0' + month_start : month_start
|
||
var day_start = now.getDate()
|
||
day_start = day_start < 10 ? '0' + day_start : day_start
|
||
var hours_start = now.getHours()
|
||
hours_start = hours_start < 10 ? '0' + hours_start : hours_start
|
||
var minutes_start = now.getMinutes()
|
||
minutes_start = minutes_start < 10 ? '0' + minutes_start : minutes_start
|
||
var seconds_start = now.getSeconds()
|
||
seconds_start = seconds_start < 10 ? '0' + seconds_start : seconds_start
|
||
var formattedTime_start =
|
||
year_start +
|
||
'-' +
|
||
month_start +
|
||
'-' +
|
||
day_start +
|
||
' ' +
|
||
hours_start +
|
||
':' +
|
||
minutes_start +
|
||
':' +
|
||
seconds_start
|
||
|
||
// 获取当前时间
|
||
var now_end = new Date()
|
||
|
||
// 格式化输出结束时间
|
||
var year_end = now_end.getFullYear()
|
||
var month_end = now_end.getMonth() + 1
|
||
month_end = month_end < 10 ? '0' + month_end : month_end
|
||
var day_end = now_end.getDate()
|
||
day_end = day_end < 10 ? '0' + day_end : day_end
|
||
var hours_end = now_end.getHours()
|
||
hours_end = hours_end < 10 ? '0' + hours_end : hours_end
|
||
var minutes_end = now_end.getMinutes()
|
||
minutes_end = minutes_end < 10 ? '0' + minutes_end : minutes_end
|
||
var seconds_end = now_end.getSeconds()
|
||
seconds_end = seconds_end < 10 ? '0' + seconds_end : seconds_end
|
||
var formattedTime_end =
|
||
year_end +
|
||
'-' +
|
||
month_end +
|
||
'-' +
|
||
day_end +
|
||
' ' +
|
||
hours_end +
|
||
':' +
|
||
minutes_end +
|
||
':' +
|
||
seconds_end
|
||
return [formattedTime_start, formattedTime_end]
|
||
}
|
||
|
||
export function gotoDeviceList(id) {
|
||
Router.push({ name: 'standard-215-device-list', params: {
|
||
srcId: id }})
|
||
}
|
||
|
||
export function hiddenTextWord(text, length) {
|
||
if (text.length > length) {
|
||
return text.slice(0, length) + '...'
|
||
} else {
|
||
return text
|
||
}
|
||
}
|
||
|
||
export function changeTheme() {
|
||
if (JSON.parse(localStorage.getItem('themeConfig'))?.title === 'th') {
|
||
return 'th'
|
||
} else {
|
||
return 'hz'
|
||
}
|
||
}
|
||
|
||
// 递归遍历树并返回具有相同 id 的项
|
||
export function findItemsWithSameId(tree, targetId) {
|
||
const result = []
|
||
|
||
function traverse(node) {
|
||
// 如果当前节点的 id 与目标 id 相同,添加到结果数组
|
||
if (node.id === targetId) {
|
||
result.push(node)
|
||
}
|
||
|
||
// 如果有子节点,递归遍历子节点
|
||
if (node.list && node.list.length > 0) {
|
||
node.list.forEach(child => traverse(child))
|
||
}
|
||
}
|
||
|
||
// 遍历树的每个节点
|
||
tree.forEach(node => traverse(node))
|
||
|
||
return result
|
||
}
|