
// 兼容 IE8
(function () {

    if (!window.console) {
        window.console = {
            debug: function () { },
            error: function () { },
            info: function () { },
            log: function () { },
            warn: function () { },
            dir: function () { },
            dirxml: function () { },
            table: function () { },
            trace: function () { },
            group: function () { },
            groupCollapsed: function () { },
            groupEnd: function () { },
            clear: function () { },
            count: function () { },
            countReset: function () { },
            assert: function () { },
            profile: function () { },
            profileEnd: function () { },
            time: function () { },
            timeLog: function () { },
            timeEnd: function () { },
            timeStamp: function () { },
            context: function () { },
            memory: {
                totalJSHeapSize: 0,
                usedJSHeapSize: 0,
                jsHeapSizeLimit: 0
            }
        };
    };

    if (!document.getElementsByClassName) {
        document.getElementsByClassName = function (className) {
            function search(element, className, array) {
                var children = element.children;
                if (children) {
                    for (var i = 0; i < children.length; i++) {
                        var child = children[i];
                        if (!child) continue;
                        if (child.className == className) array.push(child);
                        search(child, className, array);
                    };
                };
            };
            var array = [];
            search(document.body, className, array);
            return array;
        };
    };

    // 判断 IE 8。
    window.isIE8 = function () { return navigator.userAgent.indexOf("MSIE 8.0;") > -1 ? true : false; };

})();

// 检查浏览器。
(function () {
    // 微信 PC 端：
    // Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x6304051b)

    // 微信 iPhone 端
    // Mozilla/5.0 (iPhone; CPU iPhone OS 15_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.16(0x18001042) NetType/WIFI Language/zh_CN

    // 微信 Android 端
    // Mozilla/5.0 (Linux; Android 11; M2102K1AC Build/RKQ1.201112.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/86.0.4240.99
    // XWEB/3179 MMWEBSDK/20211001 Mobile Safari/537.36 MMWEBID/764 MicroMessenger/8.0.16.2040(0x280010E3) Process/toolsmp WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64

    var ua = navigator.userAgent;
    window.inWeixin = ua.indexOf(" MicroMessenger/") > -1 ? true : false;
})();

// 格式化 Date 对象为易读文本。
function toLucid(date) {
    if (typeof date == "number" || typeof date == "string") return toLucid(new Date(date));
    if (date && date instanceof Date) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        var milli = date.getMilliseconds();
        year = (year < 10 ? "000" : (year < 100 ? "00" : (year < 1000 ? "0" : ""))) + String(year);
        month = (month < 10 ? "0" : "") + String(month);
        day = (day < 10 ? "0" : "") + String(day);
        hour = (hour < 10 ? "0" : "") + String(hour);
        minute = (minute < 10 ? "0" : "") + String(minute);
        second = (second < 10 ? "0" : "") + String(second);
        milli = (milli < 10 ? "00" : (milli < 100 ? "0" : "")) + String(milli);
        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + "." + milli;
    };
    return "0000-00-00 00:00:00.000";
};

window.showLoading = function (visible) {
    if (!document.body) return;

    var id = "global-loading";
    var div = document.getElementById(id);
    if (!div) {
        var html = "<div>";
        for (var i = 0; i < 8; i++) html += '<span></span>';
        html += '</div>'
        div = document.createElement('div');
        div.className = "global-loading";
        div.innerHTML = html;
        div.id = id;
        div.className = id;
        div.style.display = 'none';
        document.body.appendChild(div);
    }
    div.style.display = visible ? 'block' : 'none';

    var mask = document.getElementById("global-loading-mask");
    if (mask && mask.style) mask.style.display = visible ? 'block' : 'none';
};

// ajax
(function () {

    function _receive(xhr, succeed, failed) {
        xhr.onreadystatechange = () => {
            if (xhr.readyState != 4) return
            var response = xhr.responseText;
            // try {
            //     var json = JSON.parse(response);
            //     response = json;
            // } catch (err) {
            //     // console.error("ajax", err.message);
            // }
            if (xhr.status == 200 || xhr.status == 304) {
                if (typeof succeed === "function") succeed(response);
            } else {
                if (typeof failed === "function") failed(response);
            }
        }
    }

    window.ajaxGet = function (url, succeed, failed) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        _receive(xhr, succeed, failed);
        try {
            xhr.send();
        } catch (err) {
            // console.error(err);
            if (typeof failed === "function") failed(err.message);
        }
    }

    window.ajaxPost = function (url, data, succeed, failed) {
        var xhr = new XMLHttpRequest()
        var content = "";
        if (data) {
            if (typeof data == "string") content = data;
            else if (typeof data == "object") content = data;
            else content = String(data);
        }
        xhr.open("POST", url, true)
        xhr.setRequestHeader("Content-Type", "text/plain")
        _receive(xhr, succeed, failed);
        try {
            xhr.send(content);
        } catch (err) {
            // console.error(err);
            if (typeof failed === "function") failed(err.message);
        }
    }

    // 使用 AJAX 上传文件。
    window.ajaxUpload = function (url, succeed, failed, accept, before, after, progress, _blob) {
        if (typeof succeed != "function") succeed = function () { };
        if (typeof failed != "function") failed = function (msg) { console.error("ajaxUpload", msg); };
        if (typeof before != "function") before = function (file) { console.log("ajaxUpload", "before", file); };
        if (typeof after != "function") after = function (file) { console.log("ajaxUpload", "after", file); };
        if (typeof progress != "function") progress = function (p) { console.log("ajaxUpload", "progress", p); };
        if (!url) return failed("未指定 URL。");

        var input = document.createElement("input");
        input.type = "file";
        if (accept && typeof accept == "string") input.accept = accept;
        input.click();
        input.onchange = function (evt) {
            if (evt.target.files.length < 1) return failed("没有选择文件。");

            if (typeof url == "function") url = url(evt.target.files[0]);
            if (typeof url != "string") return failed("未获取 URL。");

            var file = evt.target.files[0];
            if (typeof before == "function") {
                var value = before(file);
                if (typeof value == "boolean" && value == false) return;
                if (typeof value == "number" && value == 0) return;
            }

            var reader = new FileReader();
            reader.file = file;
            reader.onabort = function (e) { };
            reader.onerror = function (e) { };
            reader.onloadstart = function (e) { };
            reader.onprogress = function (e) { };
            reader.onload = function (e) { };
            reader.onloadend = function (e) {
                var xhr = new XMLHttpRequest();
                xhr.open("post", url);
                xhr.setRequestHeader("Content-Type", "application/octet-stream");
                if (_blob) xhr.responseType = 'arraybuffer';
                xhr.onreadystatechange = function (e) {
                    if (xhr.readyState == 4) {
                        after(file);
                        if (xhr.status == 200) {
                            if (_blob) {
                                var blob = new Blob([xhr.response]);
                                if (typeof _succeed === 'function') _succeed(blob);
                                return;
                            }
                            var response = xhr.responseText;
                            try { response = JSON.parse(response); } catch (err) { }
                            succeed(response);
                        } else failed("Status=" + String(xhr.status));
                    }
                };
                xhr.onprogress = function (e) {
                    if (e.lengthComputable) {
                        var p = { name: reader.file.name, total: e.total, loaded: e.loaded };
                        progress(p);
                    }
                };
                xhr.send(reader.result);
            };
            reader.readAsArrayBuffer(file);
        };
    }

})();

// 从指定字符串中获取参数。
window.urlQuery = function (selector, decode) {
    var combined = window.location.search;
    if (!combined) return "";
    switch (typeof selector) {
        case "string":
        case "number":
            break;
        default:
            return "";
    };
    var matched = combined.match(new RegExp("[\?\&#][^\?\&]+=[^\?\&]+", "g"));
    var array = [];
    if (matched) {
        for (var i = 0; i < matched.length; i++) {
            var split = matched[i].substring(1).split("=");
            array.push({ key: split[0], value: split[1] });
        };
    };
    var value = "";
    switch (typeof selector) {
        case "string":
            for (var i in array) {
                if (array[i].key == selector) {
                    value = array[i].value;
                    break;
                };
            };
            break;
        case "number":
            var i = parseInt(selector);
            if (i >= 0 && i < array.length) {
                value = array[i].value;
                break;
            };
            break;
    };
    if (decode) value = decodeURIComponent(value);
    return value;
};

// 从指定字符串中获取参数。
window.urlHash = function (selector, decode) {
    var combined = window.location.hash;
    if (!combined) return "";
    switch (typeof selector) {
        case "string":
        case "number":
            break;
        default:
            return "";
    };
    var matched = combined.match(new RegExp("[\?\&#][^\?\&]+=[^\?\&]+", "g"));
    var array = [];
    if (matched) {
        for (var i = 0; i < matched.length; i++) {
            var split = matched[i].substring(1).split("=");
            array.push({ key: split[0], value: split[1] });
        };
    };
    var value = "";
    switch (typeof selector) {
        case "string":
            for (var i in array) {
                if (array[i].key == selector) {
                    value = array[i].value;
                    break;
                };
            };
            break;
        case "number":
            var i = parseInt(selector);
            if (i >= 0 && i < array.length) {
                value = array[i].value;
                break;
            };
            break;
    };
    if (decode) value = decodeURIComponent(value);
    return value;
};

// 获取查询字符串中的返回地址。
function getReturn() {
    var ret = urlQuery("back");
    if (!ret) ret = urlQuery("return");
    if (!ret) ret = "/";
    return ret;
};

// 显示吐司提示。
// _html：要显示的内容。
// _duration：持续时间，单位毫秒，不指定时默认 2000 毫秒。
window.toast = function (_html, _duration) {
    var className = "toast";

    if (document.getElementsByClassName) {
        var shown = document.getElementsByClassName(className);
        for (i = 0; i < shown.length; i++) {
            try {
                document.body.removeChild(shown[i]);
            } catch (error) { };
        };
    };
    if (typeof _html != "string" || _html == "") return;

    var box = document.createElement("span");
    var area = document.createElement("div");
    console.info(className, _html);
    box.style.backdropFilter = "blur(5px)";
    box.style.backgroundColor = "#3f3f3f";
    box.style.borderRadius = "5px";
    box.style.boxShadow = "0px 10px 40px rgba(0,0,0, 0.3)";
    box.style.color = "white";
    box.style.display = "inline-block";
    box.style.fontFamily = "consolas, 'microsoft yahei', 'pingfang sc', sans-serif";
    box.style.fontSize = "14px";
    box.style.lineHeight = "28px";
    box.style.paddingBottom = "10px";
    box.style.paddingLeft = "20px";
    box.style.paddingRight = "20px";
    box.style.paddingTop = "10px";
    box.style.textShadow = "0px 0px 10px rgba(0,0,0, 0.5)";
    box.innerHTML = _html;
    area.className = className;
    area.style.bottom = "20%";
    area.style.display = "block";
    area.style.fontSize = "0px";
    area.style.left = "10%";
    area.style.opacity = "0";
    area.style.position = "fixed";
    area.style.right = "10%";
    area.style.textAlign = "center";
    area.style.transition = "all 0.15s linear";
    area.style.zIndex = "200000000";
    area.appendChild(box);
    document.body.appendChild(area);
    setTimeout(function () {
        area.style.opacity = 1;
        var delay = 150 + parseInt((typeof _duration == "number") ? _duration : 2000);
        setTimeout(function () {
            area.style.opacity = 0;
            setTimeout(function () {
                try {
                    document.body.removeChild(area);
                } catch (error) { };
            }, 300);
        }, delay);
    }, 1);
    return { area: area, box: box };
};

