define('jForum', [
    'require',
    'jquery',
    'jForumXhr',
    'jForumUtils',
    'jForumTemplate',
    'jForumMember',
    'jForumToolbar',
    'jForumPagination',
    'jForumLoad',
    'jForumXhrDefer',
    'jForumSocket',
    'store',
    'bootstrap',
    'ekko-lightbox',
    'parsley',
    'purl'
], function (require, $, xhr, util, template, member, toolbar, pagination, loadBar, xhrDefer, socket, store, bootstrap, lightbox, parsley, purl) {
    'use strict';

    var jForum = (function () {
        function init() {
            //分页加载数据
            $('.page_navigation').on('initDataEvent', function (e) {
                var _pn = $(e.target);
                var rawdata = {};
                rawdata.uri = _pn.attr('data-handler');
                rawdata.data = util.parseQueryJson(_pn.attr('data-query'));
                rawdata.callFun = _pn.attr('data-function');
                rawdata.defFun = _pn.attr('data-deferred') || null;
                if (!$.isEmptyObject(rawdata.data)) {
                    rawdata.uri += '?' + $.param(rawdata.data);
                }
                //
                var option = {
                    url: rawdata.uri,
                    ajaxBefore: function () {
                        loadBar.start();
                    },
                    ajaxComplete: function () {
                        loadBar.stop();
                    },
                    randerPageStruct: function (pageHtmlStruct, pnSelector) {
                        var extEle = $('#page_another_navigation');
                        extEle.find(pnSelector).remove();
                        extEle.append(pageHtmlStruct);
                    },
                    jsonCallback: function (jsonArray) {
                        if ($.isEmptyObject(jsonArray)) {
                            return;
                        }
                        var fn = template[rawdata.callFun];
                        if (typeof fn === "function") {
                            fn.call(this, jsonArray);
                        }
                    },
                    deferCallback: function(){
                        var deferFun = xhrDefer[rawdata.defFun];
                        if (typeof deferFun === "function") {
                            deferFun.call(this, xhr, template);
                        }
                    }
                };
                paginationFunction(_pn, option).fail(function () {
                    console.log('[page_navigation] execute fail');
                });
            }).trigger('initDataEvent');
            //ajax
            $('[data-result="loader.json"]').on('loadDataEvent', function (e) {
                var _a = $(e.target);
                var rawdata = {};
                rawdata.uri = _a.attr('data-handler');
                rawdata.data = util.parseQueryJson(_a.attr('data-query') || '');
                rawdata.allowEmpty = $.parseJSON(_a.attr('data-empty-show') || 'true');
                rawdata.callFun = _a.attr('data-template-function');
                //
                xhr.jsonLoader(rawdata.uri, rawdata.data, rawdata.allowEmpty, _a).done(function (data) {
                    try {
                        template[rawdata.callFun](data, _a);
                    } catch (e) { }
                });
            }).trigger('loadDataEvent');
            $('[data-result="loader.jsonp"]').on('loadDataEvent', function (e) { //topic/move
                var _b = $(e.target);
                var rawdata = {};
                rawdata.uri = _b.attr('data-handler');
                rawdata.callFun = _b.attr('data-function');
                rawdata.data = util.parseQueryJson(_b.attr('data-query'));
                var container = _b.attr('data-container') || null;
                if (container) {
                    rawdata.data.box = container;
                }
                //
                xhr.jsonpLoader(rawdata.uri, rawdata.data, _b).done(function (data) {
                    try {
                        template[rawdata.callFun](data);
                    } catch (e) { }
                });
            }).trigger('loadDataEvent');
            $('[data-result="click.jsonp"]').on('click', 'button[data-toggle="dropdown"]', function (e) { //topic[board]/view
                var parent = $(this).parent(); //改用e.target有一个弹出不能用
                var rawdata = {};
                rawdata.uri = parent.attr('data-handler');
                rawdata.data = util.parseQueryJson(parent.attr('data-query'));
                rawdata.callFun = parent.attr('data-function');
                if (parent.attr('data-selector')) {
                    var currentId = "dynamic-box-" + util.randomAlphaNumeric(8);
                    parent.find(parent.attr('data-selector')).attr('id', currentId);
                    if ($('#' + currentId).children().length > 0) {
                        return;
                    }
                    rawdata.data.box = currentId;
                }
                //
                xhr.jsonpLoader(rawdata.uri, rawdata.data, parent).done(function (data) {
                    try {
                        template[rawdata.callFun](data);
                    } catch (e) { }
                });
            });

            $('[data-result="batch.jsonp"]').on('loadDataEvent', function (e) { //[/search|/board|/volumes]/index.jsp
                var _c = $(e.target);
                var rawdata = {};
                rawdata.uri = _c.attr('data-handler');
                rawdata.callFun = _c.attr('data-function');
                rawdata.queryParamKey = _c.attr('data-param');
                rawdata.idSelector = _c.attr('data-record');
                rawdata.data = util.parseQueryJson(_c.attr('data-query'));
                //
                rawdata.data[rawdata.queryParamKey] = $(rawdata.idSelector).map(function () {
                    var reg = /\[(data-(.*?))\]/g;
                    var dataAttrName = rawdata.idSelector.match(reg)[0].replace('[', '').replace(']', '');
                    return this.getAttribute(dataAttrName);
                }).get().join(",");
                xhr.jsonpLoader(rawdata.uri, rawdata.data, _c).done(function (data) {
                    try {
                        template[rawdata.callFun](data);
                    } catch (e) { }
                });
            }).trigger('loadDataEvent');
            $('.load_content_section').on('initDataEvent', function (e) {
                var _d = $(e.target);
                var rawdata = {};
                rawdata.uri = _d.attr('data-handler');
                rawdata.callFun = _d.attr('data-function');
                rawdata.data = util.parseQueryJson(_d.attr('data-query'));
                //
                xhr.bodyLoader(rawdata.uri, rawdata.callFun, rawdata.data, _d);
            }).trigger('initDataEvent');
            $('body').on('click', '.action-cmd', function (e) {
                var _f = $(this);
                var rawdata = {};
                rawdata.uri = _f.attr('data-handler');
                rawdata.data = util.parseQueryJson(_f.attr('data-query'));
                rawdata.callFun = _f.attr('data-function');
                rawdata.tip = $.parseJSON(_f.attr('data-acctip') || 'true');
                //
                xhr.action(rawdata.uri, rawdata.callFun, rawdata.data, rawdata.tip, _f);
            });
            //会员主页的发送消息|话题会员弹出层的消息[NW]
            $('body').on('click', '.message-transmit', function (e) {
                //在线吗
                var cam = member.get();
                if ($.isEmptyObject(cam) || parseInt(cam.id) < 1) {
                    return util.errorMessage('暂不支持游客发送消息');
                }
                var requestURI = $(this).attr('data-handler');
                $.confirm({
                    title: '新消息',
                    closeIcon: true,
                    closeIconClass: 'ico-sm mdi mdi-close',
                    content: '<form action=""><div class="form-group"><textarea class="form-control" name="content" required="required" rows="3" placeholder="输入消息的内容"></textarea></div></form>',
                    buttons: {
                        formSubmit: {
                            text: '发送',
                            btnClass: 'btn-blue',
                            action: function () {
                                var content = this.$content.find('textarea[name=content]').val();
                                if (util.isBlank(content)) {
                                    this.$content.find('textarea[name=content]').focus();
                                    return false;
                                }
                                var requestParam = {};
                                requestParam.content = content;
                                xhr.jsonPost(requestURI, {
                                    data: requestParam,
                                    jsonCallback: transmitMessageResult,
                                    failCallback: function (jqXHR, textStatus, errorThrown) {
                                        if (textStatus === 'error') {
                                            var err = $.parseJSON(jqXHR.responseText);
                                            if (err.level && err.level === 'err') {
                                                return util.errorMessage(err.message);
                                            }
                                        }
                                        util.errorMessage('当前操作因错误而异外中止');
                                    }
                                });
                            }
                        }
                    },
                    onContentReady: function () {
                        var jc = this;
                        this.$content.find('form').on('submit', function (e) {
                            e.preventDefault();
                            jc.$$formSubmit.trigger('click');
                        });
                    }
                });
                return false;
            });
            //版块导航的选中跳转
            $('.board-navigator-select').on('click', function (e) {
                var _h = $(this); _h.html('正在加载数据');
                var currentId = "board-navigator-" + util.randomAlphaNumeric(8);
                var parent = _h.parents('div.board-navigator-box'); parent.attr('id', currentId);
                var rawdata = {};
                rawdata.uri = parent.attr('data-handler');
                rawdata.callFun = parent.attr('data-function');
                rawdata.data = { 'box': currentId };
                //
                xhr.jsonpLoader(rawdata.uri, rawdata.data, _h).done(function (data) {
                    try {
                        template[rawdata.callFun](data);
                    } catch (e) { }
                });
            });
            //话题:收藏|点赞,版块:收藏
            $('.action-cache').bind('initEvent', function (e) {
                var _ac = $(e.target);
                //是否存在缓存
                var action = _ac.attr('data-action');
                var connect = _ac.attr('data-action-key');
                //存在设置为disable
                var cacheVal = store.get(action + '#' + connect);
                if (!util.isBlank(cacheVal) && cacheVal) {
                    var d = _ac.text().trim();
                    _ac.prop('disabled', true).html(_ac.html().replace(d, "已" + d));
                }
            }).trigger('initEvent');
            //轮播图
            $('[data-carousel="bootstrap"]').on('loadDataEvent', function (e) {
                var self = $(this);
                var rawdata = {};
                rawdata.uri = self.attr('data-handler');
                rawdata.data = util.parseQueryJson(self.attr('data-query'));
                xhr.jsonGet(rawdata.uri, { data: rawdata.data }).done(function (data) {
                    self.find('.ld-spin').remove();
                    if ($.isEmptyObject(data)) {
                        self.css('height', '0');
                        return;
                    }

                    template.drawCarousel(data, self);
                });
            }).trigger('loadDataEvent');
            // 版块最新的话题
            $('#board_topic_collect').on('loadDataEvent', function (e) {
                var _k = $(e.target); 
                //threadsPushHandler(_k);
                threadSizePushHandler(_k);
            }).trigger('loadDataEvent');
            //提示
            $('[data-toggle="tooltip"]').tooltip();
            $('[data-toggle="popover"]').popover();
            try {
                $('.dropdown-toggle').dropdown();
            } catch (e) { }
            //返回浏览历史的上一条
            $('.historyBack').on('click', function (e) {
                e.preventDefault();
                window.history.back();
                return false;
            });
            //防止多次提交
            $('[data-submit="once"]').one('submit', function () {
                var submitBtn = $(this).find('[type="submit"]');
                submitBtn.prop('disabled', true).val(submitBtn.attr('data-submit-disabled') || '数据发送中');
                return true;
            });
            //像册放大图
            $(document).on('click', '[data-toggle="lightbox"]', function (event) {
                event.preventDefault();
                $(this).ekkoLightbox({ alwaysShowClose: true });
            });
            //查看未知的新话题@20201015
            $('#unknow_topic_tip').on('click', 'a', function(event){
                event.preventDefault();
                var _tt = $(this);
                var reqData = {};
                reqData.id = _tt.attr('data-board');
                reqData.stamp = _tt.attr('data-stamp');
                //?
                xhr.jsonGet(BASE+'/loader/board/topic/recent.json', {data: reqData}).done(function (data) {
                    //?
                    if ($.isEmptyObject(data)) {
                        return;
                    }
                    //?
                    var _btc = $('#board_topic_collect');
                    $('html, body').animate({ scrollTop: _btc.offset().top }, 500, function(){
                    	_tt.parent().parent().hide('normal', function(){
                    	    var _uttEle = $(this).removeClass('fix_style_tip');
                    	    _uttEle.find('span').remove();
                    	    _btc.attr('data-ux', util.getUnixStamp());
                    	});
                    });
                    //?
                    var _l = template;
                    $.each(data, function (index, item) {
                        _l.drawUpdatedTopics(item, 'board_topic_collect', true);
                    });
                });
            });
            //侧边栏的工具按钮
            $('#sideTool').sideToolBar();
            //加载今天的公告
            showTodayNotice();
            //
            member.init();
            //自定义加载模块
            var curPath = purl().attr('path');
            if (curPath.startsWith('/topic') || curPath === '/posts/create' || curPath === '/topic/create') {
                console.log('[module]welcome in topic page');
                requirejs(['jForumThreads'], function (threads) { threads.init(); });
            }
            if (curPath.startsWith('/message')) {
                console.log('[module]welcome in message page');
                requirejs(['jForumMessage'], function (message) { message.init(); });
            }
            if (curPath === '/board/home') {
                //话题/回复/会员统计
                $('#online-list-stats').bind('loadDataEvent', function (e) {
                    var _g = $(e.target);
                    var boardStatsURI = _g.attr('data-board');
                    var memberStatsURI = _g.attr('data-member');
                    //
                    getBoardStats(boardStatsURI).always(getMemberStats(memberStatsURI)).fail(function () { console.log("[promise-stats]出错啦！"); });
                }).trigger('loadDataEvent');
            }
        }
        //私信的响应
        function transmitMessageResult(json) {
            if ($.isEmptyObject(json)) {
                util.errorMessage("操作因异常而中止");
                return;
            }
            if (parseInt(json.id) > 0) {
                util.tipDialog({ "message": "发送成功", "level": "acc", "refresh": false });
                return;
            }
            utils.errorMessage("消息发送失败");
        };
        //版块主页的 汇总统计
        function getBoardStats(pURI) {
            return xhr.jsonGet(pURI, {
                jsonCallback: function (json) {
                    $('#online-list-stats').find('#stats-replies').html(json.replies);
                    $('#online-list-stats').find('#stats-threads').html(json.threads);
                }
            });
        };
        //版块主页的 会员统计
        function getMemberStats(pURI) {
            return xhr.jsonGet(pURI, {
                jsonCallback: function (json) {
                    $('#online-list-stats').find('#stats-member').html(json.members);
                    $('#stats-onlines').html(json.onlines);
                    $('#stats-onlines-member').html(json.onlines);
                    var rm = $.parseJSON(json.recentMember);

                    if (!$.isEmptyObject(rm)) {
                        var T = '<a href="/member/%MID%.xhtml" class="username">%MN%</a>'.replace('%MID%', rm.id).replace('%MN%', rm.title);
                        $('#online-list-stats').find('#stats-recent-member').html(T);
                    }
                }
            });
        };
        //未知的新话题
        function threadsPushHandler(_k) {
            _k.attr('data-ux', util.getUnixStamp()); //一开始的时间戳
            try {
                if (_k.attr('data-socket-uri') && _k.attr('data-board')) {
                    var _st = new socket(_k.attr('data-socket-uri'), _k, {
                        sendDataFun: function (jqEle) {
                            var data = {};
                            data.id = jqEle.attr('data-board');
                            data.cmd = 1;
                            data.ux = jqEle.attr('data-ux');
                            return data;
                        },
                        callbackFun: updateNewsTopices
                    });
                    _st.init('ThreadsNotice');
                    _st.start(60000);
                }
            } catch (e) { console.log('thread socket file lost'); }
        }
        //未知的新话题数量@20201015
        function threadSizePushHandler(_k) {
            _k.attr('data-ux', util.getUnixStamp()); //一开始的时间戳
            try {
                if (_k.attr('data-socket-uri') && _k.attr('data-board')) {
                    var _st = new socket(_k.attr('data-socket-uri'), _k, {
                        sendDataFun: function (jqEle) {
                            var data = {};
                            data.id = jqEle.attr('data-board');
                            data.cmd = 2;
                            data.ux = jqEle.attr('data-ux');
                            return data;
                        },
                        callbackFun: updateunKnowThreadSize
                    });
                    _st.init('ThreadsNotice');
                    _st.start(60000);
                }
            } catch (e) { console.log('thread socket file lost'); }
        }
        //新话题数量推送回调
        function updateunKnowThreadSize(sockplaindata){
            var jsonObj = $.parseJSON(sockplaindata);
            if ($.isEmptyObject(jsonObj)) {
                return;
            }
            if(!jsonObj.size || parseInt(jsonObj.size) == 0){
                return;
            }
            if($('#unknow_topic_tip').find('span').length == 1){ //已经有提示消息了
                return;
            }
            $('#unknow_topic_tip')
                .html('<span>新话题已经赶来了&nbsp;,&nbsp;<a href="javascript:;" data-stamp="%STAMP%" data-board="%ID%">点击查看</a></span>'.replace('%STAMP%', jsonObj.ux).replace('%ID%', jsonObj.id))
                .slideDown(1000, 'linear', function(){
                    $(this).show();
            });
        }
        //新话题列表推送回调
        function updateNewsTopices(sockplaindata) {
            var jsonArray = $.parseJSON(sockplaindata);
            if ($.isEmptyObject(jsonArray)) {
                return;
            }
            $('#board_topic_collect').attr('data-ux', util.getUnixStamp());
            var _l = template;
            $.each(jsonArray, function (index, item) {
                _l.drawUpdatedTopics(item, 'board_topic_collect', true);
            });
        };
        // 加载公告
        function showTodayNotice() {
            xhr.jsonGet(BASE + '/message/notice', { jsonCallback: template.poperNotice });
        };
        function paginationFunction(jqEle, option) {
            var defer = $.Deferred();
            var gtx = new pagination(defer, option);
            // 没有总记录数
            gtx.getData(gtx.getPage(), jqEle);
            //绑定事件
            gtx.bindEvent(jqEle);
            return defer.promise();
        }
        //jQuery extends function
        $.fn.sideToolBar = function () {
            var _self = this;
            var baseTool = _self.attr('data-tools');
            var plugTool = $('#sideToolPlug').attr('data-tool-plug') || null;
            //
            if (plugTool !== null) {
                baseTool = plugTool + ',' + baseTool;
            }
            var baseToolArray = (baseTool + ',toTop').split(',');
            console.log('[FSB]tool string: ' + baseToolArray);
            //渲染
            var eleBox = $('<ul></ul>');
            for (var index in baseToolArray) {
                var tbar = baseToolArray[index];
                console.log('[FSB]bar: ' + tbar);
                //
                var tobj = toolbar[tbar];
                if (!tobj) {
                    continue;
                }
                var tmp = $('<a href="javascript:;" title="' + tobj.title + '"><i class="' + tobj.ico + '"/></a>'); var tmpParent = $('<li></li>');
                tmp.on('click', tobj.action);
                if (tbar === 'toTop') {
                    tmpParent.attr('id', 'topTopBar').hide();
                }
                eleBox.append(tmpParent.append(tmp));
            }
            _self.append(eleBox);
            return this;
        };
        //右侧边栏的工具栏
        $(window).on('scroll', function (e) {
            if ($(this).scrollTop() > 200) {
                 //版块新消息提示
            	 if(!$('#unknow_topic_tip').hasClass('fix_style_tip')){
            	 	$('#unknow_topic_tip').addClass('fix_style_tip').css('width', '1110px');
            	 }
                 //右侧边栏的工具栏
                 $('#topTopBar').fadeIn(500);
            } else {
                 //版块新消息提示
                 $('#unknow_topic_tip').removeClass('fix_style_tip');
                 //右侧边栏的工具栏
                 $('#topTopBar').fadeOut(500);
            }
        });
        return { init: init };
    })();
    return jForum;
});
