vue.mixin.js

(function(){
	pageLoadCallback: function () {
            var _this = this;
            if (!window.app || window.app.isLocal !== true && !Object.isFunction(this.pageLoad)) {
                return;
            }
            setTimeout(function () {
                var params = {};
                var url = new URL(window.location.href);
                url.searchParams.forEach(function (value, key) {
                    params[key] = value;
                });
                _this.pageLoad.apply(_this, [params]);
            }, 0);
        },
});
(function () {
    Object.isTypeOf = function (object, type) {
        return typeof(object) === type;
    };
    Object.isUndefined = function (object) {
        return typeof(object) === "undefined";
    };
    Object.isBoolean = function (object) {
        return typeof(object) === "boolean";
    };
    Object.isNumber = function (object) {
        return typeof(object) === "number";
    };
    Object.isString = function (object) {
        return typeof(object) === "string";
    };
    Object.isFunction = function (object) {
        return typeof(object) === "function";
    };
    Object.isObject = function (object) {
        return typeof(object) === "object";
    };
    Object.isNotNullObject = function (object) {
        return typeof(object) === "object" && object !== null;
    };
    Object.isNull = function (object) {
        return object === null;
    };
    Object.isArray = function (object) {
        return Array.isArray(object);
    };
    Object.methods = function (object) {
        var methods = [];
        for (var prop in object) {
            if (object[prop] && object[prop].constructor &&
                object[prop].call && object[prop].apply) {
                methods.push(prop);
            }
        }
        return methods;
    };
    if (typeof Object.assign != 'function') {
        // Must be writable: true, enumerable: false, configurable: true
        Object.defineProperty(Object, "assign", {
            value: function assign(target, varArgs) { // .length of function
                // is 2
                'use strict';
                if (target == null) { // TypeError if undefined or null
                    throw new TypeError('Cannot convert undefined or null to object');
                }
                var to = Object(target);
                for (var index = 1; index < arguments.length; index++) {
                    var nextSource = arguments[index];

                    if (nextSource != null) { // Skip over if undefined or
                        // null
                        for (var nextKey in nextSource) {
                            // Avoid bugs when hasOwnProperty is shadowed
                            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                                to[nextKey] = nextSource[nextKey];
                            }
                        }
                    }
                }
                return to;
            },
            writable: true,
            configurable: true
        });
    }
    Date.prototype.format = function (fmt) { // author: meizz
        var o = {
            "M+": this.getMonth() + 1, // 月份
            "d+": this.getDate(), // 日
            "h+": this.getHours(), // 小时
            "m+": this.getMinutes(), // 分
            "s+": this.getSeconds(), // 秒
            "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
            "S": this.getMilliseconds() // 毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
        }
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k])
                    : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        return fmt;
    };
    Date.isDate = function (date) {
        return (date instanceof Date && !isNaN(date.valueOf()));
    };
    Date.format = function (jsondate, fmt) {
        if (isNaN(parseInt(jsondate))) {
            return "--";
        }
        return new Date(jsondate).format(fmt);
    };
    Date.nowString = function (radix) {
        var _radis = parseInt(radix);
        if (isNaN(_radis)) {
            _radis = 36;
        }
        return new Date().getTime().toString(_radis);
    };
    /**
     * 数字检查
     *
     * @param value
     * @param min
     *            option
     * @param max
     *            option
     */
    Number.check = function (value, min, max) {
        var ret = false;
        var _value = parseFloat(value);
        if (isNaN(_value) || _value != value) {
            return ret;
        }
        ret = true;
        var _min = parseFloat(min);
        var _max = parseFloat(max);
        if (!isNaN(_min)) {
            if (_min.toString() !== min.toString()) {
                return false;
            }
            ret = _value >= _min;
            if (!ret) {
                return false;
            }
        }
        if (!isNaN(_max)) {
            if (_max.toString() !== max.toString()) {
                return false;
            }
            ret = _value <= _max;
        }
        return ret;
    };
    Number.isNumeric = function (value) {
        return !isNaN(parseFloat(value)) && !isNaN(value - parseFloat(value));
    };
    Number.parseIntWithDefault = function (value, vdefault) {
        vdefault = parseInt(vdefault);
        if (isNaN(vdefault)) {
            vdefault = 0;
        }
        value = parseInt(value);
        if (isNaN(value)) {
            value = vdefault;
        }
        return value;
    };
    Number.parseIntRate = function (value, rate) {
        if (!Number.isNumeric(value)) {
            return 0;
        }
        if (!Number.isNumeric(rate)) {
            rate = 1;
        }
        return parseInt((value * rate).toPrecision(12));
    };
    Number.parseIntRatio = function (value, ratio) {
        var _ratio = Number.parseIntWithDefault(ratio, 0);
        if (_ratio === 0) {
            throw new Error("ratio can't be zero!!");
        }
        return parseInt((value / _ratio).toPrecision(12));
    };
    Number.parseFloatWithDefault = function (value, vdefault, toFixed) {
        vdefault = parseFloat(vdefault);
        if (isNaN(vdefault)) {
            vdefault = 0;
        }
        toFixed = parseInt(toFixed);
        if (isNaN(toFixed)) {
            toFixed = -1;
        }
        value = parseFloat(value);
        if (isNaN(value)) {
            value = vdefault;
        }
        value = value.toPrecision(12);
        if (toFixed > -1) {
            return parseFloat(parseFloat(value).toPrecision(toFixed));
        }
        return value;
    };
    Number.pad = function (number, len) {
        return (Array(len).join(0) + number).slice(-len);
    };
    Number.formatPenny = function (value) {
        value = parseFloat(value);
        if (isNaN(value)) {
            value = 0;
        }
        return Number(value / 100).toFixed(2);
    };
    Number.formatRate = function (value, rate, toFixed) {
        value = parseFloat(value);
        rate = parseInt(rate);
        toFixed = parseInt(toFixed);
        if (isNaN(toFixed)) {
            toFixed = 2;
        }
        if (isNaN(value)) {
            return "--";
        }
        if (isNaN(rate)) {
            rate = 1;
        }
        if (value % rate === 0) {
            return Number(value / rate).toFixed(0);
        }
        return Number(value / rate).toFixed(toFixed);
    };
    String.isEmpty = function (value) {
        return !value || value.toString().trim().length === 0;
    };
    String.postMessageKey = function (key) {
        var nowstr = Date.nowString();
        if (String.isEmpty(key)) {
            return nowstr;
        }
        return key.toString().concat(".").concat(nowstr);
    };
    String.isMobile = function (mobile) {
        var reg = /^1[0-9]{10}$/;
        return reg.test(mobile);
    };
    String.isEmail = function (email) {
        var reg = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
        return reg.test(email);
    };
    String.isUrl = function (url) {
        var reg = /(http[s]?):\/\/[^\/\.]+?\..+\w$/i;
        return reg.test(url);
    };
    String.isIDCard = function (value) {
        if (!IDValidator) {
            throw new Error("need IDValidator support");
        }
        return new IDValidator().isValid(value);
    };

    if (!Array.isArray) {
        Array.isArray = function (arg) {
            return Object.prototype.toString.call(arg) === '[object Array]';
        };
    }
    Array.isEmpty = function (array) {
        return !array || !Array.isArray(array) || array.length === 0;
    };
    Array.deleteElement = function (array, callback) {
        if (!Array.isArray(array) || array.length === 0) {
            return array;
        }
        if (!Object.isTypeOf(callback, "function")) {
            throw new Error("callback can not be null");
        }
        var _newList = [];
        array.forEach(function (item, index) {
            var _match = callback.apply(null, [item, index]);
            if (_match === true) {
                return;
            }
            _newList.push(item);
        });
        return _newList;
    };
})();

window.pad = function (num, n) {
    var len = num.toString().length;
    while (len < n) {
        num = "0" + num;
        len++;
    }
    return num;
}
window.fileServer = function (imageId, defaultImg) {
    if (String.isEmpty(imageId)) {
        if (String.isEmpty(defaultImg)) {
            return "../images/common/placeholder.png";
        }
        return defaultImg;
    }
    return window.vApp.serverUrl + "/p/file/get_file/" + imageId;
};
window.attachServer = function (imageId, defaultImg) {
    if (String.isEmpty(imageId)) {
        if (String.isEmpty(defaultImg)) {
            return "../images/common/placeholder.png";
        }
        return defaultImg;
    }
    return window.vApp.serverUrl + "/p/file/attach/" + imageId;
};
//
// Vue.config.productionTip = true;
// page基类
var pageMixin = {
    data: {
        pageArgs: {},

    },
    created: function () {

    },
    mounted: function () {
        if (window.pageArgs) {
            this.pageArgs = window.pageArgs;
        }
        document.getElementById("page").classList.add("page-show");
        if (Object.isFunction(window.vApp.pageLoadCallback)) {
            window.vApp.pageLoadCallback.apply(this);
        }
    },
    methods: {
        getPlatform: function (callback) {
            app.getSystemInfo({
                callback: function (res) {
                    if (Array.isEmpty(res.platform) && String.isEmpty(res.platform[0])) {
                        return;
                    }
                    if (Object.isFunction(callback)) {
                        callback.apply(null, [res.platform[0].toLowerCase()]);
                    }
                }
            });
        },
        fileServer: function (imageId, defaultImg) {
            return window.fileServer(imageId, defaultImg);
        },
        attachServer: function (imageId, defaultImg) {
            return window.attachServer(imageId, defaultImg);
        },
        checkLogin: function (callback) {
            var _this = this;
            window.vApp.getToken(function (res) {
                if (String.isEmpty(res.value)) {
                    _this.showLogin();
                    return;
                }
                if (Object.isFunction(callback)) {
                    callback.apply(_this)
                }
            });
        },
        showLogin: function () {
            app.presentPage({
                path: 'pages/login.html',
                type: 'fullScreen',
                navigate: true,
                tapDismiss: false,
                singleton: true
            });
        },
        showAddressPickerView: function () {
            app.presentPage({
                path: 'pages/region-choose.html',
                type: 'bottomHalf'
            });
        },
        loadAccountByToken: function (callback) {
            var _this = this;
            invokePost("BizAction.getHhtsAccountByToken", [], function (result) {
                if (!Object.isNotNullObject(result)) {
                    return;
                }
                if (Object.isFunction(callback)) {
                    callback.apply(_this, [result])
                }
            });
        },
        loadBaseData: function () {
            invokePost("BizAction.getBaseData", [], function (result) {
                var dataDictList = result.dataDictList;
                if (Array.isEmpty(dataDictList)) {
                    dataDictList = [];
                }
                var dataDicts = {};
                dataDictList.forEach(function (item) {
                    if (String.isEmpty(item.categoryCode)) {
                        return;
                    }
                    var key = item.categoryCode.replace(".", "_");
                    var dataDict = dataDicts[key];
                    if (!dataDict) {
                        dataDict = {
                            key: key,
                            list: []
                        }
                    }
                    dataDict.list.push(item);
                    dataDicts[key] = dataDict;
                });
                for (var key in dataDicts) {
                    if (!dataDicts.hasOwnProperty(key)) {
                        return;
                    }
                    app.setStorage({
                        key: [keys.system.dataDict.code, key].join("."),
                        value: JSON.stringify(dataDicts[key])
                    });
                }
                app.postMessage({
                    key: keys.system.dataDict.loaded
                });
            });
        },
        loadDataDicts: function (code, callback) {
            if (String.isEmpty(code) && Object.isFunction(callback)) {
                callback.apply(this, [[]]);
                return;
            }
            code = code.replace(".", "_");
            app.getStorage({
                key: [keys.system.dataDict.code, code].join("."),
                callback: function (res) {
                    var result = {
                        list: []
                    };
                    try {
                        result = JSON.parse(res.value);
                    } catch (e) {

                    }
                    if (!result || Array.isEmpty(result.list)) {
                        if (Object.isFunction(callback)) {
                            callback.apply(this, [[]]);
                            return;
                        }
                    }
                    if (Object.isFunction(callback)) {
                        callback.apply(this, [result.list]);
                    }
                }
            })
        },
        sendVerifyCode: function (mobileNo, callback) {
            if (!String.isMobile(mobileNo)) {
                app.showToast("请输入手机号");
                return;
            }
            var _this = this;
            invokePost("BizAction.sendVerifyCode", [mobileNo], function (result) {
                if (Object.isFunction(callback)) {
                    callback.apply(_this, [result])
                }
            });
        },
        downloadFile: function (url, file, callback) {
            app.downloadFile({
                url: url,
                path: file,
                callback: function (res) {
                    var _path = res.path;
                    if (String.isEmpty(_path)) {
                        return;
                    }
                    if (Object.isFunction(callback)) {
                        callback.apply(this, [res]);
                    }
                    app.log("downloadFile return:" + JSON.stringify(res));
                }
            });
        },
        appZipName: function (versionId) {
            if (!Number.isNumeric(versionId)) {
                return;
            }
            return ["app", "v", versionId, "zip"].join(".");
        },
        downloadVersionFile: function (result) {
            var _this = this;
            if (!Object.isNotNullObject(result)) {
                return;
            }
            var _attachId = result.downloadUrl;
            if (String.isEmpty(_attachId)) {
                return;
            }
            var _file = _this.appZipName(result.versionId);
            if (String.isEmpty(_file)) {
                return;
            }
            var url = [window.vApp.serverUrl, '/p/file/get_file/', _attachId].join("");
            app.isFileExists({
                path: _file,
                callback: function (existRes) {
                    if (existRes.exist) {
                        app.log("FileExists :[" + _file + "] exist");
                        return;
                    }
                    app.downloadFile({
                        url: url,
                        path: _file,
                        callback: function (downloadRes) {
                            var _path = downloadRes.path;
                            if (String.isEmpty(_path)) {
                                return;
                            }
                            app.log("downloadVersionFile return:" + JSON.stringify(downloadRes));
                        }
                    });
                }
            });
        },
        startCheckVersion: function () {
            this.getCurrentAppVersion(function (version) {
                window.page.getLatestAppVersion(version, function (result) {
                    if (!Object.isNotNullObject(result)) {
                        window.page.checkNewVersion();
                        return;
                    }
                    app.log("发现新版本,检查本地是否已有更新包:[" + result.versionId + "]");
                    var _file = window.page.appZipName(result.versionId);
                    if (String.isEmpty(_file)) {
                        window.page.checkNewVersion();
                        return;
                    }
                    // 检查本地是否有新版本压缩包,存在,则解压后移除版本包
                    app.isFileExists({
                        path: _file,
                        callback: function (existRes) {
                            if (existRes.exist !== true) {
                                app.log("FileExists :[" + _file + "] is not exist");
                                window.page.checkNewVersion();
                                return;
                            }
                            app.unzip({
                                path: _file,
                                dest: "/",
                                callback: function (unzipRes) {
                                    window.page.checkNewVersion();
                                    app.showToast("已更新版本:" + result.versionId);
                                    app.log("unzip return:" + JSON.stringify(unzipRes));
                                    app.deleteFile({
                                        path: _file,
                                        callback: function (t) {
                                            app.log("deleteFile return:" + JSON.stringify(t));
                                        }
                                    });
                                }
                            });
                        }
                    });
                });
            }, function (message) {
                if (!String.isEmpty(message)) {
                    app.log(message);
                }
                window.page.checkNewVersion();
            });
        },
        checkNewVersion: function () {
            this.getCurrentAppVersion(function (version) {
                app.log("新版本检查,当前版本:" + version);
                window.page.getLatestAppVersion(version, function (result) {
                    if (Object.isNotNullObject(result)) {
                        app.log("发现新版本,下载更新包:[" + result.versionId + "]");
                        window.page.downloadVersionFile(result);
                    }
                    setTimeout(function () {
                        window.page.checkNewVersion();
                    }, 300000);
                });
            });
        },
        getCurrentAppVersion: function (success, fail) {
            var _this = this;
            if (!Object.isFunction(success)) {
                success = function () {
                };
            }
            if (!Object.isFunction(fail)) {
                fail = function (message) {
                    if (String.isEmpty(message)) {
                        return;
                    }
                    app.log(message);
                };
            }
            app.readFile({
                path: "app.json",
                callback: function (res) {
                    var _content = res.content;
                    var _app = undefined;
                    try {
                        _app = JSON.parse(_content);
                    } catch (e) {
                        app.log("readFile fail with[" + e.name + ":" + e.message + "]");
                    }
                    if (!_app) {
                        fail.apply(_this, ["parse app.json failed "]);
                        return;
                    }
                    if (String.isEmpty(_app.version)) {
                        fail.apply(_this, ["get app.version fail with value [" + _app.version + "]"]);
                        return;
                    }
                    success.apply(_this, [_app.version]);
                }
            });
        },
        getLatestAppVersion: function (version, callback) {
            var _this = this;
            app.log("start to getLatestAppVersion with:[" + version + "]");
            invokePost("BizAction.getLatestAppVersion", [version], function (result) {
                if (Object.isFunction(callback)) {
                    callback.apply(_this, [result]);
                }
            });
        },
        replaceRichText: function (selector) {
            if (String.isEmpty(selector)) {
                return;
            }
            var _imgs = document.querySelectorAll(selector);
            if (_imgs.length === 0) {
                return;
            }
            var _remoteReg = /(http[s]?):\/\//;
            var _base64Reg = /^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i;
            _imgs.forEach(function (img) {
                var _src = img.src;
                if (_base64Reg.test(_src) || _remoteReg.test(_src)) {
                    return;
                }
                var _srcs = [];
                _srcs.push(window.vApp.serverUrl);
                _srcs.push(_src.substring(_src.indexOf("/p/"), _src.length));
                _srcs.push("?r=");
                _srcs.push(Math.random().toString(16));
                img.src = _srcs.join("");
            });
        },
        pushPage: function (url) {
            app.pushPage({
                path: url
            });
        }
    },
    filters: {
        couponType: function (type) {
            type = Number.parseIntWithDefault(type, 0);
            if (type === 1) {
                return "同城";
            }
            if (type === 2) {
                return "城际";
            }
            if (type === 3) {
                return "出租车";
            }
            if (type === 4) {
                return "大巴城际";
            }
            if (type === 5) {
                return "大巴包车";
            }
            if (type === 6) {
                return "汽车票";
            }
            if (type === 7) {
                return "通勤";
            }
            if (type === 10) {
                return "网约车";
            }
            return "其他";
        },
        orderStatus: function (status) {
            status = Number.parseIntWithDefault(status, 0);
            if (status === 1) {
                return "待执行";
            }
            if (status === 2) {
                return "后付费业务进行中";
            }
            if (status === 3) {
                return "待支付";
            }
            if (status === 4) {
                return "已支付";
            }
            if (status === 5) {
                return "预付费业务进行中";
            }
            if (status === 6) {
                return "已完成";
            }
            if (status === 7) {
                return "已取消";
            }
            if (status === 8) {
                return "已关闭";
            }
            return "其他";
        },
        bussinessType: function (type) {
            type = Number.parseIntWithDefault(type, 0);
            if (type === 1) {
                return "同城";
            }
            if (type === 2) {
                return "城际约车";
            }
            if (type === 3) {
                return "出租车";
            }
            if (type === 4) {
                return "大巴线路";
            }
            if (type === 5) {
                return "大巴包车";
            }
            if (type === 6) {
                return "汽车票";
            }
            if (type === 7) {
                return "上下班";
            }
            if (type === 8) {
                return "扫码支付";
            }
            if (type === 9) {
                return "旅游线路";
            }
            if (type === 10) {
                return "网约车";
            }
            return "其他";
        },
        genAz: function (index) {
            return String.fromCharCode(index + 65);
        },
        pad: function (num, n) {
            return window.pad(num, n);
        },
        formatMilliseconds: function (value) {
            value = parseInt(value);
            if (isNaN(value)) {
                return "-:-";
            }
            value = parseInt(value / 1000);
            var _val = [];
            var _second = value % 60;
            var _minute = parseInt(value / 60) % 60;
            var _hour = parseInt(value / 60 / 60) % 60;
            var _day = parseInt(_hour / 24);
            if (_day > 0) {
                _val.push(_day);
                _val.push("天");
                _hour = _hour % 24;
            }
            if (_hour > 0) {
                if (_hour < 10) {
                    _val.push("0");
                }
                _val.push(_hour);
                _val.push("时");
            }
            if (_minute < 10) {
                _val.push("0");
            }
            _val.push(_minute);
            _val.push("分");
            if (_second < 10) {
                _val.push("0");
            }
            _val.push(_second);
            _val.push("秒");
            return _val.join("");
        },
        formatMobile: function (phone) {
            return phone.substr(0, 3) + '****' + phone.substr(7, 11);
        },
        formatCardNo: function (cardno) {
            return cardno.replace(cardno.substr(6, 8), '********');
        },
        formatDate: function (t, fmt) {
            t = Number.parseIntWithDefault(t, 0);
            if (t === 0) {
                return "--";
            }
            fmt = fmt || "yyyy-MM-dd hh:mm";
            return Date.format(t, fmt);
        },
        formatRate: function (value, rate, toFixed) {
            return Number.formatRate(value, rate, toFixed);
        },
        formatPenny: function (value) {
            return Number.formatRate(value, 100, 2);
        },
        fileServer: function (imageId, defaultImg) {
            return window.fileServer(imageId, defaultImg);
        },
        attachServer: function (imageId, defaultImg) {
            return window.attachServer(imageId, defaultImg);
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值