import CONFIG from '../../config.js';
import serve from 'commonSrc/common/js/serve';
import {loginZhenai} from 'commonSrc/api/commonAPI';
/**
* 同步下载文件
* Created by Joetse on 2021-03-16.
*
*/
export function syncDownloadFile (path) {
const baseURL = CONFIG.API_PROTOCOL() + "//" + CONFIG.API_HOST_NAME();
const url = '' + baseURL + path;
window.open(url);
}
export function goAlbum (memberId) {
const album = document.querySelector('#albumUrl');
album ? album.parentNode.removeChild(album) : '';
serve.httpRequestMsg({memberId}, loginZhenai, (res) => {
const oHead = document.getElementsByTagName('HEAD').item(0);
const oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = `https://album.zhenai.com/return-cks?token=${res.data.token}`;
oScript.id = 'albumUrl';
oHead.appendChild(oScript);
window.open(`https://album.zhenai.com/u/${memberId}`);
});
}
/**
* 解析url参数
* Created by yi on 2016-12-28.
* @return Object {id:12334}
*/
export function urlParse () {
let url = window.location.search;
let obj = {};
let reg = /[?&][^?&]+=[^?&]]+/g;
let arr = url.match(reg);
// ['?id=123454','&a=b']
if (arr) {
arr.forEach((item) => {
let tempArr = item.substring(1).split('=');
let key = tempArr[0];
let val = tempArr[1];
obj[key] = val;
});
}
return {id: 123123};
}
/** 数组排序
*@param prop 属性字段
*@returns 排序后的数组 {Array}
*/
export function rank (prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) { //降序排列
return 1;
} else if (val1 > val2) {
return -1;
} else {
return 0;
}
};
}
/** 金额转千分位
*@param num (123456)
*@returns str (123,456.00)
*/
export function moneyFormatStr (_num) {
if (!!_num) {
var _tmp = _num + ""; //1,234,567
_tmp = _tmp.indexOf('.') > -1 ? _tmp : _tmp + '.00';
var _decimal = _tmp.split('.')[1];
_tmp = _tmp.split('.')[0];
var _leg = _tmp.length;
var start = _leg % 3;
var stack = [];
if (start > 0) {
stack.push(_tmp.substr(0, start));
}
for (var s = start; s < _leg; s += 3) {
stack.push(_tmp.substr(s, 3));
}
return stack.join(",") + '.' + _decimal;
} else {
return '0.00';
}
}
/** 千分位转金额
*@param str (123,456.00)
*@returns num (123456.00)
*/
export function moneyFormatNum (_num) {
if (!!_num) {
_num = _num + "";
_num = _num.replace(/,/g, '');
return parseFloat(_num).toFixed(2);
} else {
return '';
}
}
export function moneyFloatToInt (num) {
let reg = /^\d+(\.\d+)?$/;
return reg.test(num);
}
/**
* [getMonthDaysTimeRange 初始化30天的选择范围]
* @return {[Array]} [时间范围数组]
*/
export function getMonthDaysTimeRange () {
let now = new Date();
return [new Date(now.setHours(0, 0, 0, 0) - (30 * 24 * 60 * 60 * 1000)), new Date(now.setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)];
}
/**
* [getSevenDaysTimeRange 初始化七天的选择范围 20**-**-** 00:00:00 到 20**-**-** 23:59:59]
* @return {[Array]} [时间范围数组]
*/
export function getSevenDaysTimeRange () {
let now = new Date();
return [new Date(now.setHours(0, 0, 0, 0) - 604800000), new Date(now.setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)];
}
/**
* [getTodayTimeRange 初始化一天的选择范围 20**-**-** 00:00:00 到 20**-**-** 23:59:59]
* @return {[Array]} [时间范围数组]
*/
export function getTodayTimeRange () {
let now = new Date();
return [new Date(now.setHours(0, 0, 0, 0)), new Date(now.setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)];
}
/**
* [setSecondToEnd 时间选择框点击确定时结束时间格式化成 23:59:59]
* @param {[type]} time [选择的时间]
* @param {Function} cb [回调函数]
*/
export function setSecondToEnd (time, cb) {
if (time !== undefined && time !== '' && time !== null && (typeof time === 'string')) {
let arr = time.split(' - '),
startTime = arr[0],
endTime = arr[1],
endTimeArr = endTime.split(' '),
endTimeDay = endTimeArr[0],
endTimeSecond = endTimeArr[1];
if (endTimeSecond === '00:00' || endTimeSecond === '00:00:00') {
cb([new Date(startTime), new Date(endTimeDay + ' 23:59:59')]);
}
}
if (time === '') {
cb(getTodayTimeRange());
}
}
/**
* [_isEmptyObj 判断对象是否为空对象]
* @param {[type]} obj [需要判断的对象]
* @return {Boolean} [true就为空对象]
*/
export function isEmptyObj (obj) {
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
return false; //返回false,不为空对象
}
}
return true; //返回true,为空对象
}
/**
* 去空格
* @param {[type]} s [description]
* @return {[type]} [description]
*/
export function trim (s) {
if (typeof(s) === 'number' ) {
return s;
} else {
return s.replace(/(^\s*)|(\s*$)/g, "");
}
}
/**
* 成熟度显示统一处理
* @param {[type]} caseClass [description]
* @return {[type]} [description]
*/
function showCaseClass (caseClass) {
if (caseClass !== null) {
let CaseClassStr = caseClass + '';
if (typeof caseClass === 'number') {
if (caseClass === 512) {
return '-1类';
} else if (caseClass === 513) { // 红娘的vip跟进页12类会员
return '12类';
} else if (CaseClassStr.indexOf('.') !== -1) {
let LCaseClass = caseClass * 10;
return (LCaseClass % 100) / 10 + '类';
} else {
return (caseClass % 100) + '类';
}
}
} else {
return '未分类';
}
}
/**
* [_getCurrentSystem 获取当前系统值,与currentSystem不冲突,currentSystem用于vue文件的调用]
*/
export function getCurrentSystem () {
let currentsystem = location.pathname.split('/')[1];
// if (currentsystem === "szmatchmaker") {
// currentsystem = "matchmaker";
// }
return currentsystem;
}
/**
* [_filterName 将部门中的名称去除]
* @param {[String]} name [需要过滤的字符串] "深圳邀约三军二区(罗东秀)三部(严天恩)"
* @return {[String]} [过滤后的字符串] 深圳邀约三军二区
*/
function filterOrganName (name) {
return (typeof name === "string" ? name.replace(/\([^\)]*\)/g, "") : "");
}
function filterEmpty (value) {
return value !== null && value !== undefined ? value : '';
}
/**
* 生成唯一标识
* uuid(8, 2)
* uuid(8, 10)
* uuid(8, 16)
*/
function uuid (len, radix) {
let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
let uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) {
uuid[i] = chars[0 | Math.random()*radix];
}
} else {
// rfc4122, version 4 form
let r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
/**
* 添加千分分隔符
*/
export function comdify (n) {
let re = /\d{1,3}(?=(\d{3})+$)/g;
let n1 = n.replace(/^(\d+)((\.\d+)?)$/, function (s, s1, s2) {
return s1.replace(re, "$&,") + s2;
});
return n1;
}
/**
* 去除千分位中的 ‘,’
* @param {Number} num
*/
export function delcommafy (num) {//去除千分位中的‘,’
num = num.toString();
num = num.replace(/,/gi, '');
return num;
}
/**
* 获取数据范围的organ以及deptid值
* @param {*} actionCode
* @param {*} data
*/
export function getAuthRangeValueAndDeptIds (actionCode = '', data = []) {
let result = {rangeValue: 0, deptIds: ''};
data.forEach(item => {
if (item.actionCode === actionCode) {
if(!item.types) {
result = {rangeValue: '', deptIds: ''};
}
if (item.types && item.types.length > 0 && item.types[0].ranges[0]) {
result.rangeValue = item.types[0].ranges[0].rangeValue;
result.deptIds = item.types[0].ranges[0].deptIds;
}
}
});
return result;
}
/**
* 获取数据范围的organ
* @param {*} actionCode
* @param {*} data
*/
export function getAuthRangeValue (actionCode = '', data = []) {
let rangeValue = 0;
data.forEach(item => {
if (item.actionCode === actionCode) {
if (item.types.length > 0 && item.types[0].ranges[0]) {
rangeValue = item.types[0].ranges[0].rangeValue;
}
}
});
return rangeValue;
}
/**
* 获取同城门店数据范围的
* @param {*} actionCode
* @param {*} data
*/
export function getSameCityShop (actionCode = '', data = []) {
let deptIds = [];
data.forEach(item => {
if (item.actionCode === actionCode) {
if (item.types.length > 0 && item.types[0].ranges[0]) {
deptIds = item.types[0].ranges[0].deptIds;
}
}
});
if (deptIds && deptIds.length > 0) {
deptIds.forEach((item, index) => {
return deptIds[index] = Number(item)
})
}
return deptIds;
}
/**
* 获取同城门店数据范围的
* @param {*} actionCode
* @param {*} data
*/
export function getApiHost () {
let httpHost = CONFIG.API_PROTOCOL() + '//' + CONFIG.API_HOST_NAME();
return httpHost;
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
export const formatDate = (date, symbol = '-') => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
return [year, month, day].map(formatNumber).join(symbol)
}
export const getDateDiff = (startDate, endDate) => {
startDate = formatDate(new Date(startDate))
endDate = formatDate(new Date(endDate))
const startTime = new Date(Date.parse(startDate.replace(/-/g, '/'))).getTime()
const endTime = new Date(Date.parse(endDate.replace(/-/g, '/'))).getTime()
const dates = Math.floor(startTime - endTime) / (1000 * 60 * 60 * 24)
return Math.abs(dates)
}
/**
* 防抖
* @param func
* @param wait
* @param immediate
* @returns {function(...[*]=): *}
*/
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
}
}
// 节流
export function throttle (func, delay) {
let prev = Date.now()
return function () {
const context = this
let args = arguments
let now = Date.now()
if (now - prev >= delay) {
func.apply(context, args)
prev = Date.now()
}
}
}
export function isAssetTypeAnVideo (filePath) {
let index = filePath.lastIndexOf('.')
let ext = filePath.substr(index + 1)
return ['mp4', 'mov', 'm4v'].indexOf(ext.toLowerCase()) !== -1
}
/**
* @param {blob} data
* @description 使用 axios 从接口中返回 data 时,发起请求时需要配置 responseType: blob
*/
export function downloadFileByBlob (data, {type = 'text', filename = 'untitle.txt'}) {
const url = window.URL.createObjectURL(new Blob([data], {type}));
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
export default {
urlParse: urlParse,
rank: rank,
moneyFormatStr: moneyFormatStr,
moneyFormatNum: moneyFormatNum,
moneyFloatToInt: moneyFloatToInt,
getMonthDaysTimeRange: getMonthDaysTimeRange,
getSevenDaysTimeRange: getSevenDaysTimeRange,
getTodayTimeRange: getTodayTimeRange,
setSecondToEnd: setSecondToEnd,
isEmptyObj: isEmptyObj,
trim: trim,
getCurrentSystem: getCurrentSystem,
showCaseClass: showCaseClass,
filterOrganName: filterOrganName,
filterEmpty: filterEmpty,
uuid: uuid,
comdify: comdify,
delcommafy: delcommafy,
getSameCityShop: getSameCityShop,
getAuthRangeValueAndDeptIds,
getAuthRangeValue: getAuthRangeValue,
getApiHost: getApiHost,
getDateDiff,
formatDate,
debounce,
throttle,
isAssetTypeAnVideo,
downloadFileByBlob
};