import { parse } from 'qs'; import moment from 'moment'; // import { EXPIRYTIME } from '@/config'; import { nameRegexp, phoneRegexp } from '@/utils/regexp'; import { reverse, map, minBy, maxBy, get } from 'lodash'; // 按日期筛选的默认时间 export const defaultQueryDate = `${moment() .subtract(3, 'days') .startOf('day') .valueOf()},${moment() .endOf('day') .valueOf()}`; // 获取查询参数 export function getPageQuery(): any { return parse(window.location.href.split('?')[1]); } export const loadScript = (url: string) => { return new Promise((resolve, reject) => { let script = window.document.createElement('script'); script.async = true; script.src = url; script.onload = function() { resolve(); }; script.onerror = function() { // eslint-disable-next-line reject(); }; window.document.head.appendChild(script); }); }; export function formatDate(date: any) { return moment(parseInt(date, 0)).format('YYYY-MM-DD'); } export function formatDateTime(date: any) { return moment(parseInt(date, 0)).format('YYYY-MM-DD HH:mm'); } export function formatTimeFrame(start: number, end: number, format?: string) { const dateFormat = format || 'YYYY-MM-D HH:mm'; return `${start ? moment(start).format(dateFormat) : '-'} ~ ${ end ? moment(end).format(dateFormat) : '-' }`; } export function formatTime(time = 0): string { if (time >= 3600 * 24) { return `${parseInt((time / (3600 * 24)).toString(), 10)}天`; } else if (time >= 3600) { return `${parseInt((time / 3600).toString(), 10)}小时`; } else { return `${parseInt((time / 60).toString(), 10)}分`; } } // 计算服务年限 export const durationTime = (startTime: number, endTime: number) => { if (!startTime || !endTime) { return; } const start = moment(startTime); const end = moment(endTime); const date = moment.duration(end.diff(start)); let day = ''; let month = ''; let year = ''; if (date.years()) { year = `${date.years()}年`; } if (date.months()) { month = `${date.months()}月`; } let days = date.days(); const dayRem = date.hours() || date.minutes() || date.seconds() || date.milliseconds(); if (dayRem) { days += 1; } if (days) { day = `${days}天`; } return `${year}${month}${day}`; }; export function formatNumber(count: number) { let list = reverse(count.toString().split('')); if (list.length < 4) return count; const length = list.length; return reverse( map(list, (char: string, idx: number) => { return (idx + 1) % 3 === 0 && idx !== 0 && idx !== length ? `,${char}` : char; }), ); } export function calcStringLength(str: string) { // 获得字符串实际长度,中文2,英文1 // 要获得长度的字符串 let realLength = 0; let len = str.length; let charCode = -1; for (let i = 0; i < len; i++) { charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) realLength += 1; else realLength += 2; } return realLength; } export function formatPhoneNumber(phone: string) { return (phone || '').replace(/^\+86/, ''); } export function checkNickname(rule, value) { if (value && !nameRegexp.test(value)) { // eslint-disable-next-line return Promise.reject('只能是数字、字母、中文、下划线'); } else { return Promise.resolve(); } } export function checkAge(rule, value) { if (value && (value < 18 || value > 75)) { // eslint-disable-next-line return Promise.reject('年龄需要在 18~75 之间'); } return Promise.resolve(); } export function checkRegion(rule, value) { if (value?.province && value.city && value.area) { return Promise.resolve(); } // eslint-disable-next-line return Promise.reject('所在地址不能为空'); } // export function getExpiryTime(time: any): number { // return moment(time || EXPIRYTIME) // .endOf('day') // .valueOf(); // } export function getPrefix(str: string, length: number) { const limit = length || 16; return str.length > limit ? str.slice(0, limit) + '...' : str; } export function checkMobile(rule: object, value: string) { if (value && !phoneRegexp.test(value)) { // eslint-disable-next-line return Promise.reject('手机号码格式不正确'); } else { return Promise.resolve(); } } // 格式化周期时间 export function formatIntervalTime(interval?: number, unit?: string): string { if (!interval) { return '0秒'; } let time = ''; // @ts-ignore const duration = moment.duration(interval, unit || 'seconds'); const seconds = duration.seconds(); const minutes = duration.minutes(); const hours = duration.hours(); const days = duration.days(); if (days) { time += `${days}天`; } if (hours) { time += `${hours}小时`; } if (minutes) { time += `${minutes}分钟`; } if (seconds) { time += `${seconds}秒`; } return time; } /** * 获取图片的高宽 * @param file */ export function getImageWH(file: any): Promise { return new Promise(resolve => { // 转码为base64 let base64 = ''; let width = 0; let height = 0; let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(evt: any) { base64 = evt.target.result; const img = new Image(); img.src = base64; if (img.complete) { width = img.width; height = img.height; resolve({ width, height }); } else { img.onload = function() { width = img.width; height = img.height; resolve({ width, height }); }; } }; }); } /** * 获取预警到现在的时间距离 * @param time */ export function getTimeGap(time: number) { const current = moment().valueOf(); let timeGap = current - time; if (timeGap < 60 * 1000) return '刚刚'; else if (timeGap < 60 * 60 * 1000) return `${Math.ceil(timeGap / (60 * 1000))}分钟前`; else if (timeGap < 24 * 60 * 60 * 1000 && timeGap > 60 * 60 * 1000) return `${Math.ceil(timeGap / (60 * 60 * 1000))}小时前`; else if (timeGap < 365 * 24 * 60 * 60 * 1000) return moment(time).format('MM-DD HH:mm:ss'); else return moment(time).format('YYYY-MM-DD HH:mm:ss'); } // 计算y轴最小值 export const calcYaxis = (data: any) => { // 计算y轴最小值 const minTemp = minBy(data, 'value'); const maxTemp = maxBy(data, 'value'); let yAxisMin = minTemp ? minTemp.value : 0; let yAxisMax = maxTemp ? maxTemp.value : 0; if (yAxisMin > 0 && yAxisMax > 0) { yAxisMin = 0; } else if (yAxisMin < 0 && yAxisMax < 0) { yAxisMax = 0; } return { yAxisMin, yAxisMax }; }; /** * 生成随机字符串 * @param len * @param type * @returns {string} */ const DEFAULT_LENGTH = 12; export function randomString(len = DEFAULT_LENGTH, type?: string) { // eslint-disable-next-line const space = { password: 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678', letter: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', complex: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789();.#-{}[]!,_:@?*&', hex: '1234567890ABCDEF', number: '1234567890', }; const $chars = space[type || 'letter']; const maxPos = $chars.length; let pwd = ''; for (let i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } export function getUrlParams(name: string, search: string) { const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`); const r = search.substr(1).match(reg); if (r != null) return decodeURIComponent(r[2]); return undefined; } export function getAgeByBirthday(strBirthday: string) { let returnAge: number; const birthYear = strBirthday.slice(0, 4); const birthMonth = strBirthday.slice(4, 6); const birthDay = strBirthday.slice(6); const d = new Date(); const nowYear: number = d.getFullYear(); const nowMonth = d.getMonth() + 1; const nowDay = d.getDate(); if (String(nowYear) === String(birthYear)) { returnAge = 0; //同年 则为0岁 } else { var ageDiff = nowYear - Number(birthYear); //年之差 if (ageDiff > 0) { if (Number(nowMonth) === Number(birthMonth)) { let dayDiff = nowDay - Number(birthDay); //日之差 if (dayDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff; } } else { var monthDiff = nowMonth - Number(birthMonth); //月之差 if (monthDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff; } } } else { returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天 } } return returnAge; //返回周岁年龄 } export function getBirthdayFromIdCard(idCard: string) { let birthday = ''; if (idCard != null && idCard != '') { if (idCard.length == 15) { birthday = '19' + idCard.substr(6, 6); } else if (idCard.length == 18) { birthday = idCard.substr(6, 8); } birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-'); } return birthday; } // Google Analysis export function GoogleAnalysisSetting(me: any, merchant: any) { // if (!me || !merchant) return; // const { nickname, mobile, id } = me; // const { name } = merchant; // gtag('set', { user_id: id }); // 登录成功后,设置为用户ID // gtag('config', 'UA-170491696-1', { // custom_map: { // dimension1: mobile, //登录成功后替换为用户的手机号码 // dimension2: nickname, //登录成功后替换为用户名称 // dimension3: name //登录成功后替换为项目名称,当切换项目时,需要重新赋值 // } // }); } /** * url query参数转换成对象 * @param url */ export function queryToObj(url: string): any { const query = url.split('?')[1]; let result = {}; if (!query) return result; query.split('&').forEach(item => { const q = item.split('='); result[q[0]] = q[1]; }); return result; } // 获取摄像机旋转角度 export const getCameraRotate = (orientations: number) => { switch (orientations) { case 1: // 正东 return 270; case 2: // 正南 return 0; case 3: // 正西 return 90; case 4: // 正北 return 180; case 5: // 东南 return 315; case 6: // 东北 return 225; case 7: // 西南 return 45; case 8: // 西北 return 135; default: return 0; } }; export const getAge = (date: number) => { return new Date().getFullYear() - new Date(date).getFullYear(); }; export function formatCash(num: number) { //不考虑入参的判断 return String(num) .split('') .reverse() .reduce((pre, next, index) => { return index % 3 ? next + '' + pre : next + ',' + pre; }); }