(() => {
    if (!/android/.test(navigator.userAgent.toLowerCase())) {
        console.error("当前环境不支持WebView桥接通信, 请检查是否为安卓环境");
        return
    }
    let bridge;
    function setupWebViewJavascriptBridge(callback) {
        return new Promise((reslove, reject) => {
            if (window.WebViewJavascriptBridge) {
                bridge = window.WebViewJavascriptBridge;
                callback && callback()
                reslove()
            } else {
                document.addEventListener(
                    "WebViewJavascriptBridgeReady",
                    function () {
                        bridge = window.WebViewJavascriptBridge;
                        callback && callback()
                        reslove()
                    },
                    false
                );
            }
        })
    }
    let funcs = {}
    setupWebViewJavascriptBridge(() => {
        bridge.init()
        bridge.registerHandler("ampeHHCommunication", (data) => {
            console.log('[zyh][registerHandler]',data);
            data = JSON.parse(data || '{}');
            let eventName = data.eventName || '{}';
            let eventData = JSON.parse(data.eventData || '{}');
            if (funcs[eventName]) {
                for (let callback of funcs[eventName]) {
                    callback({type: eventName, data: eventData})
                }
            }
        });
    })
    window.hh = {
        async call(funcName, params, callback) {
            if (!bridge) {
                await setupWebViewJavascriptBridge()
            }
            bridge.callHandler(funcName, params, callback);
        },
        async on(funcName, callback) {
            if (funcs[funcName]) {
                funcs[funcName].add(callback)
            } else {
                funcs[funcName] = new Set([callback])
            }
        },
        off(funcName, callback) {
            if (!funcs[funcName]) {
                return false
            }
            if (!callback) {
                return delete funcs[funcName]
            }
            let res = funcs[funcName].delete(callback)
            if(funcs[funcName].size <= 0) {
                delete funcs[funcName]
            }
            return res
        }
    };
})();
