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

    var UE = window.baidu.editor,
        UI = window.baidu.editor.ui,
        popup = window.baidu.editor.ui.Popup,
        combox = window.baidu.editor.ui.Combox,
        utils = window.baidu.editor.utils,
        domUtils = window.baidu.editor.dom.domUtils,
        stateful = window.baidu.editor.ui.Stateful,
        uiUtils = window.baidu.editor.ui.uiUtils,
        uiBase = window.baidu.editor.ui.UIBase;

    var wxeditor = {
        init: function (me) {
            this.setModes(me);//新增工具栏点击按钮
            me.addListener("click", function (t, evt) {

            });
        },
        setModes: function (me) {
            var mdls = this.getModules(me);
            $.each(mdls, function (key, item) {
                UI[key] = function (r) {
                    var btn = new UI.Button(utils.extend({
                        className: "edui-for-" + key,
                        theme: r.options.theme,
                        editor: r,
                        onclick: function () {
                            this.editor.fireEvent(item.event);
                        }
                    }, item));
                    UI.buttons[key] = btn;
                    r.addListener('selectionchange', function (type, causeByUi, uiReady) {
                        if (!uiReady) {
                            var state = r.queryCommandState(key);
                            if (state == -1) {
                                btn.setDisabled(true);
                            } else {
                                btn.setDisabled(false);
                            }
                        }
                    });
                    return btn;
                };
                me.addListener(item.event, item.callback);
            });
        },
        getModules: function (me) {
            var that = this;
            var mdls = {
                "insert-image": {
                    title: "插入图片",
                    event: "extendImageSelect",
                    callback: function (e, evt) {
                        evt = evt || window.event;
                        var el = evt.target || evt.srcElement;
                        var me = this;
                        var simpleupload = $('#' + me.key).data('simpleupload');
                        if (simpleupload && $.isFunction(simpleupload)) {
                            simpleupload.call(me);
                            return
                        }
                        var format = evt ? evt.format || null : null;
                        var callback = $(el).data('callback');
                        if (!callback && $(el).is('div')) {
                            layui.uploadRender({
                                elem: el,
                                url: '/upload/index?type=images',
                            });
                            $(el).data('callback', function (res) {
                                if (!res.code) return;
                                var list = res.data, url = res.url;
                                //替换图片
                                if (format) {
                                    format = format.replace(/([\s|_])src=\"([^\"]*)\"/ig, '$1src="' + url + '"');
                                    me.execCommand('inserthtml', format);
                                    return;
                                }
                                //新加图片
                                list = list ? list : [];
                                for (var i = 0, url = ''; url = list[i++];) {
                                    me.execCommand('inserthtml', '<p><img src="' + url + '" ></p>');
                                }
                            }).trigger('click');
                        }
                    },
                },
            };
            return mdls;
        }
    };


    UE.plugins["wxeditor-extend"] = function () {
        wxeditor.init(this);
    };


    $.getEditor = function (id, config) {
        var initConfig = {
            toolbars: [
                [
                    "forecolor", "backcolor","formatmatch", "|","insert-image","unlink","|","paragraph","fontfamily", "fontsize", "fullscreen",
                ],
            ],
            zIndex: 1,
            charset: "utf-8",
            fontfamily: [
                { label: "宋体", name: "songti", val: "宋体,SimSun" },
                { label: "新宋体", name: "xinsongti", val: '新宋体,NSimSun' },
                { label: "仿宋", name: "fangsong", val: '仿宋,仿宋_GB2312, SimFang' },
                { label: "楷体", name: "kaiti", val: '楷体,楷体_GB2312, SimKai' },
                { label: "微软雅黑", name: "yahei", val: '微软雅黑,Microsoft YaHei' },
                { label: "黑体", name: "heiti", val: "黑体, SimHei" },
                { label: "隶书", name: "lishu", val: "隶书, SimLi" },
                { label: "萝莉体", name: "luoliti", val: "萝莉体 第二版,Heiti SC" },
                { label: "andaleMono", name: "andaleMono", val: "andale mono" },
                { label: "arial", name: "arial", val: "arial, helvetica,sans-serif" },
                { label: "arialBlack", name: "arialBlack", val: "arial black,avant garde" },
                { label: "comicSansMs", name: "comicSansMs", val: "comic sans ms" },
                { label: "impact", name: "impact", val: "impact,chicago" },
                { label: "timesNewRoman", name: "timesNewRoman", val: "times new roman" }
            ],
            shortcutMenu: ["fontfamily", "fontsize", "bold", "italic", "underline", "fontborder", "strikethrough", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist", "superscript", "subscript", "justifyleft", "justifycenter", "justifyright", "justifyjustify", "rowspacingtop", "rowspacingbottom", "lineheight"],
            fontsize: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 36, 48, 60, 72],
            enableAutoSave: false,//禁止自动保存
            autoClearinitialContent: false,
            autoFloatEnabled: false, // 是否保持 toolbar 滚动时不动
            autoHeightEnabled: false,//是否自动长高
            focus: false,
            wordCount: true,
            elementPathEnabled: false,
            initialFrameWidth: '100%', // 初始化编辑器宽度
            initialFrameHeight: 200,//初始化编辑器高度
            maximumWords: 1000000,//最大字数
            imageScaleEnabled: false,//图片调整大小
            disabledTableInTable: false,//禁止表格嵌套
            imagePopup: true,//图片悬浮操作显示
            pasteplain: false, // 是否默认为纯文本粘贴。false为不使用纯文本粘贴，true为使用纯文本粘贴
            allowDivTransToP: false,//禁止讲div 转换成p标签
            codeMirrorJsUrl: false,
            codeMirrorCssUrl: false,
        };
        var conf = $('#' + id).data('config') || {};
        $.isPlainObject(conf) || (conf = eval("(" + conf + ")"));
        var wxEditor = new UE.ui.Editor($.extend({}, initConfig, conf || {}, config || {}));
        wxEditor.render(id);
        $('#' + id).data('wxEditor', wxEditor);
        return wxEditor;
    }

})(window.jQuery);