//  iframe 通信中心
class MessageCenter { 
    constructor() { 
        //  缓存事件队列
        this.messageCallbackMap = new Map();
        this.messageFailbackMap = new Map();
        this.init()
    }

    send({ actionType, data, callback, overTime, failback }) {
        window.parent.postMessage({
            actionType,
            data
        }, '*');
        if (data.messageID && callback) {
            // 带回调callback 的message， 要求携带messageID，callback，failback等
            this.listen(`${actionType}-${data.messageID}`, callback)
            if (failback) { 
                this.addFailback(`${actionType}-${data.messageID}`, overTime, failback)
            }
        }
    }

    listen(actionType, callback) {
        let activeQuene = this.messageCallbackMap.get(actionType);
        if (activeQuene?.length > 0) {
            activeQuene.push(callback)
        } else { 
            this.messageCallbackMap.set(actionType, [callback])
        }
    }

    addFailback(actionType, overTime=2000, failback) { 
        let failbackQuene = this.messageFailbackMap.get(actionType);
        if (failbackQuene && failbackQuene.failCallbackList) {
            failbackQuene.failCallbackList.push(
                failback
                )
            } else { 
                this.messageFailbackMap.set(actionType, {
                    time: new Date().getTime(),
                    overTime,
                    failCallbackList: [failback]
                })
            }
    }

    init() {
        window.addEventListener('message', (e) => { 
            const { actionType, data } = e.data;
            this.messageFailbackMap.delete(actionType);
            const quene = this.messageCallbackMap.get(actionType) ||  [];
            let index = 0;
            while (index < quene.length) { 
                const callback = quene[index];
                callback(data)
                index++
            }
        })
        setInterval(() => { 
            // 轮询查看有无超期的message信息
            const now = new Date().getTime();
            for (let item of this.messageFailbackMap.values()) { 
                if (now - item.time > item.overTime) { 
                    let index = 0;
                    while (index < item.failCallbackList.length) { 
                        const callback = item.failCallbackList[index];
                        callback({
                            error: 0,
                            msg: "message 超时错误"
                        })
                        index++
                    }
                }
            }

        }, 1000)
    }
}

// messageCenter在每个iframe内实例化一次
const messageCenter = new MessageCenter();

export default messageCenter;