各类封装整合

/**
 * 防抖函数
 */
export const debounce = (handler, delay) => {
    var timer = null;
    return function () {
        var _self = this, _arg = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            handler.apply(_self, _arg);
        }, delay);
    }
}

/**
 * 截断小数点两位后数字
 */
export const commonSubStr = (value) => {
    if (value != '' && value.substr(0, 1) == '.') {
        return value = "";
    }
    value = value.replace(/^0*(0\.|[1-9])/, '$1');//解决 粘贴不生效
    value = value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
    value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的     
    value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数     
    if (value.indexOf(".") < 0 && value != "") {//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
        if (value.substr(0, 1) == '0' && value.length == 2) {
            value = value.substr(1, value.length);
        }
    }
    return value
}
/**
 * 处理公共报文头
 */
export const handleParams = params => {
    let commonHeader = {};
    commonHeader['app'] = {
        token: '',
        deviceId: '',
        version: '',
        wifi: '',
        address: ''
    }
    commonHeader['themeId'] = '';//业务参数
    params['commonHeader'] = commonHeader;
    return params;
}
/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);
    }
    window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStore = name => {
    if (!name) return;
    return window.localStorage.getItem(name);
}
/**
 * 删除localStorage
 */
export const removeStore = name => {
    if (!name) return;
    window.localStorage.removeItem(name);
}
/**
 * 存储seesionstorage
 */
export const seesionStore = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);
    }
    sessionStorage.setItem(name, content);
}

/**
 * 获取seesionstorage
 */
export const getSeesionStore = name => {
    if (!name) return;
    return sessionStorage.getItem(name);
}
/**
 * 删除seesionstorage
 */
export const removeSeesionStore = name => {
    if (!name) return;
    sessionStorage.removeItem(name);
}


/**
 * 转换日期格式
 * @param format可以为 / ~ '' - 等字符或字符串
 */
export const transDate = (value, format) => {
    if (!value) {
        return ''
    }
    let time = new Date(value);
    let year = time.getFullYear();
    let month = time.getMonth() + 1 + '';
    let data = time.getDate() + '';
    if (month.length < 2) {
        month = '0' + month;
    }
    if (data.length < 2) {
        data = "0" + data
    }
    let newtime = year + `${format}` + month + `${format}` + data;
    return newtime;
}

/**
 * 获取当前日期:x年x月x日
 */
export const getNowDate = () => {
    let time = new Date();
    let year = time.getFullYear();
    let month = time.getMonth() + 1 + '';
    let data = time.getDate() + '';
    if (month.length < 2) {
        month = '0' + month;
    }
    if (data.length < 2) {
        data = "0" + data
    }
    let newtime = year + "年" + month + "月" + data + "日";
    return newtime
}
/**
 * 获取当前日期:x-x-x
 */
export const _getNowDate = () => {
    let time = new Date();
    let year = time.getFullYear();
    let month = time.getMonth() + 1 + '';
    let data = time.getDate() + '';
    if (month.length < 2) {
        month = '0' + month;
    }
    if (data.length < 2) {
        data = "0" + data
    }
    let newtime = year + "-" + month + "-" + data;
    return newtime
}
/**
 * 获取日期格式:x年x月
 */
export const getYearMonth = (value) => {
    let year = value.getFullYear();
    let month = value.getMonth() + 1 + '';
    if (month.length < 2) {
        month = '0' + month;
    }
    let newtime = year + "年" + month + "月";
    return newtime
}

/**
 * 一层对象克隆:等同于Object.assign({},obj)
 */
export const cloneObj = obj => {
    let newObj = JSON.parse(JSON.stringify(obj));
    return newObj
}

/**
 * 邮政编码校验
 * 返回值: true/false
 */
export const postCodeCheck = value => {
    let reg = /^[0-9]{6}$/;
    let result = reg.test(value);
    return result
}

/**
 * 手机号码校验
 * 返回值: true/false
 */
export const mobileCheck = value => {
    let reg = /^1[0-9][0-9]{9}$/;
    let result = reg.test(value);
    return result
}

/**
 * 电话号码校验
 * 返回值: true/false
 */
export const telephoneCheck = value => {
    let reg = /^0\d{2,3}-?\d{7,8}$/;
    let result = reg.test(value);
    return result
}

/**
 * 网址校验
 * 返回值: true/false
 */
export const urlCheck = value => {
    let str = `^((https|http|ftp|rtsp|mms)?://)`
        + `?(([0-9a-z_!~*'().&=+$%-]+:)?[0-9a-z_!~*'().&=+$%-]+@)?`//ftp的user@
        + `?(([0-9]{1,3}\.){3}[0-9]{1,3}`//IP形式的url
        + `|`//允许IP和DOMAIN
        + `([0-9a-z_!~*'()-]+\.)*`//域名-www
        + `([0-9a-z][0-9a-z]{0,61})?[0-9a-z]\.`//二级域名
        + `[a-z]{2,6})`//first level domain-.com or .museum
        + `(:[0-9]{1,4})?`//端口-:80
        + `((/?)|`// a slash isn't required if there is na file name
        + `(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$`;
    let reg = new RegExp(str);
    let result = reg.test(value);
    return result
}

/**
 * 传真号码校验
 * 返回值: true/false
 */
export const faxCheck = value => {
    let reg = /^(\d{3,4})?[-]?\d{7,8}$/;
    let result = reg.test(value);
    return result
}

/**
 * 邮箱校验
 * 返回值: true/false
 */
export const emailCheck = value => {
    let reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
    let result = reg.test(value);
    return result
}

/**
 * (1,2)位整数,(1,2)位小数:可参考自行添加对应整数位和小数位的校验
 * 返回值: true/false
 */
export const twoPoinTwo = value => {
    var reg = /^[0-9]{0,2}(\.[0-9]{0,2})?$/;
    var reg1 = /^[0-9]{0,16}$/
    let result = !((!reg.test(value)) && (!reg1.test(value)));
    return result
}

/**
 * 保留4位小数的数字:可参考自行添加对应小数位的校验
 * 返回值: true/false
 */
export const decimalNumFour = value => {
    let reg = /^[+|-]{0,1}[0-9]{0,20}(\.[0-9]{0,4})?$/;
    let result = reg.test(value);
    return result
}
//保留两位小数
export const decimalNumTwo = value => {
    let reg = /^[+|-]{0,1}[0-9]{0,20}(\.[0-9]{0,2})?$/;
    let result = reg.test(value);
    return result
}
/**
 * 不要特殊符号
 * 返回值: true/false
 */
export const specialSymbol = value => {
    let reg = /^[A-Za-z0-9|\u4e00-\u9fa5|\.|\:|\:]+$/;
    let result = reg.test(value || null);
    return result
}

/**
 * 身份证号校验
 * 返回值: true/false
 */
export const checkCard = value => {
    let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    let result = reg.test(value);
    return result
}

/**
 * 姓名中间不能有空格
 * 返回值: true/false
 */
export const checkName = value => {
    var reg = /^[\u4E00-\u9FA5]{1,6}$/;
    let result = reg.test(value);
    return result
}

/**
 * 检验纯数字
 * 返回值: true/false
 */
export const checkNumber = value => {
    var reg = /^[0-9]*$/;
    let result = reg.test(value);
    return result
}
/**
 * 检验纯数字(包含小数点)
 * 返回值: true/false
 */
export const checkDotNumber = value => {
    var reg = /([1-9]\d*\.?\d*)|(0\.\d*[1-9])/;
    let result = reg.test(value);
    return result
}
/**
 * 检验纯汉字
 * 返回值: true/false
 */
export const checkChinese = value => {
    var reg = /.*[\u4e00-\u9fa5]+.*$/;
    let result = reg.test(value);
    return result
}

/**
 * 检验英文和数字
 * 返回值: true/false
 */
export const checkEnAndNum = value => {
    var reg = /^[A-Za-z0-9]+$/;
    let result = reg.test(value || null);
    return result
}

/**
 * 检验正数
 * 返回值: true/false
 */
export const checkZnum = value => {
    var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
    let result = reg.test(value);
    return result
}

/**
 * 检验正整数(不包括小数)
 * 返回值: true/false
 */
export const checkZzNum = value => {
    var reg = /^[1-9]\d*$/;
    let result = reg.test(value);
    return result
}

/**
 * 仅支持英文
 * 返回值: true/false
 */
export const checkEn = value => {
    var reg = /^[A-Za-z0-9\_]+$/;
    let result = reg.test(value || null);
    return result
}

/**
 * 汉字--不能超过20个字符(可自行拓展)
 * 返回值: true/false
 */
export const checkChineseLenMax = value => {
    var reg = /^[\u4e00-\u9fa5]{0,20}$/;
    let result = reg.test(value);
    return result
}

/**
 * 汉字--不能低于20个字符(可自行拓展)
 * 返回值: true/false
 */
export const checkChineseLenMin = value => {
    var reg = /^[\u4e00-\u9fa5]{20,}$/;
    let result = reg.test(value);
    return result
}

//深复制方法
export const deepclone = (obj) => {
    var c = obj instanceof Array ? [] : {};
    for (var i in obj) if (obj.hasOwnProperty(i)) {
        var prop = obj[i];
        if (typeof prop == 'object') {
            if (prop instanceof Array) {
                c[i] = [];
                for (var j = 0; j < prop.length; j++) {
                    if (typeof prop[j] != 'object') {
                        c[i].push(prop[j]);
                    } else {
                        c[i].push(deepclone(prop[j]));
                    }
                }
            } else {
                c[i] = deepclone(prop);
            }
        } else {
            c[i] = prop;
        }
    }
    return c;
}


// 判断页面按钮是否应激活,btnJudge为按钮激活条件,status为按钮的状态
export const setBtnActive = (btnJudge) => {
    var status;
    if (btnJudge) {
        status = false;
    } else {
        status = true;
    }
    return status;
}
//比较时间
export const compareClock = (time1, time2) => {
    var start = time1.split(":")[0] + time1.split(":")[1]
    var end = time2.split(":")[0] + time2.split(":")[1]
    return parseInt(start) > parseInt(end)
}
//比较日期
export const compareDate = (time1, time2) => {
    var start = time1.split("-")[0] + time1.split("-")[1] + time1.split("-")[2];
    var end = time2.split("-")[0] + time2.split("-")[1] + time2.split("-")[2];
    return parseInt(start) > parseInt(end)
}
//时间转时间戳
export const timestamp = (time) => {
    var date = new Date(time);
    var timestamp = date.getTime();
    return timestamp;
}

// 数字转大写
export const chineseCapitals = (n) => {
    var fraction = ['角', '分'];
    var digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
    ];
    var unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
    ];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);
    var s = '';
    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);
    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    n = head + s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
    return head + s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
}

// 转货币加逗号格式并保留两位小数
export const formatCurrency = (num) => {
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if (num === 0 || num == "0") {
        return num = '0.00';
    }
    if (num) {
        num = num.toString();
        //如果num有‘+’或者‘-’,则获取它的符号
        var sign, unit;
        if (num.indexOf("+") > -1) {
            sign = '+';
            num = num.substring(1, num.length);
        } else if (num.indexOf("-") > -1) {
            sign = '-';
            num = num.substring(1, num.length);
        } else {
            sign = '';
        }
        //将num中的$,去掉,将num变成一个纯粹的数据格式字符串
        num = num.replace(/\$|\,/g, '');
        num = parseFloat(num).toFixed(2).toString();
        //如果num有单位'元',则获取它的单位
        if (num.indexOf("元") === num.length - 1) {
            unit = '元';
            num = num.substring(1, num.length - 1);
        } else {
            unit = '';
        }
        if (reg.test(num)) {
            //如果存在小数点,则获取数字的小数部分
            var cents = num.indexOf(".") > 0 ? num.substr(num.indexOf(".")) : '';
            cents = cents.length > 1 ? cents : '';//注意:这里如果是使用change方法不断的调用,小数是输入不了的
            //获取数字的整数数部分
            num = num.indexOf(".") > 0 ? num.substring(0, (num.indexOf("."))) : num;
            //针对整数部分进行格式化处理,这是此方法的核心,也是稍难理解的一个地方,逆向的来思考或者采用简单的事例来实现就容易多了
            /*
              也可以这样想象,现在有一串数字字符串在你面前,如果让你给他家千分位的逗号的话,你是怎么来思考和操作的?
              字符串长度为0/1/2/3时都不用添加
              字符串长度大于3的时候,从右往左数,有三位字符就加一个逗号,然后继续往前数,直到不到往前数少于三位字符为止
              */
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
                num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
            }
            //将数据(符号、整数部分、小数部分、单位)整体组合返回
            return (sign + num + cents + unit);
        } else {
            Toast('请输入正确的金额');
            return '';
        }
    }
}

//处理native路由传参(str转换成Array或object)
export const stringToArray = (val) => {
    if (val && (Object.prototype.toString.call(val) == '[object String]')) {
        val = val.replace(/\"|\'|\s/g, '').replace(/spersigns/g, '%')
            .replace(/\{/g, '{"').replace(/\}/g, '"}').replace(/\:/g, '":"').replace(/\,/g, '","')
            .replace(/\"{/g, '{').replace(/\}"/g, '}');
        val = JSON.parse(val)
    }
    return val;
}
//卡号添加掩码
export const acctHidden = (value) => {
    let txt = '';
    txt = value.substring(0, 4) + ' **** **** ' + value.substring(value.length - 4, value.length)
    return txt
}
//银行卡4位1个空格
export const bankStyle = (bankNo) => {
    let styleBank;  //格式化后的银行卡号

    if (bankNo) {
        let acctBankNo = bankNo.split('-')[0];   //主账号
        let acctNo = bankNo.split('-')[1] ? `-${bankNo.split('-')[1]}` : '';     //下挂编号
        let styleGroup = acctBankNo.length < 4 ? '' : acctBankNo.match(/\d{4}/g).join(' ');     //主账号隔4位分组
        let remainderLen = acctBankNo.length % 4;       //主账号除4剩余的位数
        styleBank = remainderLen === 0 ?
            `${styleGroup}${acctNo}` :
            `${styleGroup}${styleGroup ? ' ' : ''}${acctBankNo.substr(-remainderLen)}${acctNo}`;
    } else {
        styleBank = '';
    }

    return styleBank;
}

/**
 * 两个时间段相差的天数
 * sDate1和sDate2是2006-12-18格式
 */
export const datedifference = (sDate1, sDate2) => {
    var dateSpan, iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    dateSpan = Math.abs(dateSpan);
    iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays
};

/**
 * 转换日期格式 yyyymmdd 转化 yyyy-mm-dd
 * @param value yyyymmdd
 */
export const timeFormat = (value) => {
    if (!value) {
        return '';
    }
    let dateString = value.toString();
    let pattern = /(\d{4})(\d{2})(\d{2})/;
    let formatedDate = dateString.replace(pattern, "$1-$2-$3");
    return formatedDate;
}

/**
 * 转换日期格式 yyyymm 转化 yyyy-mm,  yyyy-mm转化yyyymm
 * @param value yyyymmdd
 */
export const transTimeFormat = (value, format) => {
    if (!value) {
        return '';
    }
    if (!format) {
        format = ''
    }
    let dateString = value.toString();
    let pattern = /(\d{4})(\d{2})/;
    let formatedDate = dateString.replace(pattern, '$1' + `${format}` + '$2');
    return formatedDate;
}

/**
 * 校验是否是正整数
 * @param {*} value 
 * return true 是正整数
 * return false 不是
 */
export const positiveInterger = (value) => {
    let positiveInt = /^[1-9]{1}[0-9]*$/
    if (positiveInt.test(value)) {
        return true;
    }
    return false;
}
//银行卡去除空格
export const clearSpace = (val) => {
    let bankNo = val.replace(/\s+/g, "");
    return bankNo;
}

/**
 * 转换日期格式
 * 2018-01- 或 时间戳 或 newdate ----》 201801 或 2018/01 或 2018~01 或 2018-01
 * @param format可以为 / ~ '' - 等字符或字符串
 */
export const transDateMonth = (value, format) => {
    if (!value) {
        return ''
    }
    if (!format) {
        format = ''
    }
    let time = new Date(value);
    let year = time.getFullYear();
    let month = time.getMonth() + 1 + '';
    if (month.length < 2) {
        month = '0' + month;
    }
    let newtime = year + `${format}` + month;
    return newtime;
}
//时间戳转日期(年月日)
export const transFormatDate = (value) => {
    if (value) {
        let str = value;
        let date = new Date(value);
        let y = date.getFullYear();
        let m = String(date.getMonth() + 1);
        m = Number(m) < 10 ? ('0' + m) : m;
        let d = String(date.getDate());
        d = Number(d) < 10 ? ('0' + d) : d;
        return y + '-' + m + '-' + d;
    } else {
        return '';
    }
}
/**
 * 判断对象是否为空
 * @param {*} obj 对象
 * @return true 空对象  false 不是空对象
 */
export const isNotObject = (obj) => {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
}

export const baiduMap = (bd_lat, bd_lon) => {
    var X_PI = Math.PI * 3000.0 / 180.0;
    var x = bd_lon, y = bd_lat;
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
    var gg_lng = z * Math.cos(theta) + 0.0055;
    var gg_lat = z * Math.sin(theta) + 0.0063;
    return { gg_lng, gg_lat };
}
/**
 *校验身份证
 */
export const idCard = (value) => {
    let idRule = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (idRule.test(value)) {
        return true;
    }
    return false;
}
/**
 *校验银行卡
 */
export const moneyCard = (value) => {
    let idRule = /(^(\d{9,20}[-])\d{3}$)|(^\d{9,20}$)/;
    if (idRule.test(value)) {
        return true;
    }
    return false;
}
/**
*上传图片压缩
*/
export const ImageCompress = (imgFile, imageSrc) => {
    let image = new Image();
    image.src = imageSrc;
    //获取图片原始长度
    image.onload = function () {
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        //瓦片canvas
        let tCanvas = document.createElement("canvas");
        let tctx = tCanvas.getContext("2d");
        let initSize = image.src.length;
        let width = image.width;
        let height = image.height;
        //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
        let ratio;
        if ((ratio = width * height / 4000000) > 1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        } else {
            ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        let count;
        if ((count = width * height / 1000000) > 1) {
            count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
            //            计算每块瓦片的宽和高
            let nw = ~~(width / count);
            let nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;
            let twidthArr = new Array();
            let theightArr = new Array();
            for (let i = 0; i < count; i++) {
                twidthArr[i] = function (num1) {
                    for (let j = 0; j < count; j++) {
                        theightArr[j] = function (num2) {
                            tctx.drawImage(
                                image,
                                num1 * nw * ratio,
                                num2 * nh * ratio,
                                nw * ratio,
                                nh * ratio,
                                0,
                                0,
                                nw,
                                nh
                            );
                            ctx.drawImage(tCanvas, num1 * nw, num2 * nh, nw, nh);
                        }(j);
                    }
                }(i);
            }
        } else {
            ctx.drawImage(image, 0, 0, width, height);
        }
        let saveImageUrl = canvas.toDataURL('image/jpeg', 0.7);
        let saveImage = dataURLtoFile(saveImageUrl);
        function dataURLtoFile(dataurl) {
            let arr = dataurl.split(',');
            let mime = arr[0].match(/:(.*?);/)[1];
            let suffix = mime.split('/')[1];
            let bstr = atob(arr[1]);
            let n = bstr.length;
            let u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime })
        }
        console.info(saveImage, "11111");
        return saveImage;
    }
}
/**
 * 处理事件状态方法
 * @param 入参
 */
export const handleEnterEvent = (isFromEvPram, msgtext) => {
    let param = {
        eventMessageId: isFromEvPram.eventMessageId,
        messageStatus: '1' // [1已读  0 未读] 
    }
    // feedBack: , // 1已反馈(已处理) 0 未反馈(未处理)
    if (isFromEvPram.feedBack) {
        param['feedBack'] = isFromEvPram.feedBack
    }
    rpcHttp(param, 'msgFeedBack', 'false', 'false').then(
        result => {
            if (result["code"] == 200) {
                if (result.data.isDeleted) {
                    let params = {
                        eventMessageId: isFromEvPram.eventMessageId
                    };
                    nativeHttp("eventRefresh", params).then(
                        res => {
                        }, err => {
                            Toast(err);
                        }
                    );
                }
                if (msgtext) {
                    Toast(msgtext);
                    setTimeout(() => {
                        AlipayJSBridge.call("prePage", {})
                    }, 1000);
                }
            } else {
                AlipayJSBridge.call('closeLoading', {});
                Toast(result.msg);
            }
        }, err => {
            AlipayJSBridge.call('closeLoading', {});
            Toast("系统异常,请重试");
        }
    );
}

你可能感兴趣的:(各类封装整合)