/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */
(function ($) {
    window.layer = window.layui.layer;


    var $bodoy = $('body'),
        $main = $('#main-layout'),
        $foldSidebar = $('#foldSidebar');

    function sideFlexible() {
        var $icon = $('i.layui-icon', $foldSidebar),
            shrink = $main.is('.layadmin-side-shrink') ? 1 : 0;
        if (shrink) {
            $icon.removeClass('layui-icon-shrink-right').addClass('layui-icon-spread-left');
        } else {
            $icon.removeClass('layui-icon-spread-left').addClass('layui-icon-shrink-right');
            $('.layui-side-menu .layui-nav .layui-nav-item .layui-nav-child').parents().removeClass('layui-this');
        }
        $.cookie && $.cookie('LayAdminSide', shrink ? 'layadmin-side-shrink' : '');
    }

    sideFlexible();
    $(function () {
        $("html,body").animate({ scrollTop: 0, scrollLeft: 0 }, 120);
    });

    $bodoy.on('mouseenter', '.layadmin-side-shrink .layui-side .layui-nav-item.layui-menu-item-parent', function () {
        var $panel = $('> .layui-menu-body-panel', this);
        if (!$panel.length) return;
        var offset = $(this).offset(), vh = $(window).height();
        $panel.css({
            position: 'fixed',
            top: offset.top,
        }).show();
        $(this).unbind('mouseleave.layui').bind('mouseleave.layui', function () {
            $panel.hide().css('position', '');
        });
    });

    $foldSidebar.on('click', function () {
        var spread = $('i.layui-icon', this).is('.layui-icon-spread-left');
        $main[spread ? 'removeClass' : 'addClass']('layadmin-side-shrink');
        sideFlexible();
    });


    $bodoy.on('reload', '.layui-grid', function () {
        $(this).gridReloadData();
    }).on('submit', '.layui-grid form.layui-grid-search', function () {
        $(this).closest('.layui-grid').gridReloadData(1);
        return false;
    }).on('click', '.layui-grid .layui-laypage-next', function () {
        if ($(this).is('.layui-disabled')) return false;
        var $grid = $(this).closest('.layui-grid'),
            curpage = parseInt($grid.data('curpage')) || 1,
            pagetotal = parseInt($grid.data('pagetotal')) || 1;

        if ((curpage + 1) > pagetotal) return false;
        $grid.gridReloadData(curpage + 1);
        return false;
    }).on('click', '.layui-grid .layui-laypage-prev', function () {
        if ($(this).is('.layui-disabled')) return false;
        var $grid = $(this).closest('.layui-grid'),
            curpage = parseInt($grid.data('curpage')) || 1;
        if ((curpage - 1) <= 0) return false;
        $grid.gridReloadData(curpage - 1);
        return false;
    }).on('blur', '.layui-grid .layui-laypage-skip>input', function () {
        var jump = $(this).val().trim();
        if (isNaN(jump) || /^\s+$/.test(jump) || jump <= 0) {
            jump = 1;
        }
        $(this).val(parseInt(jump) || 1);
    }).on('keyup', '.layui-grid .layui-laypage-skip>input', function (event) {
        if (event.keyCode == "13") {
            //回车执行查询
            $(this).siblings('.layui-laypage-btn').trigger('click');
        }
    }).on('click', '.layui-grid .layui-laypage-skip .layui-laypage-btn', function () {
        var $grid = $(this).closest('.layui-grid'),
            pagetotal = parseInt($grid.data('pagetotal')) || 0,
            curpage = parseInt($grid.data('curpage')) || 1,
            jump = parseInt($(this).siblings('input').val().trim()) || 1;

        jump = (jump > pagetotal ? pagetotal : jump);
        jump = (jump < 1 ? 1 : jump);
        if (jump == curpage) return false;

        $(this).siblings('input').val(jump);
        $grid.gridReloadData(jump);
        return false;
    }).on('change', '.layui-grid .layui-laypage-limits>select', function () {
        $.cookie('PAGE_SIZE', $(this).val(), { expires: 365, path: '/' });
        $(this).closest('.layui-grid').gridReloadData(1);
        return;
    }).on('click', '.ueditor_footbtn', function () {
        var eid = $(this).data('id');
        var etype = $(this).data('type');
        var body = UE.getEditor(eid).getContent();
        var url = '';
        if (etype == 'imgrtol')
            url = '/Article/imgRemoteToLocal.html';
        else
            url = '/Article/linkClear.html';
        $.loading.show();
        $.post(window._global.root + url, { content: body }, function (res) {
            $.loading.hide();
            if (res.code) {
                UE.getEditor(eid).setContent(res.data.content);
                $.showMsg(true, res.msg);
            } else {
                $.showMsg(false, res.msg);
            }
        }, 'json');
    });
    //表格复选框事件处理
    layui.form.on('checkbox(layui-grid-checkbox)', function (data) {
        var elem = data.elem, $table = $(elem).closest('.layui-grid-table'), $tr = $(elem).closest('tr');
        if ($(elem).is('.checkAll')) {
            $('thead .checkbox .checkAll', $table).prop('checked', this.checked);
            $('tbody .checkbox [type="checkbox"]', $table).prop('checked', this.checked).trigger('change');
            elem.checked && $('tbody tr', $table).addClass('selected');
            !elem.checked && $('tbody tr', $table).removeClass('selected');
            layui.form.render('checkbox', 'layui-grid-form');
            return;
        }
        if ($(elem).is('.checkbox')) {
            !elem.checked && $('thead .checkbox .checkAll', $table).prop('checked', false);
            elem.checked && !$('tbody .checkbox [type="checkbox"]:not(:checked)', $table).length &&
            $('thead .checkbox .checkAll', $table).prop('checked', true);
            !elem.checked && $tr.removeClass('selected');
            elem.checked && $tr.addClass('selected');
            layui.form.render('checkbox', 'layui-grid-form');
            $(elem).trigger('change');
            return;
        }
        if ($(elem).is('.radio')) {
            if (elem.checked) {
                var $siblings = $tr.addClass('selected').siblings('.selected').removeClass('selected');
                $('.checkbox [type="checkbox"]:checked', $siblings).prop('checked', false);
            } else {
                $tr.removeClass('selected');
            }
            layui.form.render('checkbox', 'layui-grid-form');
            $(elem).trigger('change');
        }
    });


    $bodoy.on("mouseenter", "*[lay-tips]", function () {
        var e = $(this);
        if (!e.parent().hasClass("layui-nav-item") || $main.hasClass('layadmin-side-shrink')) {
            var t = e.attr("lay-tips")
                , i = e.attr("lay-offset")
                , n = e.attr("lay-direction") || 2
                , l = layer.tips(t, this, {
                tips: n || 1,
                time: -1,
                success: function (e, a) {
                    i && e.css("margin-left", i + "px")
                }
            });
            e.data("index", l)
        }
    }).on("mouseleave", "*[lay-tips]", function () {
        layer.close($(this).data('index'))
    }).on('mouseenter', '.tips', function () {
        var text = $(this).attr('tips') || $(this).data('tips-text'), direction = $(this).data('tips-direction') || 2, width = $(this).data('tips-width');
        if (!text) return;
        var layeindex = layer.tips(text, $(this), {
            time: false, tips: direction,
            success: function (layero, index) {
                if (width) $(layero).css('width', width);
            }
        });
        $(this).unbind('mouseleave.tips').on('mouseleave.tips', function () {
            layer.close(layeindex);
        });
        $(document).unbind('click.tips').on('click.tips', function () {
            layer.close(layeindex);
        });
    }).on('mouseenter', '.tips-img', function () {
        var off = $(this).offset(), wh = $(window).height(), load_url = $(this).attr('load-url') || $(this).attr('src');
        if (!load_url) return;
        var layeindex = layer.tips('<img class="tips-load-img" style="max-width:350px;max-height:350px;" src="' + load_url + '"/>', $(this), {
            tips: [2, '#1E9FFF'],
            time: false,
            success: function (layero, index) {
                $(layero).css('width', 'auto');
                $(layero).find('img.tips-load-img').unbind('load.tips-img').bind('load.tips-img', function () {
                    var py = wh - off.top;
                    var imgh = $(layero).height();
                    if (py < 361 && imgh > (py - 10)) {
                        $(layero).css('top', (off.top - (361 - py)));
                        $(layero).find('i.layui-layer-TipsG').css('top', (361 - py));
                    }
                });
            }
        });
        $(this).unbind('mouseleave.tips-img').bind('mouseleave.tips-img', function () {
            layer.close(layeindex);
        });
        $(document).unbind('click.tips-img').bind('click.tips-img', function () {
            layer.close(layeindex);
        });
    }).on('click', '[target="dialog"]', function () {
        var options = $(this).attr('options') || $(this).data('options') || {},
            url = $(this).attr('href'), vthis = this, arg = {};
        if ($.type(options) === 'string')
            options = eval("(" + options + ")") || {};
        options['type'] = options['type'] || 1;
        var $grid = $(vthis).closest('.layui-grid');
        options['success'] = options['success'] || function (layero, index) {
            $grid.length && $(layero).data('grid', $grid);
        }
        if (options['content']) {
            layer.open(options);
            return false;
        }
        if (options['argpk'] && $grid.length) {
            var ids = [];
            $('.selected :checked', $grid).each(function () {
                ids.push($(this).val());
            });
            if (options['argpk'] !== 'notMsg' && !ids.length) {
                $.msg('请选择要操作的数据行');
                return false;
            }
            ids.length ? arg['id'] = ids.join(',') : false;
        }
        if (!url) return false;
        options['url'] = url;
        options['data'] = arg;
        $.page(options);
        return false;
    }).on('click', '[target=confirm]', function () {
        var $this = $(this), msg = $this.attr('confirm') || $this.data('confirm') || $this.attr('msg'),
            argpk = $this.attr('argpk'), args = $this.data('args') || {};
        if (!msg) return false;
        if (argpk) {
            var $grid = $this.closest('.layui-grid');
            if ($grid.length) {
                var ids = [];
                $('.selected :checked', $grid).each(function () {
                    ids.push($(this).val());
                });
                if (!ids.length) {
                    $.showMsg(false, '请选择要操作的数据行');
                    return false;
                }
                args['id'] = ids.join(',');
                $this.data('args', args);
            }
        }
        $.confirm(msg, function (layero, index) {
            $this.ajax();
        });
        return false;
    }).on('click', '[target=ajax]', function () {
        $(this).ajax();
        return false;
    }).on('click', '.layui-date', function () {
        if ($(this).attr('lay-loaded')) return;
        layui.laydate.render({
            elem: this, //指定元素
            type: $(this).attr('lay-type') || 'datetime',
            format: $(this).attr('lay-format') || 'yyyy-MM-dd HH:mm:ss',
            value: $(this).val() || '',
            trigger: 'click',
            show: true,
            theme: 'molv',//墨绿主题
        });
        $(this).attr('lay-loaded', true);
    }).on('blur keyup', '[vtype]', function () {
        $.validatorFunc(this);
    });


    $bodoy.on('click', '[view-href]', function () {
        var $this = $(this),
            url = $this.attr('view-href');
        if (!url) {
            if ($main.hasClass('layadmin-side-shrink') && $this.next('.layui-nav-child').length) {
                $foldSidebar.trigger('click');
            }
            return;
        }
        $.openpage(url, {});

        if ($(this).closest('.layui-menu-body-panel').length) {
            $(this).closest('.layui-nav-item').addClass('layui-this').siblings().removeClass('layui-this');
        }

        // location.hash = url;
        if ($main.is('.layadmin-side-spread-sm')) {
            $foldSidebar.trigger('click');
        }
        //console.log(router);
    });

    // window.onhashchange = function () {
    //     var router = layui.router();
    //     if (!router.href) return;
    //     $.loading.show();
    //     $.get(router.href, function (rs) {
    //         $.loading.hide();
    //         $('#manage-container>.page-container').html(rs);
    //     });
    // }
    // window.onhashchange();

    $bodoy.on('click', '[target="page"]', function () {
        var ajaxConf = $(this).ajaxConf(),
            $container = $(this).closest('.page-container');
        $container.length || ($container = $('.page-container', $(this).closest('.manage-body')));
        $container.length || ($container = $(this).closest('.layui-layer-content'));
        $container.length || ($container = $('#manage-container .page-container'));
        if (!ajaxConf.url || ajaxConf.url.indexOf('javascript:') >= 0 || !$container.length) return false;

        $.openpage(ajaxConf.url, {}, $container);
        return false;
    });
    $bodoy.on('render', '.layui-dropdown-select', function () {
        if ($(this).attr('lay-loaded')) return;
        var $select = $(this);
        try {
            var data = JSON.parse($('textarea', $select).val());
        } catch (e) {
            data = [];
        }
        var placeholder = $('input[type=text]', $select).attr('placeholder');
        if (placeholder) {
            data.unshift({ id: 0, title: placeholder, type: "group" });
        }
        var mWidth = $select.width();
        layui.dropdown.render({
            elem: this,
            isSpreadItem: false,
            className: 'layui-select-menu',
            show: false,
            data: data,
            templet: '<div class="layui-menu-title {{d.id? \'\':\'layui-select-tips\'}}" lay-id="{{d.id}}">{{d.title}}</div>',
            style: 'min-width:' + mWidth + 'px;',
            ready: function (elemPanel, elem) {
                var that = this;
                $(elemPanel).appendTo($select)

                $bodoy.off('click.dropdown-select').on('click.dropdown-select', function () {
                    if ($(elemPanel).is(':visible')) {
                        $select.addClass('layui-form-selected');
                    } else {
                        $select.removeClass('layui-form-selected');
                    }
                });
                $('.layui-select-title', $select).off('click.dropdown-select').on('click.dropdown-select', function (e) {
                    if ($(elemPanel).is(':visible')) {
                        $(elemPanel).hide();
                    } else {
                        $(elemPanel).show();
                    }
                });
                $('.layui-menu-body-title', elemPanel).off('click.dropdown-select').on('click.dropdown-select', function () {
                    var data = $(this).closest('.layui-menu-item-group').data('item');
                    that.change(data, this);
                    $(elemPanel).hide();
                    $select.removeClass('layui-form-selected');
                    return false;
                });
                $('.layui-icon', elemPanel).off().on('click', function () {
                    $(this).toggleClass('layui-icon-up layui-icon-down');
                    $(this).closest('.layui-menu-item-group').toggleClass('layui-menu-item-down layui-menu-item-up');
                    return false;
                });
                $('.layui-dropdown-menu,.layui-menu-item-group', elemPanel).off().on('click', function () {
                    return false;
                });
                var id = $('input[type=hidden]', $select).val(),
                    $menu = $('[lay-id="' + id + '"]', elemPanel);
                $menu.addClass('layui-selected-menu');
                $menu.parents('.layui-menu-item-group').each(function () {
                    $(this).removeClass('layui-menu-item-up').addClass('layui-menu-item-down');
                    $('>.layui-menu-body-title .layui-icon', this).removeClass('layui-icon-down').addClass('layui-icon-up');
                    var $siblings = $(this).siblings().removeClass('layui-menu-item-down').addClass('layui-menu-item-up');
                    $siblings.find('.layui-menu-item-group.layui-menu-item-down').removeClass('layui-menu-item-down').addClass('layui-menu-item-up');
                    $siblings.find('.layui-icon.layui-icon-up').removeClass('layui-icon-up').addClass('layui-icon-down');
                });
            },
            change: function (item, othis) {
                item = item || { id: 0, title: '' };
                $('input[type=text]', $select).val(item.id > 0 ? item.title : '');
                $('input[type=hidden]', $select).val(item.id);
                $(othis).closest('.layui-select-menu').find('.layui-menu-title.layui-selected-menu').removeClass('layui-selected-menu');
                $('.layui-menu-title', othis).addClass('layui-selected-menu');
                $select.trigger('change', [item, othis]);
            }
        });

        function setItem(id, data) {
            $.each(data, function (idx, item) {
                if (item.id == id) {
                    $('input[type=text]', $select).val(item.title);
                    return false;
                }
                item.child && setItem(id, item.child);
            });
        }

        var id = $('input[type=hidden]', $select).val();
        if (id > 0) setItem(id, data);
        $(this).attr('lay-loaded', true);
    });

    layui.uploadRender = function (options) {
        options = $.isPlainObject(options) ? options : {};
        return layui.upload.render($.extend({
            elem: '[lay-upload]',
            accept: 'file',
            before: function (obj) {
                this.loadlayer = $.loading.show({
                    content: '<i class="pa up-progress" style="bottom: -20px;left:50%;transform: translateX(-50%);color:#8cf118">0%</i>',
                });
            },
            progress: function (n, elem, res, index) {
                $('i.up-progress', '#layui-layer' + this.loadlayer).html(n + '%');
            },
            done: function (res, index, upload) {
                $.loading.hide();
                var item = this.item,
                    callback = $(item).data('callback') || options.callback;
                if (callback && callback.call(item, res) === false) return;
                res && res.msg && $.showMsg(res.code, res.msg);
                if (res && res.url) {
                    var $p = $(item).parent();
                    $('[lay-upvalue]', $p).val(res.url);
                    $('[lay-uphref]', $p).attr('href', res.url);
                    $('[lay-upsrc]', $p).attr('src', res.url);
                }
            },
            error: function () {
                $.loading.hide();
            }
        }, options));
    };


    layui.render = function ($container) {
        layui.element.render();
        layui.form.render();
        layui.uploadRender();
        $('.layui-dropdown-select').trigger('render');
    };

    layui.form.config.verType = 'tips';
    layui.form.on('submit', function (data) {
        if (!$.validatorFunc(data.form)) return false;
        $(data.form).ajax();
        return false;
    });

    var clipboard = new Clipboard('[data-clipboard-text]');
    clipboard.on('success', function (e) {
        $.msg('复制成功！');
    });

})(window.jQuery);
