审查视图

public/assets/js/backend.js 18.6 KB
Karson authored
1
define(['jquery', 'bootstrap', 'toastr', 'layer', 'lang', 'moment'], function ($, undefined, Toastr, Layer, Lang, Moment) {
Karson authored
2 3 4 5 6 7 8 9
    var Backend = {
        config: {
            //toastr默认配置
            toastr: {
                "closeButton": true,
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
Karson authored
10
                "positionClass": "toast-top-right",
Karson authored
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "5000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            }
        },
        api: {
            ajax: function (options, success, failure) {
                var index = Backend.api.layer.load();
                options = $.extend({
                    type: "POST",
                    dataType: 'json',
29
                    success: function (ret) {
Karson authored
30
                        Backend.api.layer.close(index);
31 32 33 34
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : null;
                            var msg = ret.hasOwnProperty("msg") && ret.msg != "" ? ret.msg : "";
                            if (ret.code === 1) {
Karson authored
35
                                if (typeof success == 'function') {
36
                                    var onAfterResult = success.call(undefined, data);
Karson authored
37 38 39 40
                                    if (!onAfterResult) {
                                        return false;
                                    }
                                }
41
                                Toastr.success(msg ? msg : __('Operation completed'));
Karson authored
42
                            } else {
43
                                Toastr.error(msg ? msg : __('Operation failed'));
Karson authored
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
                            }
                        } else {
                            Toastr.error(__('Unknown data format'));
                        }
                    }, error: function () {
                        Backend.api.layer.close(index);
                        Toastr.error(__('Network error'));
                    }
                }, options);
                $.ajax(options);
            },
            //修复URL
            fixurl: function (url) {
                if (url.substr(0, 1) !== "/") {
                    var r = new RegExp('^(?:[a-z]+:)?//', 'i');
                    if (!r.test(url)) {
60
                        url = Config.moduleurl + "/" + url;
Karson authored
61 62 63 64
                    }
                }
                return url;
            },
65 66 67 68
            //获取修复后可访问的cdn链接
            cdnurl: function (url) {
                return /^(?:[a-z]+:)?\/\//i.test(url) ? url : Config.upload.cdnurl + url;
            },
Karson authored
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
            //查询Url参数
            query: function (name, url) {
                if (!url) {
                    url = window.location.href;
                }
                name = name.replace(/[\[\]]/g, "\\$&");
                var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                        results = regex.exec(url);
                if (!results)
                    return null;
                if (!results[2])
                    return '';
                return decodeURIComponent(results[2].replace(/\+/g, " "));
            },
            //上传文件
            upload: function (file, callback) {
                var data = new FormData();
                data.append("file", file);
                $.ajax({
                    url: "ajax/upload",
                    data: data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    dataType: 'json',
95 96 97 98 99 100 101 102 103 104 105 106 107 108
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : null;
                            var msg = ret.hasOwnProperty("msg") && ret.msg != "" ? ret.msg : "";
                            if (ret.code === 1) {
                                if (typeof callback == 'function') {
                                    var onAfterResult = success.call(undefined, data);
                                    if (!onAfterResult) {
                                        return false;
                                    }
                                }
                                if ($('.summernote').size() > 0 && data && typeof data.url !== 'undefined') {
                                    $('.summernote').summernote("insertImage", data.url, 'filename');
                                }
Karson authored
109 110
                                Toastr.success(__('Operation completed'));
                            } else {
111
                                Toastr.error(msg ? msg : __('Operation failed'));
Karson authored
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
                            }
                        } else {
                            Toastr.error(__('Unknown data format'));
                        }
                    }, error: function () {
                        Toastr.error(__('Network error'));
                    }
                });
            },
            open: function (url, title, options) {
                title = title == undefined ? "" : title;
                url = Backend.api.fixurl(url);
                url = url + (url.indexOf("?") > -1 ? "&" : "?") + "dialog=1";
                var area;
                if ($(window).width() < 800) {
                    area = ["95%", "95%"];
                } else {
                    area = ['800px', '600px'];
                }
                Backend.api.layer.open($.extend({
                    type: 2,
                    title: title,
                    shadeClose: true,
                    shade: false,
                    maxmin: true,
                    moveOut: true,
                    area: area,
                    content: url,
                    zIndex: Backend.api.layer.zIndex,
                    skin: 'layui-layer-noborder',
                    success: function (layero, index) {
143
                        var that = this;
Karson authored
144 145 146 147
                        //$(layero).removeClass("layui-layer-border");
                        Backend.api.layer.setTop(layero);
                        var frame = Backend.api.layer.getChildFrame('html', index);
                        var layerfooter = frame.find(".layer-footer");
148
                        Backend.api.layerfooter(layero, index, that);
Karson authored
149 150 151 152 153 154 155 156 157 158

                        //绑定事件
                        if (layerfooter.size() > 0) {
                            // 监听窗口内的元素及属性变化
                            // Firefox和Chrome早期版本中带有前缀
                            var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
                            // 选择目标节点
                            var target = layerfooter[0];
                            // 创建观察者对象
                            var observer = new MutationObserver(function (mutations) {
159
                                Backend.api.layerfooter(layero, index, that);
Karson authored
160 161 162 163 164 165 166 167 168 169 170 171 172 173
                                mutations.forEach(function (mutation) {
                                });
                            });
                            // 配置观察选项:
                            var config = {attributes: true, childList: true, characterData: true, subtree: true}
                            // 传入目标节点和观察选项
                            observer.observe(target, config);
                            // 随后,你还可以停止观察
                            // observer.disconnect();
                        }
                    }
                }, options ? options : {}));
                return false;
            },
174
            layerfooter: function (layero, index, that) {
Karson authored
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
                var frame = Backend.api.layer.getChildFrame('html', index);
                var layerfooter = frame.find(".layer-footer");
                if (layerfooter.size() > 0) {
                    $(".layui-layer-footer", layero).remove();
                    var footer = $("<div />").addClass('layui-layer-btn layui-layer-footer');
                    footer.html(layerfooter.html());
                    if ($(".row", footer).size() === 0) {
                        $(">", footer).wrapAll("<div class='row'></div>");
                    }
                    footer.insertAfter(layero.find('.layui-layer-content'));
                }
                var heg = frame.outerHeight();
                var titHeight = layero.find('.layui-layer-title').outerHeight() || 0;
                var btnHeight = layero.find('.layui-layer-btn').outerHeight() || 0;

                var oldheg = heg + titHeight + btnHeight;
191
                var maxheg = 600;
192 193
                if (frame.outerWidth() < 768 || that.area[0].indexOf("%") > -1) {
                    maxheg = $(window).height();
194
                }
Karson authored
195
                // 如果有.layer-footer或窗口小于600则重新排
196
                if (layerfooter.size() > 0 || oldheg < maxheg || that.area[0].indexOf("%") > -1) {
Karson authored
197 198
                    var footerHeight = layero.find('.layui-layer-footer').outerHeight() || 0;
                    footerHeight = 0;
199 200
                    if (oldheg >= maxheg) {
                        heg = Math.min(maxheg, oldheg) - titHeight - btnHeight - footerHeight;
Karson authored
201 202 203 204 205 206 207
                    }
                    layero.css({height: heg + titHeight + btnHeight + footerHeight});
                    layero.find("iframe").css({height: heg});
                }
                if (layerfooter.size() > 0) {
                    footer.on("click", ".btn", function () {
                        if ($(this).hasClass("disabled") || $(this).parent().hasClass("disabled")) {
208
                            return;
Karson authored
209 210 211 212 213 214 215 216 217 218
                        }
                        $(".btn:eq(" + $(this).index() + ")", layerfooter).trigger("click");
                    });
                }
            },
            sidebar: function (params) {
                colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
                $colorNums = colorArr.length;
                badgeList = {};
                $.each(params, function (k, v) {
219
                    $url = Backend.api.fixurl(k);
Karson authored
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

                    if ($.isArray(v))
                    {
                        $nums = typeof v[0] !== 'undefined' ? v[0] : 0;
                        $color = typeof v[1] !== 'undefined' ? v[1] : colorArr[(!isNaN($nums) ? $nums : $nums.length) % $colorNums];
                        $class = typeof v[2] !== 'undefined' ? v[2] : 'label';
                    } else
                    {
                        $nums = v;
                        $color = colorArr[(!isNaN($nums) ? $nums : $nums.length) % $colorNums];
                        $class = 'label';
                    }
                    //必须nums大于0才显示
                    badgeList[$url] = $nums > 0 ? '<small class="' + $class + ' pull-right bg-' + $color + '">' + $nums + '</small>' : '';
                });
                $.each(badgeList, function (k, v) {
236
                    var anchor = top.window.$("li a[addtabs][url='" + k + "']");
Karson authored
237
                    if (anchor) {
Karson authored
238 239
                        top.window.$(".pull-right-container", anchor).html(v);
                        top.window.$(".nav-addtabs li a[node-id='" + anchor.attr("addtabs") + "'] .pull-right-container").html(v);
Karson authored
240 241 242
                    }
                });
            },
Karson authored
243
            addtabs: function (url, title, icon) {
Karson authored
244
                var dom = "a[url='{url}']"
Karson authored
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
                var leftlink = top.window.$(dom.replace(/\{url\}/, url));
                if (leftlink.size() > 0) {
                    leftlink.trigger("click");
                } else {
                    url = Backend.api.fixurl(url);
                    leftlink = top.window.$(dom.replace(/\{url\}/, url));
                    if (leftlink.size() > 0) {
                        var event = leftlink.parent().hasClass("active") ? "dblclick" : "click";
                        leftlink.trigger(event);
                    } else {
                        var baseurl = url.substr(0, url.indexOf("?") > -1 ? url.indexOf("?") : url.length);
                        leftlink = top.window.$(dom.replace(/\{url\}/, baseurl));
                        //能找到相对地址
                        if (leftlink.size() > 0) {
                            icon = typeof icon != 'undefined' ? icon : leftlink.find("i").attr("class");
                            title = typeof title != 'undefined' ? title : leftlink.find("span:first").text();
                            leftlink.trigger("fa.event.toggleitem");
                        }
                        var navnode = $(".nav-tabs ul li a[node-url='" + url + "']");
                        if (navnode.size() > 0) {
                            navnode.trigger("click");
                        } else {
                            //追加新的tab
                            var id = Math.floor(new Date().valueOf() * Math.random());
                            icon = typeof icon != 'undefined' ? icon : 'fa fa-circle-o';
                            title = typeof title != 'undefined' ? title : '';
Karson authored
271
                            top.window.$("<a />").append('<i class="' + icon + '"></i> <span>' + title + '</span>').prop("href", url).attr({url: url, addtabs: id}).addClass("hide").appendTo(top.window.document.body).trigger("click");
Karson authored
272 273 274 275
                        }
                    }
                }
            },
Karson authored
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
            success: function (options, callback) {
                var type = typeof options === 'function';
                if (type) {
                    callback = options;
                }
                return Backend.api.layer.msg(__('Operation completed'), $.extend({
                    offset: 0, icon: 1
                }, type ? {} : options), callback);
            },
            error: function (options, callback) {
                var type = typeof options === 'function';
                if (type) {
                    callback = options;
                }
                return Backend.api.layer.msg(__('Operation failed'), $.extend({
                    offset: 0, icon: 2
                }, type ? {} : options), callback);
            },
            toastr: Toastr,
            layer: Layer
        },
        lang: function () {
            var args = arguments,
                    string = args[0],
                    i = 1;
            string = string.toLowerCase();
            //string = typeof Lang[string] != 'undefined' ? Lang[string] : string;
            if (typeof Lang[string] != 'undefined') {
                if (typeof Lang[string] == 'object')
                    return Lang[string];
                string = Lang[string];
307
            } else if (string.indexOf('.') !== -1 && false) {
Karson authored
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
                var arr = string.split('.');
                var current = Lang[arr[0]];
                for (var i = 1; i < arr.length; i++) {
                    current = typeof current[arr[i]] != 'undefined' ? current[arr[i]] : '';
                    if (typeof current != 'object')
                        break;
                }
                if (typeof current == 'object')
                    return current;
                string = current;
            } else {
                string = args[0];
            }
            return string.replace(/%((%)|s|d)/g, function (m) {
                // m is the matched format, e.g. %s, %d
                var val = null;
                if (m[2]) {
                    val = m[2];
                } else {
                    val = args[i];
                    // A switch statement so that the formatter can be extended. Default is %s
                    switch (m) {
                        case '%d':
                            val = parseFloat(val);
                            if (isNaN(val)) {
                                val = 0;
                            }
                            break;
                    }
                    i++;
                }
                return val;
            });
341 342
        },
        init: function () {
343
            //公共代码
Karson authored
344
            //配置Toastr的参数
345 346 347
            if (Config.controllername == 'index') {
                Backend.config.toastr.positionClass = "toast-top-right-index";
            }
Karson authored
348
            Toastr.options = Backend.config.toastr;
349
            //点击包含.btn-dialog的元素时弹出dialog
Karson authored
350
            $(document).on('click', '.btn-dialog,.dialogit', function (e) {
351
                e.preventDefault();
352
                Backend.api.open(Backend.api.fixurl($(this).attr('href')), $(this).attr('title'));
353
            });
354
            //点击包含.btn-addtabs的元素时事件
Karson authored
355 356
            $(document).on('click', '.btn-addtabs,.addtabsit', function (e) {
                e.preventDefault();
357
                Backend.api.addtabs($(this).attr("href"), $(this).attr("title"));
Karson authored
358
            });
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
            //点击加入到Shortcut
            $(document).on('click', '#ribbon ol li:last a[data-url]', function (e) {
                e.preventDefault();
                var fastjump = top.window.$(".fastmenujump");
                if (fastjump) {
                    var url = $(this).data("url");
                    var text = $(this).text();
                    if (fastjump.find("option[value='" + url + "']").size() == 0) {
                        fastjump.append("<option value='" + url + "'>" + $(this).text() + "</option>");
                        var shortcut = localStorage.getItem("shortcut");
                        shortcut = shortcut ? JSON.parse(shortcut) : {};
                        shortcut[url] = text;
                        localStorage.setItem("shortcut", JSON.stringify(shortcut));
                        Toastr.success(__('Operation completed'));
                    }
                } else {
                    Toastr.error(__('Operation failed'));
                }
            });
378 379 380 381
            //修复含有fixed-footer类的body边距
            if ($(".fixed-footer").size() > 0) {
                $(document.body).css("padding-bottom", $(".fixed-footer").height());
            }
Karson authored
382 383 384 385 386 387 388 389 390 391
        }
    };
    //将Layer暴露到全局中去
    window.Layer = Layer;
    //将Toastr暴露到全局中去
    window.Toastr = Toastr;
    //将语言方法暴露到全局中去
    window.__ = Backend.lang;
    //将Backend渲染至全局,以便于在子框架中调用
    window.Backend = Backend;
Karson authored
392 393 394
    //将Moment方法暴露到全局中去
    window.Moment = Moment;
395
    Backend.init();
Karson authored
396 397
    return Backend;
});