let events = {};
let id = 1;

let bindMap = {
    "appStarted":'start',
    "viewChanged":"route"
}

let triggedMap = {};
/**
 * 绑定自定义事件
 * @param event 自定义事件
 * @param options.triggerAll 是否触发历史绑定的事件处理函数
 * @param handler 自定义事件的处理函数
 */
exports.bind = function (event, ...params) {
    // appStarted，viewChanged
    if(bindMap[event]) event = bindMap[event];
    //194801 事件绑定支持传入参数控制是否触发历史绑定的事件处理函数
    let handler, options;
    if(!params || params.length==0) {
        console.warn('未传入事件处理函数！');
        return;
    }
    
    if(params.length > 1) options = params[0];
    handler = params[params.length-1];
    handler.id = id;
    
    events[event] = events[event] || [];
    events[event].push(handler);
    if(triggedMap[event]){
        if(!options || options.triggerAll===true) {
            handler.apply({
                event: event
            }, triggedMap[event]);
        }  
    }
    return id++;
};

/**
 * 主动触发应用级事件
 */
exports.trigger = function (event,...params) {
    triggedMap[event] = params;
    let triggerPass = "true";
    if (events[event] && events[event].length > 0) {
        events[event].forEach(function (handler) {
            //事件的处理必须是异步的
            let doHandler = function () {
                handler.apply({
                    event: event
                }, params);
            };
            //154941 light框架支持Light.on("viewback") 
            if(params[0]&&params[0].sync){
                let triggerResult = handler.apply({
                    event: event
                }, params);
                if(!triggerResult){
                    triggerPass = "false";
                }
            }else{
                setTimeout(doHandler,0);
            }
            
        });
    }
    return triggerPass;
};

/**
 * 解绑事件
 */
exports.unbind = function (event,id) {
    if(id&&events[event]){
        events[event] = events[event].filter(function (handler) {
            return handler.id !== id
        })
    }else{
        events[event] = [];
    }
};