欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用jquery写的一个PC端桌面应用管理界面

程序员文章站 2022-05-28 10:03:06
...

支持拖拽移动,桌面文件夹管理(拖拽应用到另一个应用上面,会自动生成文件夹),桌面任务栏管理,桌面应用管理,桌面菜单栏.(资源下载地址在最下面)

   $.fn.extend({
            animateCss: function (animationName, callback) {
                var animationEnd = (function (el) {
                    var animations = {
                        animation: 'animationend',
                        OAnimation: 'oAnimationEnd',
                        MozAnimation: 'mozAnimationEnd',
                        WebkitAnimation: 'webkitAnimationEnd',
                    };

                    for (var t in animations) {
                        if (el.style[t] !== undefined) {
                            return animations[t];
                        }
                    }
                })(document.createElement('div'));

                this.addClass('animated ' + animationName).one(animationEnd, function () {
                    $(this).removeClass('animated ' + animationName);

                    if (typeof callback === 'function') callback();
                });

                return this;
            },
        });
        /**
        重构桌面管理
        @dev fanyl
        */
        var DesktopManager = (function () {
            var isArray = $.isArray;
            // 自定义事件监听
            var emitterEvents = {
                bind: function (ev, callback, context) {
                    var calls = this._callbacks || (this._callbacks = {});
                    var list = calls[ev] || (calls[ev] = []);
                    list.push([callback, context]);
                    return this;
                },
                unbind: function (ev, callback) {
                    var calls;
                    if (!ev) {
                        this._callbacks = {};
                    } else if (calls = this._callbacks) {
                        if (!callback) {
                            calls[ev] = [];
                        } else {
                            var list = calls[ev];
                            if (!list) return this;
                            for (var i = 0, l = list.length; i < l; i++) {
                                if (list[i] && callback === list[i][0]) {
                                    list[i] = null;
                                    break;
                                }
                            }
                        }
                    }
                    return this;
                },
                trigger: function (eventName) {
                    var list, calls, ev, callback, args;
                    var both = 2;
                    if (!(calls = this._callbacks)) return this;
                    while (both--) {
                        ev = both ? eventName : 'all';
                        if (list = calls[ev]) {
                            for (var i = 0, l = list.length; i < l; i++) {
                                if (!(callback = list[i])) {
                                    list.splice(i, 1); i--; l--;
                                } else {
                                    args = both ? Array.prototype.slice.call(arguments, 1) : arguments;
                                    callback[0].apply(callback[1] || this, args);
                                }
                            }
                        }
                    }
                    return this;
                }
            };
            if(!Object.keys){
                Object.keys = (function() {

                    var hasOwnProperty = Object.prototype.hasOwnProperty;

                    return function(obj) {
                        if (obj !== Object(obj)) {
                            throw new TypeError('Object.keys called on non-object');
                        }
                        var ret = [ ];
                        for (var i in obj) {
                            if (hasOwnProperty.call(obj, i)) {
                                ret.push(i);
                            }
                        }
                        return ret;
                    };

                }());
            }
            function ToObject(v) {
                if (v === null || v === undefined) throw TypeError();
                return Object(v);
            }
            function HasProperty(o, p) {
                return Object.prototype.hasOwnProperty.call(o, p);
            }
            function findIndex(value, predicate) {
                var o = ToObject(value);
                var lenValue = o.length;
                var len = lenValue;
                var t = arguments.length > 2 ? arguments[2] : undefined;
                var k = 0;
                while (k < len) {
                    var pk = String(k);
                    var kPresent = HasProperty(o, pk);
                    if (kPresent) {
                        var kValue = o[pk];
                        var testResult = predicate.call(t, kValue, k, o);
                        if (Boolean(testResult)) {
                            return k;
                        }
                    }
                    ++k;
                }
                return -1;
            }
            function find(value, predicate) {
                var o = ToObject(value);
                var lenValue = o.length;
                var len = lenValue;
                var t = arguments.length > 2 ? arguments[2] : undefined;
                var k = 0;
                while (k < len) {
                    var pk = String(k);
                    var kPresent = HasProperty(o, pk);
                    if (kPresent) {
                        var kValue = o[pk];
                        var testResult = predicate.call(t, kValue, k, o);
                        if (Boolean(testResult)) {
                            return kValue;
                        }
                    }
                    ++k;
                }
                return undefined;
            }
            function flatArray(data, callback, dep) {
                if (dep < 0 || data.length <= 0) {
                    return null;
                }
                var item, result = [], val;
                for (var i = 0, len = data.length; i < len; i++) {
                    item = data[i];
                    result.push(item);
                    if (dep > 0 && (val = callback(item, i, data)) && isArray(val)) {
                        val = flatArray(val, callback, dep - 1);
                        if (val) {
                            result.push.apply(result, val)
                        }
                    }
                }
                return result;
            }
            function flatter(data, callback, dep) {
                dep = dep || 1;
                if ($.isPlainObject(data)) {
                    data = $.map(Object.keys(data), function (n) { return data[n] })
                }
                return flatArray(data, callback, dep);
            }
            function debounce(fn, delay) {
                var timeId, context, result, nowTime, startTime;
                function debounceFn() {
                    nowTime = Date.now();
                    var t = nowTime - startTime;
                    if (t >= delay) {
                        result = fn.apply(context, args);
                        timeId = null;
                    } else {
                        timeId = setTimeout(debounceFn, delay - t);
                    }
                }
                return function () {

                    startTime = Date.now();
                    context = this;
                    args = arguments;
                    if (!timeId) {
                        timeId = setTimeout(debounceFn, delay)
                    }
                    return result;
                }
            }
            // 简化板模板引擎
            var dxTemplate = (function dxTemplate() {

                var invert = function (obj) {
                    var result = {};
                    for (var name in escapeMap) {
                        if (escapeMap.hasOwnProperty(name)) {
                            result[escapeMap[name]] = name;
                        }
                    }
                    return result;
                }
                // List of HTML entities for escaping.
                var escapeMap = {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#x27;',
                    '`': '&#x60;'
                };
                var unescapeMap = invert(escapeMap);

                // Functions for escaping and unescaping strings to/from HTML interpolation.
                var createEscaper = function (map) {
                    var escaper = function (match) {
                        return map[match];
                    };
                    // Regexes for identifying a key that needs to be escaped
                    var source = '(?:' + Object.keys(map).join('|') + ')';
                    var testRegexp = RegExp(source);
                    var replaceRegexp = RegExp(source, 'g');
                    return function (string) {
                        string = string == null ? '' : '' + string;
                        return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
                    };
                };
                var _util = {
                    escape: createEscaper(escapeMap),
                    unescape: createEscaper(unescapeMap)
                }
                var parseTemplate = function (str) {
                    var err = "";
                    try {
                        var func;
                        var strFunc =
                            "var p=[];with(obj){p.push('" +
                            str.replace(/[\r\t\n]/g, " ")
                                .replace(/'(?=[^#]*#>)/g, "\t")
                                .split("'").join("\\'")
                                .split("\t").join("'")
                                .replace(/<%=(.+?)%>/g, "',$1,'")
                                .replace(/<%-(.+?)%>/g, "',_.escape($1),'")
                                .split("<%").join("');")
                                .split("%>").join("p.push('")
                            + "');}return p.join('');";
                        func = new Function("obj", '_', strFunc);
                        return function (data) {
                            return func.call(this, data, _util)
                        }
                    } catch (e) { throw 'template parse:'+e.message; }
                }
                return parseTemplate;
            }());
            //UID
            var _desktop_uid=1;
            function uid()
            {
                return _desktop_uid++;
            }
            /**
                插件管理
            */
            function PluginManager() {
                this.loadPlugins = {};
            }
            PluginManager.create = function (proto) {
                var plugins = [], pluginsNames = {};
                var subClass = function (options) {
                    this.plugins = $.extend(options.plugins || [], plugins);
                    this.pluginsNames = {};
                    this.loadPlugins = {};
                    this.init && this.init.apply(this, arguments);

                }
                var base = function () { }
                base.prototype = this.prototype;

                subClass.addPlugin = function (name, depends, plugin) {
                    if (!isArray(depends)) {
                        plugin = depends;
                        depends = null;
                    }
                    if (pluginsNames[name]) {
                        throw 'plugin already exists:'+name;
                    }
                    pluginsNames[name] = true;
                    $.extend(plugin, emitterEvents);
                    plugin.name = name;
                    plugin.__depends__ = depends;
                    plugins.push(plugin);
                }
                subClass.prototype = new base();
                subClass.prototype.constructor = subClass;
                $.extend(subClass.prototype, proto);
                return subClass;
            }
            PluginManager.prototype = {
                constructor: PluginManager,
                setOptions: function (options) {
                    this.options = $.extend(this.options || {}, this.defaultOptions, options);
                },
                getPlugin: function (name) {
                    return this.pluginsNames[name];
                },
                initPlugin: function () {
                    var that = this;
                    var plugin, depends, pluginsNames = this.pluginsNames, plugins = this.plugins, loadPlugins = this.loadPlugins;
                    for (var i = 0, len = plugins.length; i < len; i++) {
                        pluginsNames[plugins[i].name] = plugins[i]
                    }
                    var loadPlugin = function (plugin, callback) {
                        var depends = plugin.__depends__, len = depends ? depends.length : 0, name = plugin.name;
                        if (loadPlugins[name]) {
                            callback && callback(plugin);
                            return;
                        }
                        var args = [that];
                        var load = function () {
                            loadPlugins[name] = plugin;
                            plugin.init && plugin.init.apply(plugin, args);
                            callback && callback(plugin);
                        }

                        if (len <= 0) {
                            load();
                        } else {
                            var itemPluign;
                            for (var i = 0; i < len; i++) {
                                itemPluign = pluginsNames[depends[i]];
                                if (!plugin) {
                                    throw 'plugin not is exist'
                                }
                                loadPlugin(itemPluign);
                                args.push(itemPluign);
                            }
                            load();
                        }
                    }
                    for (var i = 0, length = plugins.length; i < length; i++) {
                        loadPlugin(plugins[i])
                    }
                },
                createdPlugin: function (name) {
                    this.invokeMethod(name || "*", 'created')
                },
                updatePlugin: function (name) {
                    this.invokeMethod(name || "*", 'update')
                },
                invokeMethod: function (name, method) {
                    var plugin, depends, plugins = this.plugins, loadPlugins = this.loadPlugins;
                    for (var i = 0, length = plugins.length; i < length; i++) {
                        plugin = plugins[i];
                        depends = plugin.__depends__;
                        if (loadPlugins[plugin.name] && (plugin.name == name || name == '*') && plugin[method] && typeof plugin[method] == 'function') {
                            plugin[method](this);
                        }
                    }
                },
                addLayer: function (el) {
                    this.wrapper.append(el);
                }
            }
            /**
               创建桌面应用层
               @param {string} theme 主题
               @parma {sttring} icon_app 添加应用APP图标
               @param {array} data  桌面数据
            */
            var DesktopLayer = PluginManager.create({
                defaultOptions:{
                    theme: '',// 主题
                    icon_app:'',// 添加应用APP图标
                    bgImage: '/assets/images/theme_glow.jpg',// 背景图片
                    data: null // 桌面数据
                },
                init: function (options) {
                    this.setOptions(options);
                    this.wrapper = $('<div class="desktop-wrapper"></div>');
                    this.wrapper.appendTo('body');
                    var that = this;
                    this.initPlugin();
                    setTimeout($.proxy(this.createdPlugin,this))
                },
                addLayer: function (el) {
                    this.wrapper.append(el);
                }
            });
            // 窗口大小发生变化刷新
            DesktopLayer.addPlugin('WindowSizeChange', {
                created: function (desktop) {
                    $(window).on('resize', debounce(function () {
                        desktop.updatePlugin();
                    }, 100))
                }
            })
            // 背景图片
            DesktopLayer.addPlugin('BackgroundImage', {
                init: function (desktop) {
                    this.desktop = desktop;
                },
                created: function (desktop) {
                    //var uctheme = $.cookie("uctheme");
                    //if (uctheme == null || uctheme == "") {
                    //    uctheme = "theme_base";
                    //}
                    //$("#themeSetting_area").on('click', '>a', function (e) {
                    //    var a = $(e.currentTarget);
                    //    var themeid = a.attr("themeid");
                    //    var imgUrl = ctx + "/images/system/" + themeid + ".jpg";
                    //    // 设置选择的主题到cookie中
                    //    $.cookie("uctheme", themeid, { expires: 30, path: "/" });
                    //    this.updateBackImg(imgUrl);
                    //});
                    //var imageUrl = ctx + "/images/system/" + uctheme + ".jpg";
                    this.updateBackImg(desktop.options.bgImage);
                },
                update: function (desktop) {
                    this.updateBackImg(this.imageUrl)
                },
                updateBackImg: function (imageUrl) {
                    this.imageUrl = imageUrl;
                    var width = this.desktop.wrapper.outerWidth();
                    var height = this.desktop.wrapper.outerHeight();
                    this.desktop.wrapper.css({
                        'background-image': 'url(' + imageUrl + ')',
                        'background-size': width + 'px ' + height + 'px'
                    })
                },
                open: function () {
                    Windows.openSys({
                        id: 'themSetting',
                        title: '设置主题',
                        width: 900,
                        height: 600,
                        content: document.getElementById("themeSetting_wrap")
                    });
                }
            });
            // 左边菜单
            DesktopLayer.addPlugin('DesktopMenu', {
                layerTpl: '<div class="descktop-menu-wrap"><ul class="descktop-menu"></ul></div>',
                init: function (desktop) {
                    this.currentIndex = 0;
                    this._data = desktop.options.data;
                    this._flatData = flatter(this._data, function (d) {
                        return d.children;
                    }, 3)
                    this.desktop = desktop;
                    this.wrapper = $(this.layerTpl);
                    this.element = this.wrapper.children('.descktop-menu');
                },
                created: function (desktop) {
                    desktop.addLayer(this.wrapper);
                    this.initEvent();
                    this.initMenu();
                },
                getData: function () {
                    return this._data;
                },
                getFlatData: function () {
                    return this._flatData;
                },
                getDataItemById: function (id) {
                    return find(this._flatData, function (d) {
                        return d.id == id;
                    })
                },
                getMenuDataByIndex: function (index) {
                    return this._data[index];
                },
                initEvent: function () {
                    // 绑定菜单事件
                    this.wrapper.on('mouseenter.menu', '.item', $.proxy(function (e) {
                        var el = $(e.currentTarget);
                        this.selectedElement(el);// 设置当前元素选中样式
                        this.showChildMenu(el);// 显示下级菜单
                    }, this)).on('mouseleave.menu', '.item', $.proxy(function (e) {
                        var el = $(e.currentTarget);
                        this.unselectedElement(el);
                        this.hideChildMenu(el);
                    }, this)).on('click.menu', '.item', $.proxy(function (e) {
                        e.stopPropagation();
                        var el = $(e.currentTarget), id = el.attr('data-id'), parent = el.attr('data-parent');
                        var itemData = this.getDataItemById(id);
                        if (parent) {
                            this.selectedIndex(el.index());
                        } else if (itemData.url) {
                            this.trigger('onOpenApp', itemData);
                        }
                    }, this))
                },
                initMenu: function () {
                    var data = this.getData();
                    var itemTemplate = function (item) {
                        return '<li class="item" data-parent="true" data-id="' + item.id + '"><span>' + item.name + '</span></li>';
                    }
                    this.element.append($.map(data, itemTemplate))
                    this.selectedIndex(0);
                },
                showChildMenu: function (el) {
                    var menu = el.data('menu'), id = el.attr('data-id'), noMenu = el.data('nomenu');
                    if (!menu && !noMenu) {
                        var itemTemplate = function (item) {
                            return '<li class="item" data-id="' + item.id + '"><img src="' + item.icon + '" /><span>' + item.name + '</span></li>';
                        }
                        var itemData = this.getDataItemById(id);
                        if (itemData.children && itemData.children.length > 0) {
                            menu = $('<div class="menu-panel-wrap"><ul class="menu-panel"></ul></div>');
                            menu.children().append($.map(itemData.children, itemTemplate));
                            el.addClass('item-parent');
                            el.data('menu', menu);
                        } else {
                            el.data('nomenu', true);// 如果这不是一个菜单,下次跳过
                        }
                    }
                    if (menu) {
                        menu.appendTo(el);
                    }
                },
                hideChildMenu: function (el) {
                    var menu = el.data('menu');
                    if (menu) {
                        menu.remove();
                    }
                },
                unselectedElement: function (e) {
                    e.removeClass('active');
                    this.element.removeClass('active')
                },
                selectedElement: function (e) {
                    e.addClass('active').siblings('.active').removeClass('active');
                    this.element.addClass('active')
                },
                selectedIndex: function (index) {
                    var el = this.element.children().eq(index);
                    this.currentIndex = index;
                    this.selectedElement(el);
                    el.addClass('active2').siblings().removeClass('active2');
                    this.trigger('onMenuChange', this.getMenuDataByIndex(index))
                }
            });
            // 左边菜单工具栏
            DesktopLayer.addPlugin('DesktopMenuTool', ['DesktopMenu'], {
                layerTpl: '<ul class="desktop-menu-tools"></div>',
                init: function (desktop, desktopMenu) {

                    this.wrapper = $(this.layerTpl).appendTo(desktopMenu.wrapper);
                    this.initTool();
                    this.initEvent();
                },
                created: function () { },
                addTool: function (tools) {
                    if (!$.isArray(tools)) {
                        tools = [tools]
                    }
                    var that = this;
                    this.wrapper.append($.map(tools, function (item) {
                        that.bind('onItemClick_' + item.icon, item.callback);
                        return '<li class="item-tool" data-command="'+item.icon+'"><i class="tool-icon ' + item.icon + '" title="' + item.name + '"></i></li>'
                    }))
                },
                initTool: function () {
                    var tools = [{
                        name: '全屏',
                        icon: 'icon-fullscreen',// 全屏
                        callback: function () {

                        }
                    },
                    {
                        name: '设置',
                        icon: 'icon-setting',// 设置
                        callback: function () {
                            console.log('aa');
                        }
                    },
                    {
                        name: '快捷导航',
                        icon: 'icon-navigation', //导航
                        callback: function () {

                        }
                    },
                    {
                        name: '注销',
                        icon: 'icon-logout', //注销
                        callback: function () {

                        }
                    }
                    ];
                    this.addTool(tools);
                },
                initEvent: function () {
                    this.wrapper.on('click', '.item-tool', $.proxy(function (e) {
                        this.trigger('onItemClick_' + $(e.currentTarget).attr('data-command'));
                        e.stopPropagation();

                    },this))
                }
            });
            // 左边菜单底部时钟
            DesktopLayer.addPlugin('DesktopMenuClock', ['DesktopMenu'], {
                layerTpl: '<div class="desktop-menu-timer"><span></span></div>',
                init: function (desktop, desktopMenu) {
                    var wrapper = this.wrapper= $(this.layerTpl).appendTo(desktopMenu.wrapper);
                },
                created: function () {
                    var elTimer = this.wrapper.children('span');;
                    elTimer.everyTime('1s', function () {
                        elTimer.html((new Date()).format('HH:mm:ss</br>yyyy-MM-dd'))
                    })
                }
            });
            // 桌面应用
            DesktopLayer.addPlugin('DesktopAPP', ['DesktopMenu'], {
                layerTpl: '<div class="desktop-app-wrap"></div>',
                init: function (desktop, desktopMenu,taskbar) {
                    this.layoutData = {};
                    this.desktop = desktop;
                    this.desktopMenu = desktopMenu;
                    this.wrapper = $(this.layerTpl);
                    desktop.addLayer(this.wrapper);
                    this.currentIndex = -1;
                    this.initLayoutData();
                    this.initPage();
                    this.initEvent();
                },
                created: function () {

                },
                update: function () {
                    this.initLayoutData();
                    this.reAgainApp();
                },
                initEvent: function () {
                    // 监听桌面应用click事件
                    this.wrapper.on('click', '.app-button', $.proxy(function (e) {
                        var el = $(e.currentTarget),id=el.attr('data-id');
                        this.trigger('onAppClick', this.getCurrentPageItemDataByID(id))
                        e.stopImmediatePropagation();
                        return false;
                    }, this))
                    // 菜单栏,菜单改变时
                    this.desktopMenu.bind('onMenuChange', function (item) {
                        this.showApp(this.desktopMenu.currentIndex);
                    }, this);
                    // 监听菜单栏入口APP类型的菜单
                    this.desktopMenu.bind('onOpenApp', function (item) {
                        this.trigger('onOpenApp', item);
                    }, this);
                    this.bind('onAppClick', function (item) {
                        if (item.appType == 0) {
                            this.trigger('onOpenApp', item);
                            return;
                        }
                    });
                },
                initPage:function(){
                    var len = this.desktopMenu.getData().length;
                    this.pages = new Array(len)
                    var screenWidth=$(window).width();
                    var totalWidth=screenWidth*len;
                    for (var i = 0; i < len; i++) {
                        this.pages[i] = {
                            container: $('<div class="app-page" data-index="' + i + '"></div>').css({
                                width:screenWidth-80,
                                left:(i*screenWidth)+'px'
                            }).appendTo(this.wrapper),
                            init: false,
                            apps:[]
                        };
                    }
                },
                initLayoutData: function () {
                    var layoutData = this.layoutData;
                    var size = this.getLayerSize();// 获取可视区域大小
                    var width = size.width;
                    var height = size.height-40;
                    var margin = 10, appWidth = 124, appHeight = 127;
                    var rowCount = parseInt(height / (appHeight + margin));
                    var columnCount = parseInt(width / (appWidth + margin));
                    layoutData.offsetX = this.wrapper.offset().left;
                    layoutData.width = width;
                    layoutData.height = height;
                    layoutData.appWidth = appWidth;
                    layoutData.appHeight = appHeight;
                    layoutData.margin = margin;
                    layoutData.rowCount = rowCount;
                    layoutData.columnCount = columnCount;
                    layoutData.pageMaxCount = rowCount * columnCount;
                },
                getLayoutData:function(refresh){
                    if (refresh) {
                        this.initLayoutData();
                    }
                    return this.layoutData;
                },
                getLayerSize: function () {
                    var el = this.wrapper;
                    var width = el.outerWidth(), height = el.outerHeight();
                    return {
                        width: width,
                        height:height
                    }
                },
                updateAppName:function(id,name){
                    var itemData = this.getCurrentPageItemDataByID(id);
                    if (itemData) {
                        itemData.name = name;
                        $(itemData.elData.el).find('.app-name').text(name);
                    }
                },
                moveApp: function (id, targetid) {
                    var apps = this.getCurrentPageApps();
                    var currentIndex= this.getCurrentPageItemIndexByID(id);
                    var targetIndex = this.getCurrentPageItemIndexByID(targetid);
                    var current = apps[currentIndex];
                    var target = apps[targetIndex];

                    // 如果目录是应用,就创建新的文件夹
                    if (current.appType==0&&target.appType == 0) {
                        var cloneElData = target.elData;
                        var folder = {
                            id:'app_folder_'+uid(),
                            icon: '',
                            name: '文件夹',
                            appType: 2,
                            children: [target, current],
                            elData: {}
                        };
                        var elData = $.extend(folder.elData,cloneElData);// 复制目标位置
                        // 创建文件夹
                        var el = this.createApp(folder);
                        folder.elData.el = el[0];
                        apps[targetIndex] = folder;
                        el.css({ left: elData.x, top: elData.y }).replaceAll(cloneElData.el);

                        this.addPlaceholderApp(currentIndex);

                    }
                    else if (current.appType == 0 && target.appType == 2) {
                        var children = target.children;
                        if (children.length<9){
                            $(target.elData.el).find('ul').append(this.createMiniApp(current));
                         }
                        children.push(current);
                        this.addPlaceholderApp(currentIndex);

                    } else if (target.appType == -1||current.appType==2) {
                        apps[targetIndex] = current;
                        apps[currentIndex] = target;
                        var currenElData = this.cloneElData({}, target.elData)
                        var targetElData = this.cloneElData({}, current.elData)
                        currenElData.el = current.elData.el;
                        current.elData = currenElData;
                        targetElData.el = target.elData.el;
                        target.elData = targetElData;
                        $(current.elData.el).css({ left: current.elData.x, top: current.elData.y });
                        $(target.elData.el).css({ left: target.elData.x, top: target.elData.y });
                    }
                },
                createMiniApp:function(item){
                    return '<li data-id="'+item.id+'"><img src="'+item.icon+'"/></li>';
                },
                createApp:function (item) {
                    var el;
                    if (item.appType == 2) {
                        var childTpl = [];
                        for (var i = 0, length = Math.min(item.children.length,9) ; i < length; i++) {
                            childTpl.push(this.createMiniApp(item.children[i]));
                        }
                        el = '<div  data-apptype="' + item.appType + '" data-id="' + item.id + '" class="app-button app-file-folder"><ul>' + childTpl.join('') + '</ul><div class="app-name">' + item.name + '</div></div>';
                    } else if(item.appType ==0||item.appType ==1){
                        el = '<div  data-apptype="' + item.appType + '" data-id="' + item.id + '" class="app-button"><div class="app-icon"><img src="' + item.icon + '"/></div><div class="app-name">' + item.name + '</div></div>';
                    }else if(item.appType==-1){
                        el = '<div class="app-button-placeholder" data-id="'+item.id+'"></div>';
                    }
                    el = $(el);
                    return el;
                },
                addLastApp: function (item) {
                    var currentPage = this.getCurrentPage();
                    var apps = currentPage.apps,len=apps.length;
                    var emptyAppIndex = findIndex(apps, function (item) { return item.appType == -1; });
                    if (emptyAppIndex != -1) {
                        $(apps[emptyAppIndex].elData.el).remove();
                        this.addApp(item, emptyAppIndex,1);
                    }else {
                        var addAppIndex = findIndex(apps, function (item) { return item.appType == 1; });
                        if (addAppIndex != -1) {
                            this.addApp(item, addAppIndex, 0);
                            this.setAppLaout(apps[addAppIndex+1].elData, addAppIndex+1);
                        } else {
                            this.addApp(item);
                        }
                    }
                },
                addApp:function(item,index,del){
                    var currentPage = this.getCurrentPage();
                    var apps = currentPage.apps, len = apps.length;
                    var elApp = this.createApp(item);
                    var app = item;
                    app.elData = {
                        el: elApp[0]
                    }
                    if (index == undefined) {
                        index = apps.push(app) - 1;
                    } else {
                        apps.splice(index, del, app);
                    }
                    this.setAppLaout(app.elData, index);
                    currentPage.container.append(elApp);
                },
                createPlaceholderApp: function () {
                    var item={
                        id:'app_placeholder_'+uid(),
                        appType: -1,
                        elData:{}
                    }
                    item.elData.el = this.createApp(item)[0];
                    return item;
                },
                cloneElData: function (source, elData) {
                    source.x = elData.x;
                    source.y = elData.y;
                    source.offsetX = elData.offsetX;
                    source.pageX = elData.pageX;
                    source.pageY = elData.pageY;
                    source.width = elData.width;
                    source.height = elData.width;
                    return source;
                },
                addPlaceholderApp:function(index){
                    var placeholderApp = this.createPlaceholderApp(), elData = placeholderApp.elData;
                    var apps = this.getCurrentPageApps();
                    var target = apps[index];
                    this.cloneElData(elData, target.elData)
                    apps[index] = placeholderApp;
                    $(elData.el).css({ left: elData.x, top: elData.y }).replaceAll(target.elData.el);
                },
                createApps: function (index) {
                    if (this.pages[index].init)
                    {
                        return;
                    }
                    this.pages[index].init = true;
                    var itemData = this.desktopMenu.getMenuDataByIndex(index);
                    // 在结尾增加一个添加应用图标
                    itemData.apps.push({
                        id: 'add_app_' + (+new Date),
                        icon: this.desktop.options.icon_app,
                        name: '添加应用',
                        appType: 1 //0 应用 1:添加应用 2:文件夹
                    })
                    this.pages[index].apps = [];//当前页APP集合
                    this.pages[index].points = []; // 当前页所有页坐标点
                    var appLen=itemData.apps.length,i=-1;
                    while (++i < appLen) {
                        this.addApp(itemData.apps[i]);
                    }
                },
                setAppLaout: function (elData,index) {
                    var layoutData = this.getLayoutData();
                    var width = layoutData.width,height = layoutData.height;
                    var margin = layoutData.margin,
                        rowIndex = 0,
                        appWidth = layoutData.appWidth,
                        appHeight = layoutData.appHeight,
                        rowCount = layoutData.rowCount,
                        columnCount = layoutData.columnCount, offsetX = layoutData.offsetX;
                    var rIndex = index % rowCount, cIndex = Math.floor(index / rowCount);
                    var marginLeft=(cIndex+1)*margin,marginTop=(rIndex+1)*margin;
                    var left = cIndex * appWidth + marginLeft, top = rIndex * appHeight + marginTop;
                    var el = elData.el;
                    elData.x = left;
                    elData.y = top;
                    elData.offsetX = offsetX;
                    elData.pageX = offsetX + left;
                    elData.pageY = top;
                    elData.width = appWidth;
                    elData.height = appHeight;
                    if (el) {
                        el.style.left = left + "px";
                        el.style.top = top + 'px';
                    }
                },
               // 窗口大小发生变化,重排
                reAgainApp: function (start) {
                    start = start || 0;
                    var apps = this.getCurrentPageApps();
                    for (var i = start, len = apps.length; i < len; i++) {
                        this.setAppLaout(apps[i].elData, i);
                    }
                },
                // 显示APP
                showApp: function (currentIndex) {
                    this.currentIndex = currentIndex;
                    this.createApps(currentIndex);
                    var pageCount = this.pages.length;
                    var width = this.getLayerSize().width;
                    var totalWidth = width * pageCount;
                    for (var i = 0; i < pageCount; i++) {
                        this.pages[i].container.stop(true).animate({
                            left: ((i - currentIndex) * width) + 'px'
                        }, 'slow', 'swing')
                    }
                    this.trigger('onShowApp',currentIndex)
                },
                getCurrentPageItemData: function (index) {
                    return this.desktopMenu.getMenuDataByIndex(this.currentIndex).apps[index];
                },
                getCurrentPageItemDataByID: function (id) {
                    return find(this.getCurrentPageApps(),function (item) {
                        return item.id == id;
                    });
                },
                getCurrentPageItemIndexByID: function (id) {
                    return findIndex(this.getCurrentPageApps(),function (item) {
                        return item.id == id;
                    });
                },
                getCurrentPage: function () {
                    return this.pages[this.currentIndex];
                },
                getCurrentPageApps:function(){
                    return this.getCurrentPage().apps;
                },
                getCurrentPageElements: function (appType) {
                    var container = this.getCurrentPage().container;
                    return appType != undefined ? container.children('.app-button[data-apptype="' + appType + '"]') : container.children('.app-button')
                },
                updateFolderContent: function (id) {
                    var itemData = this.getCurrentPageItemDataByID(id);
                    if (itemData.appType == 2) {
                        var children = itemData.children;
                        if (children.length <= 0) {
                            $(itemData.elData.el).remove();
                        } else {
                            var childTpl = [];
                            for (var i = 0, length = Math.min(children.length, 9) ; i < length; i++) {
                                childTpl.push(this.createMiniApp(children[i]));
                            }
                            $(itemData.elData.el).children('ul').html(childTpl);
                        }
                    }
                }
            });
            // 文件夹对话窗
            DesktopLayer.addPlugin('FolderDialog', ['DesktopAPP'], {
                layerTpl:'<div class="appfolder-dialog"></div>',
                contentTpl: "<div class =\"appfolder-dialog-body\">\n                    <div class =\"appfolder-title\">\n            <span class=\"appfolder-title-text\"></span>\n            <div class=\"input-wrap\">\n                <input type=\"text\" value=\"\" />\n            </div>\n            </div>\n             <div class =\"appfolder-content\">\n            <div class =\"appfolder-pages\"></div>\n            <ul class =\"appfolder-indicators\"> </ul>\n            </div>\n            </div>\n           <div class =\"appfolder-madal-mask\"></div>",
                init: function (desktop, desktopApp) {
                    this.desktopApp = desktopApp;
                    this.pageIndex = 1
                    this.pageSize = 9;
                    this.pageCount = 0;
                    this.wrapper = $(this.layerTpl).hide().appendTo('body');
                    this.currentFolderId = -1;
                    this.initEvent();
                },
                initEvent: function () {
                    this.wrapper.on('click', '.appfolder-madal-mask', $.proxy(function () {
                        this.close();
                    }, this));
                    // 文件夹左右翻页
                    this.wrapper.on('click', '.indicator', $.proxy(function (e) {
                        var that = this;
                        if ($(e.currentTarget).hasClass('indicator-left')) {
                            this.showPage(this.pageIndex - 1)
                        } else {
                            this.showPage(this.pageIndex + 1)
                        }
                    }, this));
                    // 文件夹指示器翻页
                    this.wrapper.on('click', '.btn-indicator', $.proxy(function (e) {
                        var that = this, index = $(e.currentTarget).attr('data-index');
                        this.showPage(parseInt(index)+1);
                    }, this));
                    // 文件夹内的APP,右击菜单
                    this.wrapper.smartMenu([[{
                        text: "移出文件夹",
                        func: $.proxy(function (e) {
                            $(e.currentTarget).remove();
                            var id = e.currentTarget.getAttribute('data-id'), folderid = this.currentFolderId;
                            this.removeApp(id, folderid);
                        }, this)
                    }]], {
                            name: 'folderapp',
                            selector: '.app-button',
                            beforeShow: function (e) {
                                if ($(e.currentTarget).attr('data-apptype') != "0") {
                                    return false;
                                }
                            }
                        });

                },
                removeApp: function (id, folderid) {
                    var desktopApp = this.desktopApp;
                    var itemData = desktopApp.getCurrentPageItemDataByID(folderid);
                    var children = itemData.children;
                    var index = findIndex(children, function (item) { return item.id == id; });
                    if (index != -1) {
                        var appData = children.splice(index, 1);
                        var len = children.length;
                        // 当文件夹数量为空,删除当前文件夹,并关闭文件窗口
                        if (len <= 0) {
                            this.close();
                        } else {
                            var prevPageCount = this.pageCount;
                            this.updateFolder(len);// 当文件夹应用数发生变生,更新文件夹内部状态
                            var currentPageCount = this.pageCount;
                            if (currentPageCount < prevPageCount) {
                                this.wrapper.find('.appfolder-page').eq(currentPageCount).remove();
                                this.showPage(this.pageIndex)
                            }
                        }
                        // APP移出文件夹后,重新显示在桌面
                        this.desktopApp.addLastApp(appData[0]);

                    }
                },
                updateFolder: function (count) {
                    this.pageCount = Math.ceil(count / this.pageSize);
                    var elIndicators = this.wrapper.find('.appfolder-indicators').empty();
                    if (this.pageIndex > this.pageCount) {
                        this.pageIndex = this.pageCount;
                    }
                    // 如果页数大于一,显示分页指示符
                    if (this.pageCount > 1) {
                        // 暂时注释
                        //this.wrapper.find('.appfolder-content').append('<button class ="indicator indicator-left">&lang;</button><button class ="indicator indicator-right">	&rang;</button>')
                        for (var i = 0; i < this.pageCount; i++) {
                            elIndicators.append('<li ><span class="btn-indicator" data-index="'+i+'"></span></li>')
                        }
                    } else {
                        this.wrapper.find('.indicator').remove();
                        elIndicators.empty();
                    }
                },
                render: function (item) {
                    this.currentFolderId = item.id;
                    var children = item.children, count = children.length, i = 0;
                    var wrapper = this.wrapper.attr('data-id', item.id).html(this.contentTpl), indicators = [];
                    var elPages = wrapper.find('.appfolder-pages');
                    var elIndicators = wrapper.find('.appfolder-indicators');
                    this.updateFolder(count);
                    var pageSize = this.pageSize, pageCount = this.pageCount;
                    var p = 0, i, t = 0;
                    for (; p < pageCount; p++) {
                        var elPage = $('<div class="appfolder-page" data-index="' + p + '"></div>'), page = [];
                        for (i = 0; i < pageSize && t < count; i++ , t++) {
                            page.push(this.desktopApp.createApp(children[t]))
                        }
                        elPage.css({
                            left: p * 400,
                        }).append(page).appendTo(elPages);
                    }
                    // 编辑标题
                    this.wrapper.find('.appfolder-title-text').text(item.name).on('click', $.proxy(function (e) {
                        var that = this;
                        var el = $(e.currentTarget);

                        el.parent().addClass('edit')
                    }, this));
                    // 编辑标题
                    this.wrapper.find('.input-wrap>input').val(item.name).on('blur', $.proxy(function (e) {
                        var that = this;
                        var el = $(e.currentTarget);
                        el.parent().parent().removeClass('edit');
                        var value = $.trim(el.val());
                        if (value == '') {
                            value = '未命名'
                        }
                        this.wrapper.find('.appfolder-title-text').text(value);
                        this.desktopApp.updateAppName(this.wrapper.attr('data-id'), value)
                    }, this));

                    return wrapper;
                },
                showPage: function (pageIndex) {
                    if (pageIndex == this.pageIndex) {
                        return;
                    }
                    if (pageIndex < 0) {
                        return;
                    }
                    if (pageIndex > this.pageCount) {
                        return;
                    }
                    var pIndex = pageIndex - 1;
                    var elPages = this.wrapper.find('.appfolder-page'), len = elPages.length, width = 400;
                    for (var i = 0; i < len; i++) {
                        elPages.eq(i).stop(true).animate({
                            left: (i - pIndex) * width
                        })
                    }
                    this.pageIndex = pageIndex;
                    this.showIndicator();
                },
                showIndicator: function () {
                    this.wrapper.find('.appfolder-indicators>li').eq(this.pageIndex - 1).addClass('active').siblings('.active').removeClass('active')
                },
                open: function (item) {
                    this.render(item).fadeIn();
                    this.showIndicator();

                },
                close: function () {
                    var that = this;
                    this.wrapper.fadeOut(function () {
                        that.wrapper.empty();
                        that.desktopApp.updateFolderContent(that.currentFolderId);
                    })
                }
            });
            // 新增应用文件夹
            DesktopLayer.addPlugin('Folder', ['DesktopAPP', 'FolderDialog'], {
                init: function (desktop, desktopApp, folderDialog) {

                    this.desktop = desktop;
                    this.desktopApp = desktopApp;
                    this.folderDialog = folderDialog;
                    var currentIndex = desktopApp.currentIndex;
                    this.onMouseMove = $.proxy(this.onMouseMove, this);
                    this.onMouseUp = $.proxy(this.onMouseUp, this);
                    this.initEvent();
                },
                initEvent: function () {
                    var wrapper = this.desktopApp.wrapper;
                    var $doc = this.$doc = $(wrapper[0].ownerDocument);
                    var that = this;
                    // 监听APPclick事件,只针对文件夹应用显示处理
                    this.desktopApp.bind('onAppClick', $.proxy(function (item) {
                        if (item.appType != 2) {
                            return;
                        }
                        this.folderDialog.open(item);
                    }, this))
                    wrapper.on('mousedown', '.app-button[data-apptype!="1"]', $.proxy(function (e) {
                        e.preventDefault();
                        if(e.which!=1){
                            return;
                        }
                        var eventObj = that.eventObj = {};
                        var el = $(e.currentTarget), id = el.attr('data-id');
                        var app = this.desktopApp.getCurrentPageItemDataByID(id), elData = app.elData;
                        eventObj.id = app.id;
                        eventObj.offsetX = elData.offsetX;
                        eventObj.dragTarget = el;
                        eventObj.pageX = e.pageX;
                        eventObj.pageY = e.pageY;
                        eventObj.x = elData.x;
                        eventObj.y = elData.y;
                        eventObj.dropTarget = null;
                        this._mouseDownEvent = e;

                        $doc.on('mousemove', that.onMouseMove);
                        $doc.on('mouseup', that.onMouseUp);
                    }, this));
                },
                onMouseStart: function () {
                    var eventObj = this.eventObj;
                    var moveElement = eventObj.moveElement = eventObj.dragTarget.clone();// 创建一个复本
                    moveElement.addClass('drag-move-app');
                    eventObj.dragTarget.addClass('drag-target-app')
                    this.desktopApp.getCurrentPage().container.append(moveElement)

                },
                moveShadow: function (x, y) {
                    this.eventObj.moveElement.css({
                        left: x,
                        top: y
                    })
                },
                contiansXY: function (x, y) {
                    var apps = this.desktopApp.getCurrentPageApps(), eventObj = this.eventObj, app, elData;
                    for (var i = 0, len = apps.length; i < len; i++) {
                        app = apps[i];
                        elData = app.elData;
                        if (app.appType !=1 && app.id != eventObj.id && x > elData.pageX && x < (elData.pageX + elData.width) && y > elData.pageY && y < (elData.pageY + elData.height)) {
                            return app;
                        }
                    }
                    return null;
                },
                onMouseMove: function (e) {
                    if (!this.eventObj) {
                        return;
                    }
                    var eventObj = this.eventObj, pageX = e.pageX, pageY = e.pageY, mX = pageX - eventObj.pageX, mY = pageY - eventObj.pageY;
                    if (Math.abs(Math.max(mX, mY))<5) {
                        return;
                    }
                    if (!eventObj.moveElement) {
                        this.onMouseStart();
                    }
                    this.moveShadow(Math.max(eventObj.x + mX, 0), eventObj.y + mY);
                    var app;
                    var prevDropTarget = eventObj.dropTarget;
                    if ((app = this.contiansXY(pageX, pageY))) {
                        if (prevDropTarget && prevDropTarget[0] != app.elData.el || !prevDropTarget) {
                            eventObj.dropTarget = $(app.elData.el);
                            eventObj.dropTarget.addClass('drop-target-app')
                        }
                    } else {
                        eventObj.dropTarget = null;
                    }
                    if (prevDropTarget && prevDropTarget != eventObj.dropTarget) {
                        prevDropTarget.removeClass('drop-target-app')
                    }
                },
                onMouseUp: function (e) {
                    this.$doc.off('mousemove', this.onMouseMove);
                    this.$doc.off('mouseup', this.onMouseUp);
                    var eventObj = this.eventObj;
                    if (eventObj && eventObj.moveElement) {
                        eventObj.moveElement.remove();
                        eventObj.dragTarget.removeClass('drag-target-app');
                    }
                    if (eventObj.dropTarget) {
                        eventObj.dropTarget.removeClass('drop-target-app');
                        this.onDrop(this.eventObj);
                        this.eventObj = null;
                    }
                    e.preventDefault();
                },
                onDrop: function (e) {
                    var targetid = e.dropTarget.attr('data-id');
                    this.desktopApp.moveApp(e.id, targetid);
                }
            });
            // 新增应用
            DesktopLayer.addPlugin('NewAppDialog', ['DesktopAPP'], {
                // 弹出窗模板
                layerTplFunc: dxTemplate("  <div class=\"add-appdialog\">            <div class=\"add-appdialog-body\">                <div class=\"left-menu\">                    <div class=\"header\">                        <div class=\"add-app-input\">                            <i class=\"search-icon\"></i> <input type=\"text\" class=\"input-search\" placeholder=\"搜索\" />                            <i class=\"ui-icon ui-icon-close\" style=\"display:none\"></i>                        </div>                    </div>                    <div class=\"content\">                        <div class=\"search-result\" style=\"display:none\">                        </div>                        <ul class=\"accordion\" >                            <%                            for(var i=0,len=data.length;i<len;i++){                                var item=data[i];                                var children=item.children;                            %>                            <li>                            <div class=\"accordion-header accordion-parent\" data-level=\"1\"><%=item.name%></div>                            <%if(children&&children.length){ %>                             <ul>                                <%for(var k=0,klen=children.length;k<klen;k++){                                    var childItem=children[k];                                    var hasApp=!!childItem.url;                                                                      var child2=childItem.children;                                    var hasChild=child2&&child2.length;                                                                 %>                                       <li>                                        <div class=\"accordion-header<%=!hasApp?\" accordion-parent\":\"\"%>\" data-level=\"2\">                                            <label class=\"checkbox\">                                                <input type=\"checkbox\" data-type=\"<%=hasApp?1:0%>\" value=\"<%=childItem.id%>\" />                                                <span></span>                                            </label>                                            <span><%=childItem.name%></span>                                        </div>                                        <%if(hasChild){%>                                        <ul>                                             <%for(var j=0,jlen=child2.length;j<jlen;j++){                                                    var childItem2=child2[j];                                               %>                                            <li>                                                <div class=\"accordion-header\">                                                    <label class=\"checkbox\">                                                        <input type=\"checkbox\" data-type=\"1\"  value=\"<%=childItem2.id%>\"/>                                                        <span></span>                                                    </label>                                                    <span><%=childItem2.name%></span>                                                </div>                                             </li>                                            <%}%>                                        </ul>                                         <%}%>                                    </li>                                 <%}%>                              </ul>                                <%}%>                            </li>                            <%}%>                           </ul>                    </div>                </div>                <div class=\"middle-line\"></div>                <div class=\"right-selected\">                    <div class=\"header\">                        <span class=\"title\">                            已选择应用                        </span>                    </div>                    <div class=\"content\">                        <ul class=\"selected-list\">                        </ul>                    </div>                    <div class=\"btn-group\">                        <button class=\"btn btn-cancel\">取消</button>                        <button class=\"btn btn-confirm\">确定</button>                    </div>                </div>            </div>        </div>"),
                // 选中模板
                selectedTplFunc: dxTemplate('<%for(var i=0,len=data.length;i<len;i++){ var item=data[i];%><li data-id="<%=item.id%>"><span><%=item.name%></span> <span class="icon-del" data-id="<%=item.id%>"></span></li ><%}%>'),
                searchTplFunc: dxTemplate("<%if(data.length==0){%>                            <div class=\"empty\">没有搜索到结果</div>                            <%}else{                                for(var i=0,len=data.length;i<len;i++){                                 var item=data[i];                            %>                               <div class=\"accordion-header\">                                            <label class=\"checkbox\">                                                <input type=\"checkbox\" data-type=\"1\" value=\"<%=item.id%>\" />                                                <span></span>                                            </label>                                            <span><%=item.name%></span>                               </div>                            <%}}%>"),
                init: function (desktop, desktopApp) {
                    this.desktop = desktop;
                    this.desktopApp = desktopApp;
                    this.initEvents();
                    this.isInitDialog = false;
                    this.data = [];
                    this.flatData = [];
                    this.selectedData = [];
                    this.selectedDataIds = [];
                },
                initEvents: function () {
                    this.desktopApp.bind('onAppClick', $.proxy(function (item) {
                        if (item.appType != 1) {
                            return;
                        }
                        this.openDialog();
                    },this))
                },
                initDialog: function () {
                    if (this.isInitDialog) {
                        return;
                    }
                    this.isInitDialog = true;
                    var data = [{
                        id: 200001,
                        name: '党群组职',
                        children: [{
                            id: 200000001,
                            name: "组织部",
                            icon: '/assets/images/app/icon_02_社会维稳.png',
                            url: 'dd'
                        }, {
                            id: 200000002,
                            name: "统战部",
                            icon: '/assets/images/app/icon_02_社会维稳.png',
                            url: 'dd'
                        }, {
                            id: 200000003,
                            name: "机关党工委",
                            icon: '/assets/images/app/icon_02_社会维稳.png',
                            url: 'dd'
                        }, {
                            id: 200000004,
                            name: "党校",
                                url: '',
                                children: [
                                    {
                                        id: 20000000001,
                                        name: "社会稳定",
                                        icon: '/assets/images/app/icon_02_社会维稳.png',
                                        url: 'dd'
                                    },
                                    {
                                        id: 20000000002,
                                        name: "关注人群活动",
                                        icon: '/assets/images/app/icon_02_社会维稳.png',
                                        url: 'dd'
                                    }
                                ]
                        }, {
                            id: 200000005,
                            name: "政法委",
                            children: [
                                {
                                    id: 20000000003,
                                    name: "社会稳定",
                                    icon: '/assets/images/app/icon_02_社会维稳.png',
                                    url: 'dd'
                                },
                                {
                                    id: 20000000004,
                                    name: "关注人群活动",
                                    icon: '/assets/images/app/icon_02_社会维稳.png',
                                    url: 'dd'
                                }
                            ]
                        }, {
                            id: 200000006,
                            name: "总工会",
                            icon: '/assets/images/app/icon_02_社会维稳.png',
                            url: 'dd'
                        }, {
                            id: 200000007,
                            name: "团区委",
                            icon: '/assets/images/app/icon_02_社会维稳.png',
                            url: 'dd'
                        }]},
                        {
                            id: 200002,
                            name: '经济产业',
                            children: []
                        }];
                    this.data = data;
                    this.flatData = flatArray(data, function (d) { return d.children; }, 3)
                    var wrapper=this.wrapper=$(this.layerTplFunc({
                        data: data
                    })).hide().appendTo('body');
                    this.elSelectedList = wrapper.find('.selected-list');
                    // 确定,插入已选APP
                    this.wrapper.on('click', '.btn-confirm', $.proxy(function (e) {
                        var selectedData = this.selectedData;
                        if (selectedData.length <= 0) {
                            layer.msg('请先添加应用')
                            return;
                        }
                        for (var i = 0, len = selectedData.length; i < len; i++) {
                            var item = selectedData[i];
                            // 添加APP到桌面中
                            this.desktopApp.addLastApp({
                                id: item.id,
                                name: item.name,
                                appType: 0,
                                icon: item.icon,
                                url:item.url
                            })
                        }
                        this.clearSelected();//清空选中
                        this.closeDialog(); // 关闭
                        e.stopPropagation();
                    }, this))
                    // 取消
                    this.wrapper.on('click', '.btn-cancel', $.proxy(function (e) {
                        this.clearSelected();//清空选中
                        this.closeDialog();//关闭
                        e.stopPropagation();
                    }, this))
                    // 删除选中
                    this.elSelectedList.on('click', '.icon-del', $.proxy(function (e) {
                        var ids = [$(e.currentTarget).attr('data-id')];
                        this.removeSelectedItem(ids);
                        this.selectedCheckbox(ids,false)
                    }, this))
                    // 搜索
                    this.wrapper.find('.input-search').on('input',$.proxy(function (e) {
                        var el = $(e.currentTarget), value = $.trim(el.val()), that = this;
                        this.searchList(value);
                    }, this))
                    this.wrapper.find('.add-app-input .ui-icon-close').on('click', $.proxy(function () {
                        this.wrapper.find('.input-search').val('');
                        this.searchList('');
                    },this))
                    this.initAccordion();
                },
                initAccordion: function () {
                    var headerIcons = ['', 'ui-icon-plus', 'ui-icon-carat-1-e'];
                    var headerSelectedIcons = ['', 'ui-icon-minus', 'ui-icon-carat-1-s'];

                    var that = this, element=this.elAccordion = this.wrapper.find('.accordion');
                    this.wrapper.on('change', ':checkbox', $.proxy(function (e) {
                        e.stopImmediatePropagation();
                        var elChckbox = $(e.currentTarget),itemIds=[];
                        if (elChckbox.length) {
                            var type = elChckbox.attr('data-type'), checked = elChckbox.is(':checked');
                            // 如果当前选中的是二级,就选中下面子级
                            if (type == 0) {
                                elChckbox.parents('.accordion-header').next().find(':checkbox').prop('checked', checked).each(function () {
                                    itemIds.push(this.value);
                                });
                            } else {
                                itemIds.push(elChckbox.val());
                            }
                            if (checked) {
                                this.addSelectedItem(itemIds);
                            } else {
                                this.removeSelectedItem(itemIds);
                            }
                        }
                    }, this));
                    element.on('click', '.accordion-header', $.proxy(function (e) {
                        var el = $(e.currentTarget);
                        if ($(e.target).closest('.checkbox').length || el.next('ul').length <= 0) {
                            return;
                        }
                        toggle(el, true);
                    },this));
                    $.each(headerIcons, function (index, value) {
                        if (value != '') {
                            element.find('.accordion-parent[data-level="' + index + '"]').append('<span class="ui-icon ' + value + '"></span>').next().hide();
                        }
                    })
                    function hide(el, animate) {
                        var level = el.attr('data-level'), headIcon = headerIcons[level], selectedIcon = headerSelectedIcons[level];
                        el.removeClass('active').find('.ui-icon').addClass(headIcon).removeClass(selectedIcon).end().next()[animate ? 'slideUp' : 'hide']();
                    }
                    function show(el, animate) {
                        if (el.hasClass('active')) {
                            return;
                        }
                        var level = el.attr('data-level'), headIcon = headerIcons[level], selectedIcon = headerSelectedIcons[level];
                        el.addClass('active').find('.ui-icon').addClass(selectedIcon).removeClass(headIcon).end().next()[animate ? 'slideDown' : 'show']();
                    }
                    this.showAccordion = show;
                    function toggle(el,animate) {
                        if (el.hasClass('active')) {
                            hide(el, animate)
                        } else {
                            show(el, animate)
                        }
                    }
                    show(element.find('.accordion-parent[data-level="1"]:first'));
                },
                searchList: function (value) {
                    var searchResult = [];
                    var flatData = this.flatData;
                    var elSearchContainer = $('.search-result', this.wrapper);
                    if (value != '') {
                        searchResult = flatData.filter(function (item) {
                            return item.name.indexOf(value) != -1;
                        }, this);
                        elSearchContainer.html(this.searchTplFunc({ data: searchResult })).show();
                        this.wrapper.find('.accordion').hide();
                        this.wrapper.find('.add-app-input .ui-icon-close').show();
                    } else {
                        this.wrapper.find('.accordion').show();
                        elSearchContainer.empty().hide();
                        this.wrapper.find('.add-app-input .ui-icon-close').hide();
                    }
                },
                getItemDataById: function (id) {
                    return find(this.flatData, function (d) {
                        return d.id == id;
                    })
                },
                clearSelected: function () {
                    this.selectedDataIds.length = 0;
                    this.selectedData.length = 0;
                    this.elAccordion.find(':checkbox').prop('checked', false);
                    this.renderSelected();
                },
                renderSelected: function () {
                    var selectedDataIds = this.selectedDataIds
                    this.elSelectedList.html(this.selectedTplFunc({ data: this.selectedData }));

                },
                selectedCheckbox: function (ids,checked) {
                     this.elAccordion.find(':checkbox').each(function () {
                        var id = this.value;
                           if (ids.indexOf(id) != -1) {
                               this.checked = checked;
                        }
                    })
                },
                addSelectedItem: function (ids) {
                    var selectedData = this.selectedData, selectedDataIds = this.selectedDataIds;
                    $.each(this.flatData, function (i, item) {
                        var id = String(item.id);
                        if (ids.indexOf(id) != -1 && selectedDataIds.indexOf(id)==-1) {
                            selectedData.push(item);
                            selectedDataIds.push(id)
                        }
                    })
                    this.renderSelected();

                },
                removeSelectedItem: function (ids) {
                    var selectedData = this.selectedData, selectedDataIds = this.selectedDataIds;
                    for (var i = selectedData.length - 1; i >= 0; i--) {
                        var item = selectedData[i];
                        var id = String(item.id);
                        if (ids.indexOf(id) != -1) {
                            selectedData.splice(i, 1);
                            selectedDataIds.splice(i, 1);
                        }
                    }
                    this.renderSelected();
                },
                closeDialog: function () {
                    layer.close(this.layerIndex)
                },
                openDialog: function () {
                    var that = this;
                    this.initDialog();
                    this.layerIndex=layer.open({
                        id: 'addApp',
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        move: false,// - 触发拖动的元素
                        resize: false,// 是否允许拉伸
                        maxmin: false,// - 最大最小化。
                        anim: 0,
                        shade: 0.7,//遮罩
                        shadeClose: false,//是否点击遮罩关闭
                        skin: 'add-appdialog-wrap',
                        scrollbar: false,
                        fixed: true,//固定
                        success: function () {

                        },
                        cancel: function () {
                            console.log('fffffffffff')
                        },
                        //   btn: ['确定', '取消'],
                        yes: function () { },
                        btn2: function () {

                        },
                        area: ['660px', '576px'],
                        content: this.wrapper
                    });
                }
            })
            // 桌面APP右击菜单功能
            DesktopLayer.addPlugin('AppContextMen', ['DesktopAPP'], {
                init: function (desktop, desktopAPP) {
                    // 应用右击菜单
                    desktopAPP.wrapper.smartMenu([[{
                        text: "删除应用",
                        func: function () {
                            alert('ff');
                        }
                    }]], {
                        name: 'app',
                        selector: '.app-button',
                        beforeShow: function (e) {
                            if ($(e.currentTarget).attr('data-apptype') != "0") {
                                return false;
                            }
                        }
                    });
                }
            })
            // 任务栏
            DesktopLayer.addPlugin('Taskbar', ['DesktopMenu', 'DesktopAPP', 'TaskDailog'], {
                layerTpl: '<div class="desktop-taskbar"><div class="desktop-taskbar-home"></div><ul class="desktop-taskbar-tasks"></ul></div>',
                init: function (desktop, desktopMenu, desktopApp, taskDailog) {
                    this.wrapper = $(this.layerTpl);
                    desktop.addLayer(this.wrapper);
                    this.desktopMenu = desktopMenu;
                    this.desktopApp = desktopApp;
                    this.taskDailog = taskDailog;
                    this.elTasks = this.wrapper.children('.desktop-taskbar-tasks');
                    this.activeTask =null;// 当前**项
                    this.tasks = [];
                    this.initContextMenu();
                    this.initEvent();
                },
                initEvent: function () {
                    // 监听应用打开
                    this.desktopApp.bind('onOpenApp', $.proxy(function (itemData) {
                        this.addTask({
                            id: itemData.id,
                            name: itemData.name,
                            icon: itemData.icon,
                            url: itemData.url,
                            newwindow: itemData.newwindow||0
                        });// 添加一个应用到任务栏中
                        this.openTask(itemData.id);// 打开当前应用窗口
                    }, this));
                    // 点击首页-第一页 
                    this.wrapper.on('click', '.desktop-taskbar-home', $.proxy(function (e) {
                        this.desktopMenu.selectedIndex(0);
                    }, this));
                    // 点击任务栏
                    this.wrapper.on('click', '.desktop-taskbar-tasks>.item', $.proxy(function (e) {
                        var el = $(e.currentTarget), id = el.attr('data-id');
                        this.openTask(id);
                    }, this));
                    // 监听窗口是否关闭
                    this.taskDailog.bind('onClose', function (id) {
                        this.removeTask(id);
                    }, this)
                    // 监听窗口是否最小化
                    this.taskDailog.bind('onMin', function (id) {
                        this.hideTask(id);
                    }, this)
                },
                addTask: function (task) {
                    var elTasks = this.elTasks, tasks = this.tasks;
                    if (this.isTaskExists(task.id)) {
                        return;
                    }
                    var tpl = '<li class="item" data-id="' + task.id + '"><img src="' + task.icon + '" /><span>' + task.name + '</span></li>';
                    task.el = $(tpl).appendTo(elTasks);
                    tasks.push(task);
                },
                removeAllTask: function () {
                    this.removeOtherTask();
                },
                removeOtherTask: function (id) {
                    var tasks = this.tasks;
                    for (var i = tasks.length - 1; i >= 0; i--) {
                        if (id != tasks[i].id) {
                            this.removeTask(tasks[i].id);
                        }
                    }
                },
                removeTask: function (id) {
                    var index = findIndex(this.tasks, function (item) { return item.id == id; });
                    if (index != -1) {
                        var task = this.tasks[index];
                        this.tasks.splice(index, 1);
                        this.hideTask(id);
                        // 关闭对话框
                        this.taskDailog.close(id);
                        task.el.remove();
                    }
                },
                hideAllTask:function(){
                    var tasks = this.tasks;
                    for (var i = 0, length=tasks.length; i < length; i++) {
                        this.hideTask(tasks[i].id)
                    }
                },
                hideTask: function (id) {
                    var task = this.getTaskItemData(id);
                    if (task) {
                        this.taskDailog.hide(task.id);
                        task.el.removeClass('active');
                        if (task == this.activeTask) {
                            this.activeTask = null;
                        }
                    }
                },
                showTask: function (id) {
                    var task = this.getTaskItemData(id);
                    if (task) {
                        this.taskDailog.show(task.id);
                        task.el.addClass('active').siblings('.active').removeClass('active');
                        this.activeTask = task;
                    }
                },
                openTask: function (id) {
                    var task = this.getTaskItemData(id);
                    if (task) {

                        var dialog = this.taskDailog.get(task.id);// 获取对话框
                        // 创建一个对话框
                        if (!dialog) {
                            dialog = this.taskDailog.createDialog(task.id, task.name, task.url, task.newwindow);
                        }
                        // 如果打开的对话框,不是当前**,就显示在它前面
                        if (this.activeTask && task != this.activeTask) {
                            this.showTask(task.id);
                            return;
                        }
                        // 如果是隐藏的就显示
                        if (!dialog.isVisible()) {
                            this.showTask(task.id);
                        } else {
                            this.hideTask(task.id);
                        }

                    }
                },
                getTaskItemData: function (id) {
                    return find(this.tasks, function (item) { return item.id == id });
                },
                initContextMenu: function () {
                    this.wrapper.smartMenu([[{
                        text: "显示桌面",
                        func: $.proxy(function () {
                            this.hideAllTask();
                        },this)
                    }],
                    [{
                        text: "关闭全部",
                        func: $.proxy(function () {
                            this.removeAllTask();
                        },this)
                    }],
                    [{
                        text: "关闭其他",
                        func: $.proxy(function (e) {
                            var el = $(e.currentTarget), id = el.attr('data-id');
                            console.log(id);
                            this.removeOtherTask(id);
                        }, this)
                    }],
                    [{
                        text: "关闭",
                        func: $.proxy(function (e) {
                            var el = $(e.currentTarget), id = el.attr('data-id');
                            this.removeTask(id);
                        }, this)
                    }]], {
                            name: 'desktop-taskbar',
                            selector: '.desktop-taskbar-tasks>.item',
                            offsetY: -100,
                            beforeShow: function (e) {

                            }
                        });
                },
                isTaskExists: function (id) {
                    return findIndex(this.tasks, function (item) { return item.id == id }) != -1;
                }
            });
            // 任务对话框
            DesktopLayer.addPlugin('TaskDailog', (function () {
                var DialogBase = $.Class($.extend({
                    init: function (options) {
                        this.id = options.id;
                        this.title = options.title;
                        this.url = options.url;
                    },
                    show: function (){},
                    hide: function (){},
                    close: function (){},
                    focus: function () { },
                    isVisible: function () { return false;}
                }, emitterEvents))
                var DxArtDialog = DialogBase.extend({
                    init: function (options) {
                        this._super(options);
                        var that = this;
                        var width = $(window).innerWidth(), height = $(window).innerHeight(),dialog;
                        this.dialog = art.dialog.open(this.url, {
                            id: 'app_content_dialog_' + this.id,
                            title: '智慧福田' + this.title,
                            width: width * 0.98,
                            height: height - 200,
                            left: width * 0.01,
                            top: 50,
                            show: false,
                            close: function () {
                                that.trigger('onClose', that.id)
                            },
                            minCallback: function () {
                                that.trigger('onMin', that.id)
                            }
                        }
                       );
                    },
                    isVisible:function(){
                        return $(this.dialog.DOM.wrap).is(':visible');
                    },
                    focus: function () {
                        this.dialog.focus();
                    },
                    show: function () {
                        this.dialog.show();
                    },
                    close: function () {
                        this.dialog.close();
                    },
                    hide: function () {
                        this.dialog.hide();
                    }
                })
                var DxWinDialog = DialogBase.extend({
                    init: function (options) {
                        this._super(options);
                        var that = this;
                        this.dialog = window.open(this.url, this.id);
                        this.dialog.focus();
                    },
                    show: function () {
                        if (this.dialog.closed) {
                            this.dialog = window.open(this.url, this.id);
                        }
                    },
                    focus: function () {
                        this.dialog.focus();
                    },
                    close: function () {
                        if (!this.dialog.closed) {
                            this.dialog.close();
                        }
                    }
                });
                var DxLayerDialog = DialogBase.extend({
                    init: function (options) {
                        this._super(options);
                        var that = this;
                        that.layerIndex = layer.open({
                            type: 2,
                            title: 'fff',
                            closeBtn: 1,
                            area: ['80%', '80%'],
                            move: true,// - 触发拖动的元素
                            resize: false,// 是否允许拉伸
                            maxmin: true,// - 最大最小化。
                            anim: 0,
                            shade: 0,//遮罩
                            shadeClose: false,//是否点击遮罩关闭
                            skin: 'add-appdialog-wrap',
                            scrollbar: false,
                            fixed: true,//固定
                            content: [that.url],
                            min: function () {
                                return false;
                            }
                        });
                        that.layerId = '#layui-layer' + that.layerIndex;
                        this.hide();
                    },
                    isVisible:function(){
                        return $(this.layerId).is(":visible");
                    },
                    hide: function () {
                        $(this.layerId).hide();
                    },
                    show: function () {
                        $(this.layerId).show();
                    },
                    focus: function () {

                    },
                    close: function () {
                        layer.close(this.layerIndex);
                    }
                })

                var createDialog = function (dialogId, title, url, dialogType) {
                    url='http://www.baidu.com'
                    if (dialogType == 1) {
                        return new DxWinDialog({
                            id: dialogId,
                            title: title,
                            url: url
                        })
                    } else {
                        return new DxArtDialog({
                            id: dialogId,
                            title: title,
                            url: url
                        })
                    }
                }
                return {
                init: function (desktop) {
                    this.desktop = desktop;
                    this.dialogs = [];
                    this.onCloseHanlder = $.proxy(this.onCloseHanlder, this);
                    this.onMinHanlder = $.proxy(this.onMinHanlder, this);
                },
                createDialog: function (dialogId, title, url, newwindow) {
                    dialog = createDialog(dialogId, title, url, newwindow);
                    dialog.bind('onClose', this.onCloseHanlder);
                    dialog.bind('onMin', this.onMinHanlder);
                    this.set(dialogId, dialog);
                    return dialog;
                },
                onCloseHanlder: function (id) {
                    this.remove(id);
                    this.trigger('onClose', id);
                },
                onMinHanlder: function (id) {
                    this.trigger('onMin', id);
                },
                set: function (id, dialog) {
                    this.dialogs['app_content_dialog_' + id] = dialog;
                },
                get: function (id) {
                    return this.dialogs['app_content_dialog_' + id];
                },
                remove: function (id) {
                    var key = 'app_content_dialog_' + id;
                    this.dialogs[key] = null;
                    delete this.dialogs[key];
                },
                show:function(id){
                    var dialog = this.get(id);
                    if (dialog) {
                        dialog.show();
                        dialog.focus();
                    }
                },
                hide: function (id) {
                    var dialog = this.get(id);
                    if (dialog) {
                        dialog.hide();
                    }
                },
                close: function (id) {
                    var dialog = this.get(id);
                    if (dialog) {
                        dialog.close();
                        this.remove(id);
                    }
                }
               }
            })());
            // 桌面右击上下文菜单
            DesktopLayer.addPlugin('DesktopContextMenu', ['Taskbar'], {
                init: function (desktop, taskbar) {
                    this.taskbar = taskbar;
                },
                created: function (desktop) {
                    var that = this;
                    var MenuData = [
				[{
				    text: "显示桌面",
				    func: function () {
				        that.taskbar.hideAllTask();
				    }
				}, {
				    text: "关闭所有",
				    func: function () {
				        that.taskbar.removeAllTask();
				    }
				}, {
				    text: "刷新桌面",
				    func: function () {
				        window.location.reload();
				    }
				}],
				[/*systemSettings,{
				text: "主题设置",
				func: function() {
					   Windows.openSys({
							id :'themSetting',
							title :'设置主题',
							width :650,
							height:500,
							content :document.getElementById("themeSetting_wrap")
					   });
					}
				},*/
					{
					    text: "修改密码",
					    func: function () {
					       // modifyPassword();
					    }
					}, {
					    text: "消息面板",
					    data: [[{
					        text: "显示消息面板",
					        icon: "open_eye.png",
					        func: function () {
					            //var $message = $("#messagePanel");
					            //if ($message.attr("display") != "true") {
					            //    $('#messageContext').show();
					            //    $message.slideDown("slow");
					            //    $message.attr("display", "true");
					            //    $('#messageSlide').attr("extend", "true").attr("title", "收起消息面板").find('img').attr('src', ctx + "/images/system/arrows_icon01.png");
					            //}
					        }
					    }, {
					        text: "关闭消息面板",
					        icon: "close_eye.png",
					        func: function () {
					            //var $message = $("#messagePanel");
					            //if ($message.attr("display") != "false") {
					            //    $message.slideUp("slow");
					            //    $message.attr("display", "false");
					            //}
					        }
					    }
					    ]]
					}, {
					    text: "注销系统",
					    func: function () {
					        layer.confirm('您确定要退出当前系统?', {
					            btn: ['确定', '取消'] //按钮
					        }, function () {
					            window.location.href = ctx + "/index/logout";
					        }, function () { });
					    }
					}]
                    ];
                    desktop.wrapper.smartMenu(MenuData, {
                      name: 'desktop'
                  });
                }
            });
            return {
                // 初始化桌面
                initDesktop: function (config) {
                    new DesktopLayer(config)
                }
            };
        }())

用jquery写的一个PC端桌面应用管理界面

 

下载地址

相关标签: 桌面