/**
 * date:2020/02/27
 * author:Mr.Chung
 * version:2.0
 * description:layuimini 菜单框架扩展
 */
layui.define(["element", "laytpl", "jquery", "miniTab"], function (exports) {
    var element = layui.element,
        $ = layui.$,
        laytpl = layui.laytpl,
        layer = layui.layer;
    var navList = []
    var options = {
        iniUrl: url.menu,    // 初始化接口
        clearUrl: "api/clear.json", // 缓存清理接口
        urlHashLocation: true,      // 是否打开hash定位
        bgColorDefault: false,      // 主题默认配置
        multiModule: false,          // 是否开启多模块
        menuChildOpen: false,       // 是否默认展开菜单
        loadingTime: 0,             // 初始化加载时间
        pageAnim: true,             // iframe窗口动画
        maxTabNum: 20,              // 最大的tab打开数量
    };
    var miniMenu = {

        /**
         * 菜单初始化
         * @param options.menuList   菜单数据信息
         * @param options.multiModule 是否开启多模块
         * @param options.menuChildOpen 是否展开子菜单
         */
        render: function (options) {
            options.menuList = options.menuList || [];
            options.multiModule = options.multiModule || false;
            options.menuChildOpen = options.menuChildOpen || false;
            if (options.multiModule) {
                miniMenu.renderMultiModule(options.menuList, options.menuChildOpen);
            } else {
                miniMenu.renderSingleModule(options.menuList, options.menuChildOpen);
            }
            miniMenu.listen();
            miniMenu.bindFunction()
        },

        /**
         * 单模块
         * @param menuList 菜单数据
         * @param menuChildOpen 是否默认展开
         */
        renderSingleModule: function (menuList, menuChildOpen) {
            menuList = menuList || [];
            var leftMenuHtml = '',
                childOpenClass = '',
                leftMenuCheckDefault = 'layui-this';
            var me = this;
            if (menuChildOpen) childOpenClass = ' layui-nav-itemed';
            leftMenuHtml = this.renderLeftMenu(menuList, { childOpenClass: childOpenClass });
            $('.layui-layout-body').addClass('layuimini-single-module'); //单模块标识
            $('.layuimini-header-menu').remove();
            $('.layuimini-menu-left').html(leftMenuHtml);
            var selectLi = '<li class="layui-nav-item search-li"><i class="layui-icon layui-icon-search searchEvent"></i><i class="layui-icon layui-icon-search searchEvent-mini"></i><input value="" id="search" placeholder="请输入搜索内容"><div class="mc-hover-show"><input value=""  placeholder="请输入搜索内容"></div> </li>'
            $('.layui-left-nav-tree').prepend(selectLi)
            element.init();
        },
        /*搜索导航栏绑定事件*/
        bindFunction: function () {
            var navData = JSON.parse(sessionStorage.getItem('menu')).menuInfo || []
            var selectList = []
            $('.layuimini-mini .searchEvent-mini').off('click').click(function () {
                $('.mc-hover-show').animate({ left: '60px' })
                $('.mc-hover-show input').focus()
            })
            $('.mc-hover-show input').blur(function () {
                $('.mc-hover-show').animate({ left: '-1000px' })
            })
            $('.mc-hover-show input').off('keydown').keydown(function (e) {
                selectList = []
                navList = []
                if (e.keyCode == 13) {
                    var value = $(this).val()
                    var navLsit = miniMenu.getNavList(navData)
                    if (value) {
                        for (var i = 0; i < navLsit.length; i++) {
                            if (navLsit[i].title.indexOf(value) != -1) {
                                selectList.push(navLsit[i])
                            }
                        }
                        var htmlStr = '<dl class="layui-nav-child tips-dd">{innerHTML}</dl>'
                        var innerHTML = ''
                        for (var i = 0; i < selectList.length; i++) {
                            innerHTML += '<dd><a href="javascript:;" class="layui-menu-tips" layuimini-href="' + selectList[i].href + '" target="_self"><iclass="layui-icon layui-icon-ok-circle"></i><span class="layui-left-nav">' + selectList[i].title + '</span></a></dd>'
                        }
                        var html = htmlStr.replace('{innerHTML}', innerHTML)
                        window.openTips = layer.tips(html, $(this), {
                            tips: [2, '#2f4056'],
                            time: 300000,
                            skin: "popup-tips",
                            success: function (el) {
                                $(el).css({ left: 60, top: 30 });
                                element.render();
                                $('.mc-hover-show').animate({ left: '-1000px' })
                            }
                        });
                        miniMenu.listen();
                    }
                }

            })
            $('#search').keydown(function (e) {
                selectList = []
                navList = []
                if (e.keyCode == 13) {
                    var value = $('#search').val()
                    var navLsit = miniMenu.getNavList(navData)
                    if (value) {
                        for (var i = 0; i < navLsit.length; i++) {
                            if (navLsit[i].title.indexOf(value) != -1) {
                                selectList.push(navLsit[i])
                            }
                        }
                        miniMenu.render(Object.assign({ menuList: selectList }, miniMenu, options));
                    } else {
                        miniMenu.render(Object.assign({ menuList: JSON.parse(sessionStorage.getItem('menu')).menuInfo }, options))
                    }
                }
            })
            $('.searchEvent').click(function () {
                selectList = []
                navList = []
                var value = $('#search').val()
                var navLsit = miniMenu.getNavList(navData)
                if (value) {
                    for (var i = 0; i < navLsit.length; i++) {
                        if (navLsit[i].title.indexOf(value) != -1) {
                            selectList.push(navLsit[i])
                        }
                    }
                    miniMenu.render(Object.assign({ menuList: selectList }, miniMenu, options));
                } else {
                    miniMenu.render(Object.assign({ menuList: JSON.parse(sessionStorage.getItem('menu')).menuInfo }, options))
                }
            })
        },
        // 格式化导航栏数据
        getNavList: function (list) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].href != '#') {
                    navList.push({
                        title: list[i].title,
                        href: list[i].href,
                        target: list[i].target
                    })
                }
                if (list[i].child && list[i].child.length != 0) {
                    miniMenu.getNavList(list[i].child)
                }
            }
            return navList
        },
        /**
         * 渲染一级菜单
         */
        compileMenu: function (menu, isSub) {
            var menuHtml = '<li {{#if( d.menu){ }}  data-menu="{{d.menu}}" {{#}}} class="layui-nav-item menu-li {{d.childOpenClass}} {{d.className}}"  {{#if( d.id){ }}  id="{{d.id}}" {{#}}}> <a {{#if( d.href){ }} layuimini-href="{{d.href}}" {{#}}} {{#if( d.target){ }}  target="{{d.target}}" {{#}}} href="javascript:;">{{#if( d.icon){ }}  <i class="{{d.icon}}"></i> {{#}}} <span class="layui-left-nav">{{d.title}}</span></a>  {{# if(d.children){}} {{d.children}} {{#}}} </li>';
            if (isSub) {
                menuHtml = '<dd class="menu-dd {{d.childOpenClass}} {{ d.className }}"> <a href="javascript:;"  {{#if( d.menu){ }}  data-menu="{{d.menu}}" {{#}}} {{#if( d.id){ }}  id="{{d.id}}" {{#}}} {{#if(( !d.child || !d.child.length ) && d.href){ }} layuimini-href="{{d.href}}" {{#}}} {{#if( d.target){ }}  target="{{d.target}}" {{#}}}> {{#if( d.icon){ }}  <i class="{{d.icon}}"></i> {{#}}} <span class="layui-left-nav"> {{d.title}}</span></a> {{# if(d.children){}} {{d.children}} {{#}}}</dd>'
            }
            return laytpl(menuHtml).render(menu);
        },
        compileMenuContainer: function (menu, isSub) {
            var wrapperHtml = '<ul class="layui-nav layui-nav-tree layui-left-nav-tree {{d.className}}" id="{{d.id}}">{{d.children}}</ul>';
            if (isSub) {
                wrapperHtml = '<dl class="layui-nav-child ">{{d.children}}</dl>';
            }
            if (!menu.children) {
                return "";
            }
            return laytpl(wrapperHtml).render(menu);
        },

        each: function (list, callback) {
            var _list = [];
            for (var i = 0, length = list.length; i < length; i++) {
                _list[i] = callback(i, list[i]);
            }
            return _list;
        },
        renderChildrenMenu: function (menuList, options) {
            var me = this;
            menuList = menuList || [];
            var html = this.each(menuList, function (idx, menu) {
                if (menu.child && menu.child.length) {
                    menu.children = me.renderChildrenMenu(menu.child, { childOpenClass: options.childOpenClass || '' });
                }
                menu.className = "";
                menu.childOpenClass = options.childOpenClass || ''
                return me.compileMenu(menu, true)
            }).join("");
            return me.compileMenuContainer({ children: html }, true)
        },
        renderLeftMenu: function (leftMenus, options) {
            options = options || {};
            var me = this;
            var leftMenusHtml = me.each(leftMenus || [], function (idx, leftMenu) { // 左侧菜单遍历
                var children = me.renderChildrenMenu(leftMenu.child, { childOpenClass: options.childOpenClass });
                var leftMenuHtml = me.compileMenu({
                    href: leftMenu.href,
                    target: leftMenu.target,
                    childOpenClass: options.childOpenClass,
                    icon: leftMenu.icon,
                    title: leftMenu.title,
                    children: children,
                    className: '',
                });
                return leftMenuHtml;
            }).join("");

            leftMenusHtml = me.compileMenuContainer({ id: options.parentMenuId, className: options.leftMenuCheckDefault, children: leftMenusHtml });
            return leftMenusHtml;
        },
        /**
         * 多模块
         * @param menuList 菜单数据
         * @param menuChildOpen 是否默认展开
         */
        renderMultiModule: function (menuList, menuChildOpen) {
            menuList = menuList || [];
            var me = this;
            var headerMenuHtml = '',
                headerMobileMenuHtml = '',
                leftMenuHtml = '',
                leftMenuCheckDefault = 'layui-this',
                childOpenClass = '',
                headerMenuCheckDefault = 'layui-this';

            if (menuChildOpen) childOpenClass = ' layui-nav-itemed';
            var headerMenuHtml = this.each(menuList, function (index, val) { //顶部菜单渲染
                var menu = 'multi_module_' + index;
                var id = menu + "HeaderId";
                var topMenuItemHtml = "";
                topMenuItemHtml = me.compileMenu({
                    className: headerMenuCheckDefault,
                    menu: menu,
                    id: id,
                    title: val.title,
                    href: "",
                    target: "",
                    children: ""
                });
                leftMenuHtml += me.renderLeftMenu(val.child, {
                    parentMenuId: menu,
                    childOpenClass: childOpenClass,
                    leftMenuCheckDefault: leftMenuCheckDefault
                });
                headerMobileMenuHtml += me.compileMenu({ id: id, menu: menu, id: id, icon: val.icon, title: val.title, }, true);
                headerMenuCheckDefault = "";
                leftMenuCheckDefault = "layui-hide";
                return topMenuItemHtml;
            }).join("");
            $('.layui-layout-body').addClass('layuimini-multi-module'); //多模块标识
            $('.layuimini-menu-header-pc').html(headerMenuHtml); //电脑
            $('.layuimini-menu-left').html(leftMenuHtml);
            $('.layuimini-menu-header-mobile').html(headerMobileMenuHtml); //手机
            element.init();
        },

        /**
         * 监听
         */
        listen: function () {
            /**
             * 菜单模块切换
             */
            $('body').on('click', '[data-menu]', function () {
                var loading = layer.load(0, { shade: false, time: 2 * 1000 });
                var menuId = $(this).attr('data-menu');
                // header
                $(".layuimini-header-menu .layui-nav-item.layui-this").removeClass('layui-this');
                $(this).addClass('layui-this');
                // left
                $(".layuimini-menu-left .layui-nav.layui-nav-tree.layui-this").addClass('layui-hide');
                $(".layuimini-menu-left .layui-nav.layui-nav-tree.layui-this.layui-hide").removeClass('layui-this');
                $("#" + menuId).removeClass('layui-hide');
                $("#" + menuId).addClass('layui-this');
                layer.close(loading);
            });

            /**
             * 菜单缩放
             */
            $('body').off('click').on('click', '.layuimini-site-mobile', function () {
                var loading = layer.load(0, { shade: false, time: 2 * 1000 });
                var isShow = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (isShow == 1) { // 缩放
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 0);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-indent');
                    $('.layui-layout-body').removeClass('layuimini-all');
                    $('.layui-layout-body').addClass('layuimini-mini');
                } else { // 正常
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 1);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-outdent');
                    $('.layui-layout-body').removeClass('layuimini-mini');
                    $('.layui-layout-body').addClass('layuimini-all');
                    layer.close(window.openTips);
                }
                element.init();
                layer.close(loading);
            });
            /**
             * 菜单缩放
             */
            $('body').on('click', '[data-side-fold]', function () {
                var loading = layer.load(0, { shade: false, time: 2 * 1000 });
                var isShow = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (isShow == 1) { // 缩放
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 0);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-indent');
                    $('.layui-layout-body').removeClass('layuimini-all');
                    $('.layui-layout-body').addClass('layuimini-mini');
                    // $(".menu-li").each(function (idx,el) {
                    //     $(el).addClass("hidden-sub-menu");
                    // });

                } else { // 正常
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 1);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-outdent');
                    $('.layui-layout-body').removeClass('layuimini-mini');
                    $('.layui-layout-body').addClass('layuimini-all');
                    // $(".menu-li").each(function (idx,el) {
                    //     $(el).removeClass("hidden-sub-menu");
                    // });
                    layer.close(window.openTips);
                }
                element.init();
                layer.close(loading);
                miniMenu.bindFunction()
            });

            /**
             * 手机端点开模块
             */
            $('body').on('click', '.layuimini-header-menu.layuimini-mobile-show dd', function () {
                var loading = layer.load(0, { shade: false, time: 2 * 1000 });
                var check = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (check === "1") {
                    $('.layuimini-site-mobile').trigger("click");
                    element.init();
                }
                layer.close(loading);
            });
            $('body').on('click', '.layuimini-make', function () {
                $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 1);
                $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-outdent');
                $('.layui-layout-body').removeClass('layuimini-mini');
                $('.layui-layout-body').addClass('layuimini-all');
                layer.close(window.openTips);
            });
            // 菜单跳转
            $('body').on('click', '[layuimini-href]', function () {
                var loading = layer.load(0, { shade: false, time: 2 * 1000 });
                var tabId = $(this).attr('layuimini-href'),
                    href = $(this).attr('layuimini-href'),
                    title = $(this).text(),
                    target = $(this).attr('target');

                var el = $("[layuimini-href='" + href + "']", ".layuimini-menu-left");
                layer.close(window.openTips);
                if (el.length) {
                    $(el).closest(".layui-nav-tree").find(".layui-this").removeClass("layui-this");
                    $(el).parent().addClass("layui-this");
                }

                if (target === '_blank') {
                    layer.close(loading);
                    window.open(href, "_blank");
                    return false;
                }

                if (tabId === null || tabId === undefined) tabId = new Date().getTime();
                var checkTab = miniTab.check(tabId);
                if (!checkTab) {
                    miniTab.create({
                        tabId: tabId,
                        href: href,
                        title: title,
                        isIframe: false,
                        maxTabNum: options.maxTabNum,
                    });
                }
                element.tabChange('layuiminiTab', tabId);
                layer.close(loading);
            });
        },

    };


    exports("miniMenu", miniMenu);
});
