declare const $: any; // import VueCookies from 'vue-cookies-ts' import Vue from "vue"; import Constant from '../constant/constant'; import md5 from 'js-md5'; import Cookies from 'js-cookie' const moment = require('../moment/moment'); // Vue.use(VueCookies); // const $cookies: any = Vue.prototype.$cookies; const $cookies: any = Cookies; /** * 获取cookie * @param name {String} cookie名称 */ function getCookie(name: string) { return $cookies.get(name); } /** * 获取cookie * @param name {String} cookie名称 */ function setCookie(name: string, value: string | number, expires?: string | number | Date) { return $cookies.set(name, value, {expires}); } /**清除cookie */ function clearCookie(name: string) { $cookies.remove(name, {path: ''}); } /**清除所有cookie */ function clearAllCookie() { // @ts-ignore if (window['$platform'] === 'eap') { $cookies.remove('userID'); $cookies.remove('ewalkToken'); $cookies.remove('authToken'); } else { $cookies.remove('front_userID'); $cookies.remove('front_ewalkToken'); } $cookies.remove('user'); } /** * 获取userID */ function getUserID(platform: any = 'ecp') { return platform === 'ecp' ? $cookies.get('front_userID') : ''; } /** * 获取userID */ function getAdminUserID() { return $cookies.get('userID'); } /** * 获取userID */ function getUserToken(type: string = 'base', platform: string = 'eap') { return $cookies.get(platform === 'eap' ? 'ewalkToken' : 'front_ewalkToken'); } /** * 克隆 */ function deepClone(object: any) { return JSON.parse(JSON.stringify(object)); } // 将来时间点到现在的时间点的天数 time格式: 2018-04-20 15:00:10 function getTime(willTime: string, serverTime?: string): any { const nowTime = !!serverTime ? new Date(Date.parse(serverTime.replace(/-/g, '/'))).getTime() : new Date().getTime(); const endTime = new Date(Date.parse(willTime.replace(/-/g, '/'))).getTime(); return Number(Math.ceil((endTime - nowTime) / Constant.oneDayMillisecond)); } /**加密上传图片 * @param userID * @returns object {number:'',key:''} 返回上传图片的时候安全验证参数,用到十六进制和md5 */ function uploadImgSecurity(userID: any) { let obj: any = {number: '', key: ''}; let randomNum = Math.floor(Math.random() * 1000); // 1000以内的随机数 obj['number'] = randomNum; let hexadecimal = randomNum.toString(16); // 随机数的16进制 obj['key'] = md5(userID + hexadecimal); // md5加密 // obj['key'] = userID + hexadecimal; return obj; } /** * 整理节点 * @param {*} data * @type {String} 类型--hideSellout:隐藏售罄节点(默认)|showSellout:显示售罄节点 */ function initializeNode(data: Array, networkType = 'all', type = 'hideSellout') { let list = data; list = fifterNode(data, networkType, type); list = allocationRegion(list); list = allocationZone(list); // list = filterClassic(list); list = sortNode(list); return list; } /** * 清空售罄及节点 * @param {*} data */ function fifterNode(data: Array, networkType: string, type: string) { let list = [], newList = []; if (type === 'hideSellout') { for (let i in data) { if (+data[i].Index < 100 && data[i].Region !== '' && data[i].available === 'true') { list.push(data[i]); } } } else { list = data; } if (networkType !== 'all') { for (let i in list) { if (list[i].GroupType === (networkType === 'vpc' ? 'vpc' : 'class')) { newList.push(list[i]); } } } else { newList = list; } return newList; } /** * 分配地域 * @param {*} data */ function allocationRegion(data: Array) { let region: any = []; let list: any = []; for (let i in data) { let index = region.indexOf(data[i].Region); if (index === -1) { region.push(data[i].Region); list.push({ region: data[i].Region, all: [data[i]], classic: [], vpc: [], sort: +data[i].regionSort || 0 }); list[list.length - 1][data[i].GroupType === 'class' ? 'classic' : 'vpc'].push(data[i]); } else { list[index].all.push(data[i]); list[index][data[i].GroupType === 'class' ? 'classic' : 'vpc'].push(data[i]); } } return list; } /** * 分配节点 * @param {*} data */ function allocationZone(data: Array) { for (let i in data) { let classicZone = [], vpcZone = []; let classic: any = [], vpc: any = []; for (let j in data[i].classic) { let index = classicZone.indexOf(data[i].classic[j].Zone); if (index === -1) { // let sort = +data[i].classic[j].Zone.substring(data[i].region.length, data[i].classic[j].Zone.length); let sort = +data[i].classic[j].zoneSort || 1; classicZone.push(data[i].classic[j].Zone); classic.push({ zone: data[i].classic[j].Zone, data: [data[i].classic[j]], sort: sort, node: data[i].classic[j].StockHouseName }); } else { classic[index].data.push(data[i].classic[j]); } } for (let j in data[i].vpc) { let index = vpcZone.indexOf(data[i].vpc[j].Zone); if (index === -1) { // let sort = +data[i].vpc[j].Zone.substring(2, data[i].vpc[j].Zone.length); let sort = +data[i].vpc[j].zoneSort || 1; vpcZone.push(data[i].vpc[j].Zone); vpc.push({ zone: data[i].vpc[j].Zone, data: [data[i].vpc[j]], sort: sort, node: data[i].vpc[j].StockHouseName }); } else { vpc[index].data.push(data[i].vpc[j]); } } data[i].classic = classic; data[i].vpc = vpc; } return data; } /** * 过滤经典网络节点 * @param data * @returns data */ function filterClassic(data: Array) { return data.filter(item => item.vpc.length > 0); } /** * 节点排序 * @param {*} data */ function sortNode(data: Array) { data.sort((current, next) => { return next.sort - current.sort; }); for (let i in data) { data[i].classic.sort((current: any, next: any) => { return next.sort - current.sort; }); data[i].vpc.sort((current: any, next: any) => { return next.sort - current.sort; }); } return data; } /** * 重置 url */ function resetUrl() { let state = {title: '', url: location.href.split('?')[0]}; history.replaceState(state, '', state.url); } /* * 获取天数 * @param time {String} 时间 2021-03-22 19:00:00 * @param billing {String} 计费模式 -- ElasticByDay:弹性计费|Package:包年包月 */ function getDay(time: any, billing: any) { let day = 1; if (billing === 'ElasticByDay') { day = 1; } else { day = moment(time).diff(moment(), 'day'); if (day < 1) { day = 1; } } return day } /* * 获取天数(包含今天和到期那天) * @param time {String} 时间 2021-03-22 19:00:00 * @param billing {String} 计费模式 -- ElasticByDay:弹性计费|Package:包年包月 */ function getDifferDay(time: any, billing: any) { let day = 1; if (billing === 'ElasticByDay') { day = 1; } else { day = moment(time).diff(moment(), 'day') + 2; if (day < 1) { day = 1; } } return day } /** * 获取新到期时间 * @param expiredTime 到期时间 * @param type 增加模式 days:天数|months:月数 * @param count 数量 */ function getExpiredTime(expiredTime: any, type: any, count: any) { let time = "" if (moment(expiredTime).isBefore(moment())) { time = moment().add(type, count); } else { time = moment(expiredTime).add(type, count) } time = moment(time).format('YYYY-MM-DD HH:mm:ss'); return time } // 判断结束时间是否大于开始时间 无秒的时候 function checkDate(startTime: any, endTime: any, obj: any, $layer?: any) { if (startTime !== undefined && startTime != null && startTime !== '') { startTime += ' 00:00:00'; } if (endTime !== undefined && endTime != null && endTime !== '') { endTime += ' 23:59:59'; } const tem1 = new Date(startTime.replace(/-/g, '/')).getTime(); const tem2 = new Date(endTime.replace(/-/g, '/')).getTime(); if (tem1 !== NaN && tem2 !== NaN) { if (tem1 >= tem2) { $layer && $layer.msg('结束时间不能小于起始时间!', {type: 'error'}) obj.val(''); return false; } } return true; } // 判断结束时间是否大于开始时间 有秒的时候 function checkDateForShowSecond(startTime: any, endTime: any, obj: any, $layer?: any) { const tem1 = new Date(startTime.replace(/-/g, '/')).getTime(); const tem2 = new Date(endTime.replace(/-/g, '/')).getTime(); if (tem1 !== NaN && tem2 !== NaN) { if (tem1 >= tem2) { $layer && $layer.msg('结束时间不能小于起始时间!', {type: 'error'}) obj.val(''); return false; } } return true; } // 2012-10-10 12:11:01日期格式转换成时间戳s function datetimeToUnix(datetime: any) { // if (!datetime) { // return; // } let date = new Date(datetime.replace(/-/g, '/')); let unix = date.getTime(); return unix / 1000; } // 时间戳s转换成日期格式:2012-10-10 12:11:01 function unixToDatetime(unix: any) { let unixtimestamp = new Date(parseInt(unix, 10) * 1000); let year = unixtimestamp.getFullYear(); let month = '0' + (unixtimestamp.getMonth() + 1); let date = '0' + unixtimestamp.getDate(); let hour = '0' + unixtimestamp.getHours(); let minute = '0' + unixtimestamp.getMinutes(); let second = '0' + unixtimestamp.getSeconds(); return ( year + '-' + month.substring(month.length - 2, month.length) + '-' + date.substring(date.length - 2, date.length) + ' ' + hour.substring(hour.length - 2, hour.length) + ':' + minute.substring(minute.length - 2, minute.length) + ':' + second.substring(second.length - 2, second.length) ); } /**数组根据数组对象中的某个属性值进行排序的方法 * @param attr 排序的属性 如number属性 * @param rev true表示升序排列,false降序排序,默认升序排列 * */ function sortBy(attr: any, rev: any) { if (!rev == undefined) { rev = 1; } else { rev = rev ? 1 : -1; } return function (a: any, b: any) { a = a[attr]; b = b[attr]; if (a < b) { return rev * -1; } if (a > b) { return rev * 1; } return 0; }; } /** * 获取折扣 */ function getDiscount(list: any) { let discount: any = 1; if (list.length !== 0 && list[0].activity === 'UserRateActivity') { // vip折扣 discount = list[0].discount } return discount; } /**Vue防抖 */ function VueDebounce(fnName: string, time: number) { let timeout: any = null; return function (this: any, $event?: any) { if (timeout) { clearTimeout(timeout); } timeout = setTimeout(() => { this[fnName]($event); }, time); }; } function messageSetType(value: any, type: any = 'label') { let obj: any = { MESSAGE_CONFIG_DESTROY: {label: '销毁提醒', id: 'destroy'}, MESSAGE_CONFIG_EXPIRE: {label: '到期提醒', id: 'expire'}, MESSAGE_CONFIG_BALANCE_LESS: {label: "余额不足", id: 'balanceLess'}, MESSAGE_CONFIG_MONEY: {label: '余额预警', id: 'money'}, MESSAGE_CONFIG_RDS_STORAGE: {label: 'RDS存储容量提醒', id: 'rdsStorage'}, } return obj[value][type] } /* * 获取cpu可配置列表 * @params maxCpu * @params type : basic|highavailability|finance * by hyf */ function getRdsCpuList(type: string, maxCpu: any) { let cpuList = []; let cpuConfig = Constant.cpuRdsConfig[type]['cpu']; for (let i = 0; i < cpuConfig.length; i++) { if (maxCpu < cpuConfig[i]) { break; } cpuList.push(cpuConfig[i]); } return cpuList; } /**初始化列表 */ function initList(list: Array) { list.forEach((item: any) => { item.init = { status: { selected: false, btn: {}, } }; }) return list; } /* * @Description 获取Ram可配置列表 * @param cpu * @param maxRam 最大值 * by hyf */ function getRdsRamList(type: string, cpu: any, maxRam: any) { let ramList = []; let ramConfig = Constant.cpuRdsConfig[type]['ram'][cpu] || []; for (let i = 0; i < ramConfig.length; i++) { if (maxRam >= ramConfig[i]) { ramList.push(ramConfig[i]); } } return ramList; } // 正整数( 不含0 ) function isPositiveNum(number: any): boolean { const reg = /^\+?[1-9]\d*$/; return reg.test(number); } // RDS密码验证--以这个为准 function rdsPassWord(strPw: string): boolean { // const reg = /^[^\s\u4e00-\u9fa5]{8,32}$/g; // const reg = /^(?!^([0-9]+|[a-zA-Z]+|[!@#$%^&*()_+-=]+)$)(?![a-zA-Z0-9]+$)(?![a-z0-9!@#$%^&*()_+-=]+$)(?![A-Z0-9!@#$%^&*()_+-=]+$)[a-zA-Z0-9!@#$%^&*()_+-=]{8,32}$/g; const reg = /(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[\W])(?=.*[\S])^[0-9A-Za-z\S]{8,32}$/g; return reg.test(strPw); } /** * 获取规格 * configList 规格信息 * ecpPlatform 是否是模板ecp|tpl,如果是tpl需要过滤计算型规格 */ function getHouseConfig(configList: any, ecpPlatform?: string) { let newList: any = []; if (!configList) { return newList; } for (let key in configList) { console.log(key) let obj = {name: key, desition: '', poolList: []}; if (configList[key] && configList[key]['SpecsDesc']) { for (let deckey in configList[key]['SpecsDesc']) { if (deckey === 'CPU信息') { obj = { name: key, desition: configList[key]['SpecsDesc'][deckey] || '', poolList: configList[key]['PoolList'] || [] }; break; } } } // 如果是tpl模板推送主机,只能创建通用型,其他规格类型需要过滤掉 if (ecpPlatform !== 'tpl' || ecpPlatform === 'tpl' && key === '通用型') { newList.push(obj); } } // newList.sort(Common.sortBy('name', true)); let newArr = []; newArr = newList.sort(function (a: any, b: any) { return a.name.length > b.name.length ? 1 : -1; }); return newArr; } // 获取日志和数据使用量 function unitTransform(value: any, unit: any) { let val = !!value ? value + ' B' + unit : '无'; if (value >= 1024 && value / 1024 < 1024) { let tmp = (value / 1024).toFixed(2); val = !!tmp ? tmp + ' K' + unit : '无'; } else if (value / 1024 >= 1024 && value / 1024 / 1024 < 1024) { let tmp = (value / 1024 / 1024).toFixed(2); val = !!tmp ? tmp + ' M' + unit : '无'; } else if (value / 1024 / 1024 >= 1024) { let tmp = value / 1024 / 1024 / 1024; tmp = Math.floor(tmp * 100) / 100; val = !!tmp ? tmp + ' G' + unit : '无'; } return val; } // 去除字符串两边的空格 function trim(str: any) { if (typeof str === 'boolean' || typeof str === 'number') { return str; } return str.replace(/(^\s*)|(\s*$)/g, ''); } /** * 根据时间获取数据统计类型 * @param startTS 开始时间 2015-12-01 11:01:12 * @param endTS 结束时间 2015-12-01 11:01:12 */ function getTypeFromTime(startTS: any, endTS: any) { if (!startTS || !endTS) { return; } let startTSUnix = Date.parse(startTS.replace(/-/g, '/')) / 1000; let endTSUnix = Date.parse(endTS.replace(/-/g, '/')) / 1000; let startTSDate = new Date(startTS.replace(/-/g, '/')); let year = startTSDate.getFullYear(); let month = startTSDate.getMonth() + 1; let days = new Date(year, month, 0).getDate(); // 获取开始时间那个月有多少天 let opt = 'nearlyFourHours'; let dValue = endTSUnix - startTSUnix; if (dValue <= 4 * 60 * 60) { // 4小时以内的数据调用同最近4小时接口 opt = 'nearlyFourHours'; } else if (dValue > 4 * 60 * 60 && dValue <= 24 * 60 * 60) { // 4小时以上-- 24小时即1天以内的 的数据调用同最近1天接口 opt = 'nearlyDay'; } else if (dValue > 1 * 24 * 60 * 60 && dValue <= 7 * 24 * 60 * 60) { // 1天以上-- 7天以内的 的数据调用同最近1周接口 opt = 'nearlyWeek'; } else if (dValue > 7 * 24 * 60 * 60 && dValue <= days * 24 * 60 * 60) { // 7天以上-- 1个月以内的 的数据调用同最近1月接口 opt = 'nearlyMonth'; } else { // 超过1个月的调用1年的接口 opt = 'nearlyYear'; } return opt; } // 保留两位小数 function changeTwoDecimal(value: any): string { if (isNaN(value)) { console.error('changeTwoDecimal(value): isNaN(value) 为true '); return '0'; } return parseFloat(value).toFixed(2); } export default { getCookie, // 获取cookie setCookie, clearCookie, clearAllCookie, initializeNode, // 整理节点 getTime, deepClone, getUserToken, getUserID, getAdminUserID, resetUrl, getDay, getDifferDay, checkDate, checkDateForShowSecond, unixToDatetime, getExpiredTime, // 获取到期时间 datetimeToUnix, sortBy, uploadImgSecurity, getDiscount, VueDebounce, messageSetType, getRdsCpuList, getRdsRamList, isPositiveNum, rdsPassWord, initList, getHouseConfig, unitTransform, trim, getTypeFromTime, changeTwoDecimal, }