system.js 10.9 KB
// 根据线上线上配置获取URL 前缀
String.prototype.getUrlPrefix = function (thisInfo) {
    return window.baseOnLineOrOff ? thisInfo.baseUrlOnLine : thisInfo.baseUrlOff;
};

// 获取字符的长度(考虑中文字符)
String.prototype.getCharLength = function (char) {
    return /[\u4e00-\u9fa5]/.test(char) ? 2 : 1;
}

//字符串自动按长度添加</br>标签
String.prototype.insertStringEveryNChars = function (str, len, insertStr = "</br>") {
    var result = '';
    var currentCount = 0;
    for (var i = 0; i < str.length; i++) {
        var char = str[i];
        var charLength = ''.getCharLength(char);
        if (currentCount + charLength > len && i !== 0) {
            result += insertStr;
            currentCount = 0;
        }
        result += char;
        currentCount += charLength;
    }
    //#号隔开
    let dataList = result.split('#')
    //循环添加标签
    dataList.forEach((i, index) => {
        if (index % 2 == 0) {
            dataList.splice(2 * index, 0, '<span style="color:yellow">');
        } else {
            dataList.splice(2 * index, 0, '</span>');
        }
    })
    //数组转换字符串
    result = dataList.join('')
    return result;
}

/**
 * 开始时间和结束时间的天数
 */
String.prototype.enumerateDaysBetweenDayCount = function (thisInfo, startDay, endDay) {
    const startDate = thisInfo.$moment(startDay).format('YYYY-MM-DD');
    const endDate = thisInfo.$moment(endDay).format('YYYY-MM-DD');
    var day = thisInfo.$moment(endDate).diff(startDate, 'day')
    if (day == 0) return 1;
    return day;
}

//类型判断 来源uview 框架
String.prototype.typeX = function (obj) {
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

//获取url中指定参数值,没有值返回 null "".GetUrlParam("xxx")
String.prototype.GetUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
};

/**
 * 获取开始时间和结束时间区间段 ['2021-07-01', '2021-07-01'...., '2021-08-01']
 */
String.prototype.enumerateDaysBetweenDates = function (thisInfo, startDay, endDay, format = 'yyyy-MM-DD') {
    // 假定你已经保证了startDate 小于endDate,且二者不相等
    let daysList = []
    let sDate = thisInfo.$moment(startDay)
    let eDate = thisInfo.$moment(endDay)
    daysList.push(sDate.format(format))
    while (sDate.add(1, 'days').isBefore(eDate)) {
        // 注意这里add方法处理后sDate对象已经改变。
        daysList.push(sDate.format(format))
    }
    daysList.push(eDate.format(format))
    return daysList
}
/**
 * thisInfo: this api需要支持跨越
 * config:具体参数   
 * isUrlALL 为true  读取完整的地址  wms url默认是包含mobile 值的
 * isSuccessBefore:默认值 true  
 * isHanderAjaxSuccessActionLoad 默认值 false  head组件头部 传入 true
 * headers:WMS组是true,本地或者刘甫组 设置false  和跨域服务有关系
 * callBackFn:回调函数
 */
String.prototype.ajaxGet = function (thisInfo, config, callBackFn = null) {
    if (typeof thisInfo.$axios == "undefined") {
        alert("ajaxGet 方法 当前this 实例不存在$axios属性!");
        console.trace();
        return false;
    }
    //默认参数
    var opt = {
        headers: window.baseOnLineOrOff,
        logTitle: "服务器api接口数据Before",
        isUrlALL: false,
        isSuccessBefore: true,

        isHanderAjaxSuccessActionLoad: false
    };
    Object.assign(opt, config)
    let url = opt.urlSuffix;
    if (opt.isUrlALL && url.indexOf("http") == -1) {
        alert("ajaxGet 方法 参数【isUrlALL】为true 地址必须是全路径http开头,当前URL:" + url);
        return false;
    }
    if (!opt.isUrlALL) url = "".getUrlPrefix(thisInfo) + opt.urlSuffix;
    if (url == null) {
        alert("ajaxGet 方法 url 不能为空");
        console.trace();
        return false;
    }
    if (url.indexOf("undefined") > -1) {
        alert("ajaxGet url 地址错误,路径中存在undefined。" + url);
        return false;
    }
    if (!thisInfo.sysData) {
        alert(`ajaxGet sysData 配置错误:不能是空!`);
        return false;
    }

    if (url.split("//").length > 2) {
        alert(`ajaxGet url配置错误:存在连续个//【${url}】`);
        return false;
    }
    let tempTitle = opt.logTitle;

    thisInfo.$axios
        .get(url, {
            headers: opt.headers ? header : null,
            timeout: 10000
        })
        .then(res => {
            if (opt.isSuccessBefore) {
                var isSuccessBefore = "".ajaxSuccessBefore(res, (opt.logTitle = tempTitle));
                if (isSuccessBefore) {
                    //初始化页面
                    if (opt.initCallBackFn != null) opt.initCallBackFn()
                    return false;
                }
            }
            //动态赋值 api返回的数据在data或者result或者data.result,如果有其他情况需要单独在加
            let data = res.data.data;
            if (typeof data == "undefined" || data == null) data = res.result
            if (typeof data == "undefined" || data == null) data = res.data.result
            if ("".typeX(data) == "array") {
                thisInfo.sysData = data
            } else {
                let dataKeys = Object.keys(data);
                for (const key in dataKeys) {
                    if (!Object.hasOwnProperty.call(dataKeys, key)) continue
                    let keys = dataKeys[key];
                    let val = data[dataKeys[key]]
                    thisInfo.sysData[keys] = val
                }
            }
            if (opt.isHanderAjaxSuccessActionLoad) ''.ajaxSuccessActionLoad(res)
            if (callBackFn != null) callBackFn(res);
        })
        .catch(err => {
            "".ajaxError(err, url);
        });
};



//取数组对象符合符合条件的行,返回是数组对象
Array.prototype.GetArrValueRow = function (key, val) {
    return this.filter(item => item[key] == val);
};

/* 数组去掉重复*/
Array.prototype.unique5 = function () {
    var x = new Set(this);
    return [...x];
};

/* 数组对象去掉重复*/
Array.prototype.uniqueFunc = function (uniId) {
    const res = new Map();
    return this.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}

//判断元素是否在数组中 nowValue比较的值、field字段
Array.prototype.contains = function (nowValue, field) {
    for (var i = 0; i < this.length; i++) {
        if (nowValue == this[i][field]) {
            return true;
        }
    }
    return false;
};

//根据索引删除数组
Array.prototype.removeIndex = function (dx) {
    if (isNaN(dx) || dx > this.length) {
        return false;
    }
    this.splice(dx, 1);
};

//最大值
Array.prototype.max = function () {
    return Math.max.apply({}, this);
};

//最小值
Array.prototype.min = function () {
    return Math.min.apply({}, this);
};
//数组复制
Array.prototype.copy = function () {
    let [...tempArr] = this;
    return tempArr;
};

//数组对象取最小值
Array.prototype.getMinPropertyValue = function (property) {
    if (this.length === 0) {
        return null; // 数组为空时返回 null 或其他你认为合适的默认值
    }
    return this.reduce(function (min, obj) {
        return obj[property] < min ? obj[property] : min;
    }, Infinity);
}

//数组对象取最大值
Array.prototype.getMaxPropertyValue = function (property) {
    if (this.length === 0) {
        return null; // 数组为空时返回 null 或其他你认为合适的默认值
    }
    return this.reduce(function (max, obj) {
        return obj[property] > max ? obj[property] : max;
    }, -Infinity);
}

//85取 80,9n 取90 
String.prototype.roundDownToNearest = function (value, nearest) {
    return Math.floor(value / nearest) * nearest
};

//对象复制
String.prototype.copyObj = function (obj) {
    let { ...json2 } = obj;
    return json2;
};

// 调用案例 "".Log("xxx")
String.prototype.Log = function (str, title = "") {
    if (!window.baseOnLineOrOff) {
        if (title == "") {
            console.log(str);
        } else {
            console.log(title, str);
        }
    }
};


String.prototype.intInterval = function (thisInfo, sysTimeNum = 60, callBackFn = null) {
    const timer = setInterval(() => {
        if (!thisInfo.sysData) return;
        thisInfo.sysTimeNum--;

        if (thisInfo.sysTimeNum <= 0) {
            if (callBackFn != null) callBackFn();
            thisInfo.sysTimeNum = sysTimeNum;
            // 测试用 自动刷新
            //window.location.reload()
        }
    }, 1000);
    return timer;
};


// vue 表格  vue-seamless-scroll
String.prototype.tableScrollClassOption = function () {
    return {
        step: 0.1, //数值越大速度滚动越快
        limitMoveNum: 5, //开始无缝滚动的数据量  //this.fourDatata.length
        hoverStop: true, //是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, //开启数据实时监控刷新dom
        singleHeight: 0, //单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, //单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000, //单步运动停止的时间(默认值1000ms)
    };
};

/*时间格式化  使用场景:Date().format('yyyy-MM-dd hh:mm:ss')*/
Date.prototype.format = function (format) {
    var o = {
        'M+': this.getMonth() + 1, //month
        'd+': this.getDate(), //day
        'h+': this.getHours(), //hour
        'm+': this.getMinutes(), //minute
        's+': this.getSeconds(), //second
        'q+': Math.floor((this.getMonth() + 3) / 3), //quarter
        S: this.getMilliseconds(), //millisecond
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp('(' + k + ')').test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    return format;
};

/* element-ui ajax 读取数据loading 效果 */
String.prototype.uLoading = function (thisInfo, text = "拼命加载中") {
    const loading = thisInfo.$loading({
        lock: true,
        text: text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    return loading;
};

/**
 * 将数字四舍五入并保留指定位数的小数
 * @param {number} num 需要四舍五入的数字
 * @param {number} [decimalPlaces=2] 保留的小数位数,默认为2位
 * @returns {number} 四舍五入后的数字
 */
String.prototype.roundNumber = function (num, decimalPlaces = 2) {
    return Math.round(num * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
}

//2小时固定刷新一下页面,释放内存
setTimeout(() => window.location.reload(), 3600000); // 2小时 2 * 60 * 60 * 1000