/*
 * @Purpose: vue项目中的全局调用事件
 * @FilePath: eventBus.ts
 * @Author: sujunling
 * @Date: 2022-11-15 16:18:08
 * @Original: original
 * @Descripttion:
 */

class EventBus {

    constructor() {
        this.list = {};
        this.casualData = {};
    }

    emit(name, ...args) {
        let eventName = this.list[name];
        try {
            if (eventName) {
                if (typeof eventName == 'object') {
                    eventName.map((fn) => fn.apply(this, args));
                } else {
                    eventName.apply(this, args)
                }
            } else {
                this.casualData[name] = args;
                console.log('没有找到这个事件:', name)
            }
        } catch (error) {
            console.log(error);
        }
    }

    on(name, callback) {
        let fn = this.list[name] || [];
        fn.push(callback);
        this.list[name] = fn;
        if (this.casualData[name]) {
            this.emit(name, this.casualData[name])
            delete this.casualData[name];
        }
    }

    one(name, callback) {
        this.list[name] = callback;
        if (this.casualData[name]) {
            this.emit(name, this.casualData[name])
            delete this.casualData[name];
        }
    }

    off(name, callback) {
        let fn = this.list[name];
        if (fn) {
            let index = fn.indexOf(callback);
            if (index > -1) {
                fn.splice(index, 1);
            }
        }
    }

    remove(name) {
        delete this.list[name];
    }
}

const getInstance = () => {
    if (!window['eventBus']) {
        window['eventBus'] = new EventBus();
    }
    return window['eventBus'];
};

export default getInstance();