define('jForumThreads', [
    'require',
    'jquery',
    'jForumXhr',
    'jForumUtils',
    'jForumTemplate',
    'jForumXhrDefer',
    'store',
    'purl',
    'ckeditor'
], function (require, $, xhr, util, template, xhrDefer, store, purl, ckeditor) {
    'use strict';

    var jForumThreads = (function () {
        //CK4的函数
        function insertEditorHtml(htmlString) {
            if (!!CKEDITOR.instances) {
                $('[data-richEditor="CKEditor"]').focus();
            }
            if (CKEDITOR.instances.content === undefined) { // iframe embed smiley
                $('[data-richEditor="CKEditor"]', window.parent.document).focus();
                window.parent.CKEDITOR.instances.content.insertHtml(htmlString);
                return;
            }
            CKEDITOR.instances.content.insertHtml(htmlString);
        };
        //v:4.x.x
        function initCkEditor(config) {
            var options = $.extend({
                textarea: 'content',
                plugs: 'uploadimage',
                startupFocus: false,
                width: 600,
                height: 150
            },
                config);
            CKEDITOR.config.pasteFilter = null;
            CKEDITOR.config.height = options.height;
            CKEDITOR.config.width = options.width;

            var insConfig = { extraPlugins: options.plugs };
            if (options.startupFocus) {
                insConfig.startupFocus = true;
            }
            CKEDITOR.replace(options.textarea, insConfig);
            if (options.plugs.indexOf('uploadimage') != -1) {
                CKEDITOR.config.filebrowserUploadUrl = IMGSTORE + options.upload + '?type=Files';
                CKEDITOR.config.filebrowserImageUploadUrl = IMGSTORE + options.upload + '?type=Images';
                //ADD 20191026
                CKEDITOR.on('dialogDefinition', function (evt) {
                    var dialogName = evt.data.name;
                    if (dialogName == 'image') {
                        var uploadTab = evt.data.definition.getContents('Upload'); // get tab of the dialog
                        var browse = uploadTab.get('upload'); //get browse server button

                        browse.onClick = function () {
                            var input = this.getInputElement();
                            input.$.accept = 'image/*';
                        };

                        browse.onChange = function () {
                            var input = this.getInputElement();
                            var fn = input.$.value; // 文件路径
                            var imageReg = /\.(gif|jpg|jpeg|png)$/i;
                            if (!imageReg.test(fn)) {
                                alert('非法的文件类型');
                                input.$.value = '';
                            }
                        };
                    }
                });
            }
        };
        //select2 回调
        function select2CallBack(jsonData, currentVal, jqEle, isClearOldOption) {
            var optionData = ''; var coo = isClearOldOption || false;
            $.each(jsonData, function (index, item) {
                optionData += '<option value="%V%">%T%</option>'.replace('%V%', item.id).replace('%T%', item.title);
            });
            if (optionData.length > 0) {
                if (coo) {
                    //清空旧值
                    jqEle.find('option').remove();
                }
                jqEle.append(optionData).find('option[value=' + currentVal + ']').attr("selected", true);
                jqEle.select2({ theme: 'bootstrap4' });
            }
        }
        function init() {
            // 编辑器(initEvent. 设置高和宽, click. 开始实例编辑器)
            $('body').on('initEvent', '[data-richEditor="CKEditor"]', function (e) {
                var self = $(e.target);
                var cusConfig = util.parseQueryJson(self.attr('data-query'));
                self.css({ 'width': cusConfig.width, 'height': cusConfig.height, 'background-color': '#f1f1f1', 'resize': 'none', 'border': 'none' }).attr('placeholder', '\n      内容在此输入');
            });
            $('body').on('focus', '[data-richEditor="CKEditor"]', function (e) {
                var cusConfig = util.parseQueryJson($(e.target).attr('data-query'));
                cusConfig.startupFocus = true;
                initCkEditor($.extend({}, cusConfig));
            });
            $('[data-richEditor="CKEditor"]').trigger('initEvent');
            //初始化ckeditor
            $('.richeditor').bind('initEditorEvent', function (e) {
                var cusConfig = util.parseQueryJson($(e.target).attr('data-query'));
                cusConfig.startupFocus = false;
                initCkEditor($.extend({}, cusConfig));
            }).trigger('initEditorEvent');
            //加载版块组[NW]
            $('.asyn-loadate-select').on('initDataEvent', function (e) {
                var _ls = $(e.target); var currentOption = _ls.attr('data-current') || '-1';
                xhr.jsonGet(_ls.attr('data-handler')).done(function (data) {
                    select2CallBack(data, currentOption, _ls);
                });
            }).trigger('initDataEvent');
            //创建话题:初始化版块[NW]
            $('#asyn-board-select').on('initDataEvent', function (e) {
                var _bs = $(e.target);
                if (_bs.attr('data-current') === '0') {
                    return; //没有选择版块,不初始化
                }
                var parentSelect = $('#asyn-volumes-select').attr('data-current');
                if (util.isBlank(parentSelect)) {
                    return; //没有选择版块组(卷),不初始化
                }
                var currentOption = _bs.attr('data-current');
                xhr.jsonGet(_bs.attr('data-handler'), { data: { 'volumes': parentSelect } }).done(function (data) {
                    select2CallBack(data, currentOption, _bs);
                });
            }).trigger('initDataEvent');
            /*版块组与版块联动[NW]*/
            $('#asyn-volumes-select').on('select2:select', function (e) {
                var selectBoard = e.params.data.id;
                var selectChild = $('#asyn-board-select'); var currentOption = selectChild.attr('data-current');
                xhr.jsonGet(selectChild.attr('data-handler'), { data: { 'volumes': selectBoard } }).done(function (data) {
                    select2CallBack(data, currentOption, selectChild, true);
                });
            });
            //话题内容页中会员信息弹出菜单
            $('body').on('click', 'a.poper-member-menu', function (e) {
                e.preventDefault();
                var self = $(this);
                var rawdata = {};
                rawdata.uri = self.parents('.topic_posts_item_left').attr('data-handler');
                //本地缓存命中
                rawdata.member = purl(rawdata.uri).param('id');
                var cacheData = store.get('member_profile#' + rawdata.member);
                //本人的不缓存[20200118]
                if (!jQuery.isEmptyObject(cacheData)) {
                    template.buildMemberProfileMenu(cacheData, self);
                    return;
                }
                //
                console.log('[MP]不存在缓存去拉取数据');
                xhr.jsonGet(rawdata.uri, {
                    jsonCallback: function (data) {
                        store.set('member_profile#' + rawdata.member, data);
                        template.buildMemberProfileMenu(data, self);
                    }
                });
            });
            //引用回复@20200506
            $('body').on('click', '.post-action-quote', function () {
                var self = $(this);
                var options = util.parseQueryJson(self.attr('data-query'));
                xhr.jsonGet(self.attr('data-handler'), {
                    data: { 'id': options.id },
                    jsonCallback: function (json) {
                        if (jQuery.isEmptyObject(json)) {
                            return util.errorMessage('读取原文内容失败');
                        }
                        if (json.level === 'err') {
                            return util.errorMessage(json.message);
                        }
                        if (json.infoTip) {
                            insertEditorHtml('');
                            $('#reply-tip-message').html('<strong>提示!</strong>&nbsp;' + json.infoTip);
                            //插入到表单中@20200506
                            $('#quick_reply_form').find('input[name=quote]').val(json.quote);
                            $('#quick_reply_form').find('input[name=scale]').val(json.scale);
                        }
                    },
                    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('当前操作因错误而异外中止');
                    }
                });
                return false;
            });
            //举报回复[NW]
            $('body').on('click', '.post-action-report', function () {
                var self = $(this);
                var requestParam = util.parseQueryJson(self.attr('data-query'));
                //
                $.confirm({
                    title: '',
                    closeIcon: true,
                    closeIconClass: 'ico-sm mdi mdi-close',
                    content: '<form action="">' +
                        '<div class="form-group">' +
                        '<label>类型</label>' +
                        '<select name="type" size="1" class="form-control">' +
                        '<option value="">请选择类型</option>' +
                        '<option value="1">广告</option>' +
                        '<option value="2">色情</option>' +
                        '<option value="3">政治</option>' +
                        '<option value="4">暴力</option>' +
                        '<option value="5">语言暴力</option>' +
                        '<option value="6">其它</option>' +
                        '</select></div><div class="form-group"><textarea class="form-control" name="reason" required="required" rows="3" placeholder="输入举报的理由"></textarea></div></form>',
                    buttons: {
                        formSubmit: {
                            text: '举报',
                            btnClass: 'btn-blue',
                            action: function () {
                                var reason = this.$content.find('textarea[name=reason]').val();
                                if (util.isBlank(reason)) {
                                    this.$content.find('textarea[name=reason]').focus();
                                    return false;
                                }
                                requestParam.reason = reason;
                                requestParam.type = this.$content.find("select[name=type]").val();
                                xhr.jsonPost(self.attr('data-handler'), {
                                    data: requestParam,
                                    jsonCallback: function (response) {
                                        response.refresh = false;
                                        util.tipDialog(response);
                                    },
                                    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;
            });
            //快速回复[NW]@20200506
            $('#quick_reply_posts').on('submit', '#quick_reply_form', function (e) {
                e.preventDefault();
                var self = $(this);
                //
                var requestData = {}
                requestData.token = self.find('input[name=token]').val();
                requestData.quote = self.find('input[name=quote]').val();
                requestData.scale = self.find('input[name=scale]').val();
                try {
                    requestData.content = CKEDITOR.instances.content.getData();
                } catch (e) {
                    requestData.content = $(this).find('input[name=content]').val();
                }
                if (util.isBlank(requestData.content)) {
                    $.alert('请输入回复的内容');
                    return false;
                }
                // 同步操作
                xhr.jsonPost(self.attr('action'), {
                    data: requestData,
                    jsonCallback: function (response) {
                        if (response.level === 'err' && !util.isBlank(response.message)) {
                            //出错了
                            response.refresh = false;
                            util.tipDialog(response);
                        } else {
                            template.quickReplyFillPosts(response);
                            //清空表单的元素
                            self.find('input[name=content]').val('');
                            self.find('input[name=quote]').val('');
                            self.find('input[name=scale]').val('');
                            $('#reply-tip-message').html('');
                            //清空编辑器的内容
                            CKEDITOR.instances['content'].setData('');
                        }
                    },
                    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('当前操作因错误而异外中止');
                    }
                });
                return false;
            });
            //文章内容中的标签
            $('body').on('mouseenter', '.tag-item-anchor', function () {
                $('<span class="tag-item-remove"><i class="mdi mdi-close"></i></span>').appendTo($(this));
            });
            $('body').on('mouseleave', '.tag-item-anchor', function () {
                $(this).find('.tag-item-remove').remove();
            });
            $('#tag-action-add').click(function () {
                var requestURI = $(this).attr('data-handler');
                $.confirm({
                    title: '新标签',
                    closeIcon: true,
                    closeIconClass: 'ico-sm mdi mdi-close',
                    content: '<form action=""><div class="form-group"><input class="form-control" name="names" required="required" placeholder="输入标签名称" /></div></form>',
                    buttons: {
                        formSubmit: {
                            text: '提交',
                            btnClass: 'btn-blue',
                            action: function () {
                                var names = this.$content.find('input[name=names]').val();
                                if (util.isBlank(names)) {
                                    this.$content.find('input[name=names]').focus();
                                    return false;
                                }
                                var requestParam = {};
                                requestParam.names = names;

                                xhr.jsonPost(requestURI, {
                                    data: requestParam,
                                    jsonCallback: function (response) {
                                        response.names = requestParam.names;
                                        xhrDefer.newTagHandler(response);
                                    },
                                    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;
            });
            //回复点赞
            $('body').on('click', '.mood-section a.mood-action', function (e) {
                var _j = $(this); var parent = _j.parents('.mood-section');
                var rawdata = {};
                rawdata.uri = '/posts/mood/like';
                rawdata.data = { id: parent.attr('data-mood') };
                rawdata.data.mood = _j.attr('data-action');
                rawdata.callFun = 'updateMoodCounter';
                //
                xhr.action(rawdata.uri, rawdata.callFun, rawdata.data, false, _j);
            });
            //话题内容页中顶部的固定
            $(document).scroll(function() {
                var scroH = $(document).scrollTop();  //滚动高度
                if(scroH < 300){
                    $('#scroll-top-section').hide();
                }
                if(scroH > 300){
                    $('#scroll-top-section').show();
                }
            });
        }
        return { init: init };
    })();
    return jForumThreads;
});