import cqcyCode from "@/utils/cqcyCode"; /** * 通用js方法封装处理 */ // 日期格式化 export function parseTime(time, pattern) { if (arguments.length === 0 || !time) { return null } const format = pattern || '{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) } else if (typeof time === 'string') { time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/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(/{(y|m|d|h|i|s|a)+}/g, (result, key) => { let value = formatObj[key] // Note: getDay() returns 0 on Sunday if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] } if (result.length > 0 && value < 10) { value = '0' + value } return value || 0 }) return time_str } // 表单重置 export function resetForm(refName) { if (this.$refs[refName]) { this.$refs[refName].resetFields(); } } // 添加日期范围 export function addDateRange(params, dateRange, propName) { let search = params; search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {}; dateRange = Array.isArray(dateRange) ? dateRange : []; if (typeof (propName) === 'undefined') { search.params['beginTime'] = dateRange[0]; search.params['endTime'] = dateRange[1]; } else { search.params['begin' + propName] = dateRange[0]; search.params['end' + propName] = dateRange[1]; } return search; } // 回显数据字典 export function selectDictLabel(datas, value) { if (value === undefined) { return ""; } var actions = []; Object.keys(datas).some((key) => { if (datas[key].value == ('' + value)) { actions.push(datas[key].label); return true; } }) if (actions.length === 0) { actions.push(value); } return actions.join(''); } // 回显数据字典(字符串数组) export function selectDictLabels(datas, value, separator) { if (value === undefined) { return ""; } var actions = []; var currentSeparator = undefined === separator ? "," : separator; var temp = value.split(currentSeparator); Object.keys(value.split(currentSeparator)).some((val) => { var match = false; Object.keys(datas).some((key) => { if (datas[key].value == ('' + temp[val])) { actions.push(datas[key].label + currentSeparator); match = true; } }) if (!match) { actions.push(temp[val] + currentSeparator); } }) return actions.join('').substring(0, actions.join('').length - 1); } // 字符串格式化(%s ) export function sprintf(str) { var args = arguments, flag = true, i = 1; str = str.replace(/%s/g, function () { var arg = args[i++]; if (typeof arg === 'undefined') { flag = false; return ''; } return arg; }); return flag ? str : ''; } // 转换字符串,undefined,null等转化为"" export function parseStrEmpty(str) { if (!str || str == "undefined" || str == "null") { return ""; } return str; } // 数据合并 export function mergeRecursive(source, target) { for (var p in target) { try { if (target[p].constructor == Object) { source[p] = mergeRecursive(source[p], target[p]); } else { source[p] = target[p]; } } catch (e) { source[p] = target[p]; } } return source; }; /** * 构造树型结构数据 * @param {*} data 数据源 * @param {*} id id字段 默认 'id' * @param {*} parentId 父节点字段 默认 'parentId' * @param {*} children 孩子节点字段 默认 'children' */ export function handleTree(data, id, parentId, children) { let config = { id: id || 'id', parentId: parentId || 'parentId', childrenList: children || 'children' }; var childrenListMap = {}; var nodeIds = {}; var tree = []; for (let d of data) { let parentId = d[config.parentId]; if (childrenListMap[parentId] == null) { childrenListMap[parentId] = []; } nodeIds[d[config.id]] = d; childrenListMap[parentId].push(d); } for (let d of data) { let parentId = d[config.parentId]; if (nodeIds[parentId] == null) { tree.push(d); } } for (let t of tree) { adaptToChildrenList(t); } function adaptToChildrenList(o) { if (childrenListMap[o[config.id]] !== null) { o[config.childrenList] = childrenListMap[o[config.id]]; } if (o[config.childrenList]) { for (let c of o[config.childrenList]) { adaptToChildrenList(c); } } } return tree; } /** * 参数处理 * @param {*} params 参数 */ export function tansParams(params) { let result = '' for (const propName of Object.keys(params)) { const value = params[propName]; var part = encodeURIComponent(propName) + "="; if (value !== null && value !== "" && typeof (value) !== "undefined") { if (typeof value === 'object') { for (const key of Object.keys(value)) { if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') { let params = propName + '[' + key + ']'; var subPart = encodeURIComponent(params) + "="; result += subPart + encodeURIComponent(value[key]) + "&"; } } } else { result += part + encodeURIComponent(value) + "&"; } } } return result } // 验证是否为blob格式 export async function blobValidate(data) { try { const text = await data.text(); JSON.parse(text); return false; } catch (error) { return true; } } /** * 创建加载框 * @param tips * @returns {Promise<*>} */ export function showLoading(_this, tips) { const loading = _this.$loading({ lock: true, text: tips ? tips : '加载中···', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }); setTimeout(() => { if (loading) loading.close() }, 30 * 1000) return loading } /** * HOST 地址验证 * @param url * @returns {boolean} */ export function testHost(url) { const strRegex = '^(http(s)?://)' // (https或http或ftp):// 可有可无 + '(([\\w_!~*\'()\\.&=+$%-]+: )?[\\w_!~*\'()\\.&=+$%-]+@)?' // ftp的user@ 可有可无 + '(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 3位数字.3位数字.3位数字.3位数字 + '|' // 允许IP和DOMAIN(域名) + '(localhost)|' // 匹配localhost + '([\\w_!~*\'()-]+\\.)*' // 域名- 至少一个[英文或数字_!~*\'()-]加上. + '\\w+\\.' // 一级域名 -英文或数字 加上. + '[a-zA-Z]{1,6})' // 顶级域名- 1-6位英文 + '(:[0-9]{1,5})?' // 端口- :80 ,1-5位数字 + '((/?)|' // url无参数结尾 - 斜杆或这没有 + '(/[\\w_!~*\'()\\.;?:@&=+$,%#-]+)+/?)$'; // 请求参数结尾- 英文或数字和[]内的各种字符 const re = new RegExp(strRegex, 'i'); // 大小写不敏感 if (!re.test(encodeURI(url))) { return false } return true } /** * 获取当前时间 * @param type * @returns {string} */ export function getNowFormatDate(type) { let date = new Date(), year = date.getFullYear(), //获取完整的年份(4位) month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月) strDate = date.getDate(), // 获取当前日(1-31) hours = date.getHours(), // 获取时(1-24) minutes = date.getMinutes(), // 获取分(1-60) seconds = date.getSeconds() // 获取秒(1-60) if (month < 10) month = `0${month}` // 如果月份是个位数,在前面补0 if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数,在前面补0 if (hours < 10) hours = `0${hours}` // 如果时是个位数,在前面补0 if (minutes < 10) minutes = `0${minutes}` // 如果分是个位数,在前面补0 if (seconds < 10) seconds = `0${seconds}` // 如果秒是个位数,在前面补0 if (type === 'yyyy-MM-dd') { return `${year}-${month}-${strDate}` } if (type === 'yyyy-MM-dd HH:mm:ss') { return `${year}-${month}-${strDate} ${hours}:${minutes}:${seconds}` } return `${year}-${month}-${strDate} ${hours}:${minutes}:${seconds}` } /** * 获取显示的数组 * @param node * @returns {*} */ export function traverseNode(node) { if (Object.prototype.toString.call(node) === '[object Array]') { return node.map(t => traverseNode(t)) } let data = node.data data.visible = node.visible return data } /** * 树节点过滤显示节点 * @param arr * @returns {*} */ export function traverseVisible(arr) { return arr.filter(t => { let visible = t.visible if (!visible) { return false } if (t.children) { t.children = traverseVisible(t.children) } delete t.visible return visible }) } /** * 过滤树信息 * @param list * @param value * @returns {*} */ export function deepTreeFilter(list, value) { return list.filter(item => { if (!item.isLeaf) { item.children = deepTreeFilter(item.children, value) return true } return item.label.indexOf(value) !== -1 }) } /** * 树数据添加属性 * @param list * @param key */ export function deepTreeKey(list, key) { list.forEach(item => { if (item.children && item.children.length > 0) { deepTreeKey(item.children, key) } else { item[key] = true } }) } /** * 排序比较 * @param {string} propertyName 排序的属性名 * @param {string} sort ascending(升序)/descending(降序) * @return {function} */ export function customCompare(propertyName, sort) { // 判断是否为数字 function isNumberV(val) { // 非负浮点数 const regPos = /^\d+(\.\d+)?$/ // 负浮点数 const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/ if (regPos.test(val) || regNeg.test(val)) { return true } else { return false } } return function (obj1, obj2) { let value1 = obj1[propertyName] let value2 = obj2[propertyName] // 数字类型的比较 if (isNumberV(value1) || isNumberV(value2)) { if (sort === 'ascending') { return value1 - value2 } else { return value2 - value1 } } // 布尔值的比较:利用减法-转化true 和 false // true => 1 false ⇒ 0 // true-false => 1 false-true => -1 // 下面方法是按照先false后true的顺序排序,如果想先true后false,调整value1-value2 和 value2 - value1的顺序即可 else if (_.isBoolean(value1) && _.isBoolean(value2)) { if (sort === 'ascending') { return value1 - value2 } else { return value2 - value1 } } // 字符比较使用localeCompare() else { value1 = value1 ? value1 : '默认值' const res = value1.localeCompare(value2, 'zh') return sort === 'ascending' ? res : -res } } } /** * 获取在线表格数据信息 * @returns {string|null} */ export function getLuckysheetConfig() { if (!luckysheet) return null let ls = luckysheet.getLuckysheetfile() if (!ls) return null ls.forEach((item, index) => { if(item.chart) { item.chart.forEach((chart, i) => { ls[index].chart[i] = { ...ls[index].chart[i], chartOptions: {...chartmix.default.getChartJson(chart.chart_id)} } let div = document.getElementById(chart.chart_id + '_c'); if(div.style) { ls[index].chart[i].left = parseInt(div.style.left) ls[index].chart[i].top = parseInt(div.style.top) ls[index].chart[i].width = parseInt(div.style.width) ls[index].chart[i].height = parseInt(div.style.height) } }) } }) return JSON.stringify(ls) } /** * 显示alert弹出层 * @param _this * @param title * @param e * @param callback */ export function showAlertWin(_this, title, e, callback) { if (e && e.name == 'TypeError') { console.error(e) return } _this.$alert(e, title ? title : cqcyCode[100], { confirmButtonText: '确定', showClose: false, callback: action => { resetConfirmWinPosition() if (callback) callback(action) } }) } /** * 显示消息提示 * @param _this * @param title * @param msg * @param callback */ export function showAlertMsgWin(_this, title, msg, callback) { _this.$alert(msg, title ? title : cqcyCode[100], { confirmButtonText: '确定', showClose: false, callback: action => { resetConfirmWinPosition() if (callback) callback(action) } }) } /** * 显示询问框 * @param _this * @param title * @param msg * @param callback */ export function showConfirmWin(_this, title, msg, callback) { _this.$confirm(msg, title ? title : cqcyCode[100], { confirmButtonText: '确定', cancelButtonText: '取消', customClass: 'close_confirm', closeOnClickModal: false, type: 'warning' }).then(() => { resetConfirmWinPosition() if (callback) callback() }).catch(() => { resetConfirmWinPosition() }) } /** * 显示输入框 * @param _this * @param title * @param msg * @param val * @param valid * @param callback * @param cancelCallback */ export function showPromptWin(_this, title, msg, val, valid, callback, cancelCallback) { _this.$prompt(msg, title ? title : cqcyCode[100], { confirmButtonText: '确定', cancelButtonText: '取消', customClass: 'close_confirm', closeOnClickModal: false, inputValue: val ? val : '', inputValidator: valid }).then(({value}) => { resetConfirmWinPosition() if (callback) callback(value) }).catch(() => { resetConfirmWinPosition() if (cancelCallback) cancelCallback() }) } /** * 重置询问框初始位置 */ export function resetConfirmWinPosition() { setTimeout(() => { const dragDom = document.querySelector('.el-message-box') if (dragDom) dragDom.style = '' }, 500) }