system.js 9.81 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
}

//取数组对象符合符合条件的行,返回是数组对象
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) {
    setInterval(() => {
        if (!thisInfo.sysData) return;
        thisInfo.sysTimeNum--;

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


// 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);
}


/**
 * 将数字四舍五入并保留指定位数的小数
 * @param {number} num 需要四舍五入的数字
 * @param {number} [decimalPlaces=2] 保留的小数位数,默认为2位
 * @returns {number} 四舍五入后的数字
 */
String.prototype.CellStyleFn = function (ele, val) {
    var eleList = document.querySelectorAll(ele);
    let color = ""
    for (let index = 1; index < eleList.length; index++) {
        const element = eleList[index];
        let val = element.textContent;
        color = ""
        if (val != null) val = parseFloat(val.replaceAll("%", "").replaceAll("-", ""))
        if (val > 2 && val <= 10) {
            color = "#1e9fff"
        } else if (val > 10 && val <= 20) {
            color = "#ffb800"
        } else if (val > 20) {
            color = "#ff5722"
        }
        if (color != "") element.style.color = color; // 设置文本颜色
    }
}


//cookie set ,read[value 是空 read]
String.prototype.cookie = function (key, value, options) {
    if (typeof value !== "undefined") { // 写入
        options = options || {};
        var cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value);

        // 确保 expires 是正数
        if (typeof options.expires === "number" && options.expires > 0) {
            var date = new Date();
            date.setDate(date.getDate() + options.expires);
            cookie += ";expires=" + date.toUTCString();
        }
        if (options.path) cookie += ";path=" + options.path;
        if (options.domain) cookie += ";domain=" + options.domain;
        if (options.secure) cookie += ";secure";

        // 确保 SameSite 属性值有效
        if (options.sameSite) {
            const validSameSite = ["Strict", "Lax", "None"];
            if (validSameSite.includes(options.sameSite)) {
                cookie += ";SameSite=" + options.sameSite;
            }
        }

        document.cookie = cookie;
        return; // 退出函数
    }

    // 读取
    var cookies = document.cookie.split(";").map(c => c.trim());
    for (var i = 0; i < cookies.length; i++) {
        var readCookie = cookies[i].split("=");
        var name = decodeURIComponent(readCookie.shift());
        if (name === key) return decodeURIComponent(readCookie.join("="));
    }
    return ""; // 返回空字符串而不是 null
};