(function (Q, R) {
    var Logger = R.Logger, RS = R.Supports, RC = R.Common.CmdPrefix, UIACTION = 'ui:action', COREACTION = 'core:action'
    var EventManager, EVENTS = {
        CORE: RC.Operate + "core",
        OPS: RC.Operate + "ops",
        ANNOT: RC.Operate + "annot",
        LISTER: [RC.Book + "opened", RC.Page + 'index', RC.Book + "zoom", RC.Core + "layout", UIACTION, COREACTION]
    }, STATUS = {
        HIDE: 'hide',
        SHOW: 'show',
        DISABLED: 'disabled',
        UNDISABLED: 'undisabled'
    }

    function Events(reader) {
        this.core = reader;
    }

    Q.extend(Events.prototype, {
        coreFire: function (setting) {
            Q(this.core).trigger(EVENTS.CORE, setting);
        },
        coreAction: function (type, action) {
            switch (type) {
                case 'edit':
                    this.FireUI('seal', action)
                    this.FireUI('edit:tool', action)
                    this.FireUI('edit:save', action);
                    break;
                case 'html':
                    this.FireUI('page', action);
                    this.FireUI('seal', action);
                    this.FireUI('edit:save', action);
                    this.FireUI('edit:tool', action);
                    this.FireUI('extend', action)
                    //this.FireUI('title', action)
                    this.FireUI('zoom', action)
                    this.FireUI('rotate', action)
                    this.FireUI('search', action)
                    this.FireUI('view', action)
                    this.FireUI('layout', action)
                    this.FireUI('help', action)
                    break;
                case 'core:layout':
                    if (action) {
                        var n = action[0], o = action[1];
                        if (n == '--') {
                            this.coreAction('edit', [STATUS.DISABLED])
                            this.FireUI('search', [STATUS.DISABLED])
                            this.FireUI('zoom', [STATUS.DISABLED])
                            this.FireUI('rotate', [STATUS.DISABLED])
                        } else {
                            if (R.Config.painter && n != '-') {
                                this.coreAction('edit', [STATUS.UNDISABLED])
                            }
                            this.FireUI('search', [STATUS.UNDISABLED])
                            this.FireUI('zoom', [STATUS.UNDISABLED])
                            this.FireUI('rotate', [STATUS.UNDISABLED])
                        }
                    }
                    break;
            }
        },
        fire: function (type, setting) {
            Q(this.core).trigger(type, setting)
        },
        FireUI: function (id, args, action, callback, type) {
            var evt = document.createEvent("Events");
            evt.initEvent(type || 'ui:action', true, true);
            evt.id = id, evt.action = action, evt.args = args, evt.callback = callback;
            Logger.log("发送事件：" + id);
            window.dispatchEvent(evt);
        },
        /*跳转*/
        jump: function (index) {
            this.coreFire(['jump', index]);
        },
        /*缩放*/
        zoom: function (value) {
            this.coreFire(['zoom', value]);
            return this.core.zoom();
        },
        /*页面布局*/
        layout: function (value) {
            this.coreFire(['layout', value]);
        },
        /*预览模式*/
        view: function (value) {
            this.coreFire(['view', value]);
        },
        rotate: function (value, dom) {
            this.coreFire(['rotate', value, dom]);
        },
        /*下载*/
        download: function (args) {
            if (this.core.callBefore('download') === true) {
                this.coreFire(['download', null, args]);
                //this.core.callAfter('download');
            }
        },
        custom: function (args, action) {
            this.core.callAfter({file: this.core.file, extra: this.core.extra, args: args});
        },
        more: function (args, value) {
            this.coreFire([value]);
        },
        /*全屏*/
        fullscreen: function () {
            if ($.isFunction($.fn.toggleFullScreen) && $(document).fullScreen() != null) {
                $('body').toggleFullScreen();
            }
        },
        /*打印*/
        print: function (args, id, cb) {
            this.coreFire(['print', args, cb]);
        },
        /*拓展相关*/
        extend: function (args, id, cb) {
            var target = Q('.catalog-content').find('.catalog-tree.' + id[0]);
            if (target && target.children().length <= 0 || id[1]) {
                this.fire(EVENTS.OPS, [id[0], id[1] || 'display', target, cb, args])
            }
            if ((id[0] == 'show' || id[0] == 'hide') && this.core.zoom() == "<>") {
                var _t = this;
                setTimeout(function () {
                    _t.zoom('<>')
                });
            }
        },
        /*右键操作*/
        right: function (args) {
            console.log("right:" + args)
        },
        /*搜索*/
        search: function (args, id, cb) {
            var event = {
                select: 0,
                done: function () {
                    cb && cb.call(this, Q.makeArray(arguments));
                }
            };
            this.fire(EVENTS.OPS, ['search', id && id[0], args, event]);
        },
        /*切换编辑类型*/
        brush: function (args, id) {
            var _t = this;
            if (typeof id == "string") {
                id = id.split(":");
            }
            if (id && id[0] == 'setStyle') {
                _t.fire(EVENTS.ANNOT, ['setStyle', args]);
            } else {
                if (id.length) {
                    this.fire(EVENTS.ANNOT, ['brush', id[0], id[1], id[2]]);
                }
                if (Q.isPlainObject(args)) {
                    args['type'] && _t.fire(EVENTS.ANNOT, ['brush', args['type']]);
                    Q.each(args, function (_, v) {
                        _t.fire(EVENTS.ANNOT, ['style', v]);
                    })
                } else {
                    console.log("数据不规范：" + args);
                }
            }
            console.log("brush:" + id)
        },
        /*编辑操作 撤销等*/
        edit: function (args, id) {
            this.fire(EVENTS.ANNOT, ['edit', id, args]);
        },
        oes: function (args, id, cb) {
            var t = this;
            var event = {
                done: function (data) {
                    console.log(data)
                    cb && cb.call(this, data);
                }
            };
            this.fire(EVENTS.OPS, ['oes', id && id[0], args || {}, event]);
        },
        attribute: function (_, id, cb) {
            var event = {
                done: function (data) {
                    console.log(data)
                    cb && cb.call(this, data);
                }
            };
            this.fire(EVENTS.OPS, ['attribute', id && id[0], event]);
        },
        sign: function (args, id, cb) {
            var event = {
                done: function (data) {
                    cb && cb.call(this, data);
                }
            };
            this.fire(EVENTS.OPS, ['sign', id && id[0], args, event]);
        }
    });

    function addEventListener(element, type, func) {
        //判断浏览器是否支持这个方法
        if (element.addEventListener) {
            element.addEventListener(type, func, false);
        } else if (element['attachEvent']) {
            element['attachEvent']("on" + type, func);
        } else {
            element["on" + type] = func;
        }
    }

    function doCallBack(fun, value) {
        fun(value)
    }

    /*监听ui发来的事件*/
    addEventListener(window, 'reader:action', function () {
        var event = arguments[0], id = event['id'] && event['id'].split(":"), action = event['action'],
            args = event['args'],
            cb = event['callback'], fx = id && EventManager[id[0]];
        if (fx) {
            switch (action) {
                case 'goto':
                    break;
                case 'get':
                    //do something
                    break;
                //others
                default:
                    fx.call(EventManager, args, id.slice(1), cb);
                    //cb && Q.isFunction(cb) && c && doCallBack(cb, c);
                    break;
            }
        } else {
            cb && Q.isFunction(cb) && doCallBack(cb, false);
            Logger.log('events has not lister : ' + action);
        }
    });
    Q(window.document).on(RC.Core + 'init', function (event, core) {
        EventManager = new Events(core);
        EventManager.FireUI(RC.Core + 'init', core);
        //EventManager.brush.call(EventManager, "", "revision:AddRevisions");
        Q.each(EVENTS.LISTER, function (_, event) {
            Q(core).on(event, function () {
                var args = Q.makeArray(arguments);
                if (event == UIACTION) {
                    var arg = args.slice(1)[0];
                    EventManager.FireUI(arg[0], arg.slice(1));
                } else if (event == COREACTION) {
                    var arg = args.slice(1)[0];
                    EventManager.coreAction(arg[0], arg.slice(1));
                } else {
                    EventManager.coreAction(event, args.slice(1));
                    EventManager.FireUI(event, args.slice(1));
                }
            })
        })
        window.addEventListener && window.addEventListener('message', function (e) {
            var data = e.data;
            if (data) {
                var keys = data[0], value = data[1], value1 = data[2];
                var fx = EventManager[keys];
                fx && fx.call(EventManager, value, value1);
            }
        }, true);
    })
})(jQuery, window.SWR || window.SWR);
