import { guid, isInApp } from '@/uilts/help'
//  iframe 通信中心
class IframeMessageCenter {
    constructor() {
        //  缓存事件队列
        this.messageCallbackMap = new Map();
        this.messageFailbackMap = new Map();
        this.timer = null
        this.init()
    }

    send({ info = {}, data = {}, callback, overTime, failback }) {
        if (callback) {
            info.messageId = `${info.actionType}-${guid()}` // 唯一的ID，用于标记回调函数
        }
        if (isInApp) {
            window.ReactNativeWebView.postMessage(JSON.stringify({
                info,
                data
            }))
        } else {
            window.parent.postMessage({
                info,
                data: JSON.parse(JSON.stringify(data))
            }, '*');
        }
        if (callback) {
            // 带回调callback 的message， 要求携带messageId，callback，failback等
            this.listen(info.messageId, callback)
            if (failback) {
                this.addFailback(info.messageId, overTime, failback)
            }
        }
    }

    listen(key, callback) {
        // 序列添加失败回调
        this.messageCallbackMap.set(key, { callback })
    }

    addFailback(key, overTime = 2000, failback) {
        // 序列添加失败回调
        this.messageFailbackMap.set(key, {
            time: new Date().getTime(),
            overTime,
            failback
        })
        this.checkTimer()
    }

    init() {
        window.addEventListener('message', (e) => {
            let { info = {}, data = {} } = e.data;
            let key, item

            // 如果有messageId && 是自己发送的
            if (info.messageId) {
                key = info.messageId
                item = this.messageCallbackMap.get(key)
            }

            if (info.actionType && !item) {
                key = info.actionType
                item = this.messageCallbackMap.get(key)
            }

            // 执行成功回调
            if (item) {
                // 序列删除 失败回调      
                this.messageFailbackMap.delete(key)
                const callback = item.callback
                callback(data)
                // 序列删除 成功回调
                this.messageCallbackMap.delete(key)
            }
        })

        this.checkTimer()
    }
    checkTimer() {
        if (this.timer) {
            return
        }
        let key, value, now_time
        this.timer = setInterval(() => {
            if (this.messageFailbackMap.size == 0) {
                clearInterval(this.timer)
                this.timer = null
            }

            // 轮询查看有无超期的message信息
            now_time = new Date().getTime();
            for (let item of this.messageFailbackMap.entries()) {
                key = item[0] || ''
                value = item[1] || {}

                if (now_time - value.time > value.overTime) {
                    const callback = value.failback
                    callback && callback({
                        error: 1,
                        msg: "message 超时错误"
                    })
                    this.messageFailbackMap.delete(key)
                }
            }
        }, 1000)
    }
}

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

export default iframeMessageCenter;