import { __assign, __awaiter, __generator, __read, __spreadArray } from "tslib";
/* eslint-disable @typescript-eslint/no-empty-function */
/**
 * 生命周期处理函数
 */
import * as React from 'react';
import { throttle } from 'lodash-es';
import * as querystring from 'query-string';
import { runtime } from './adapter';
var noops = function () { };
var APPLIFECYCLE = {
    onAppShow: noops,
    onAppHide: noops,
    onAppError: noops,
    onAppUnhandledRejection: noops,
    onAppLaunch: noops,
    beforeCustomLaunch: noops,
};
// 小程序 端使用lifeCycle
var alreadyInitAppLifeCycle = false;
var _HANDLER_MAP = {};
export function initAppLifeCycle(app, appLifeCycle) {
    var _this = this;
    appLifeCycle = __assign(__assign({}, APPLIFECYCLE), appLifeCycle);
    var onAppLaunch = function (query) { return __awaiter(_this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, (appLifeCycle === null || appLifeCycle === void 0 ? void 0 : appLifeCycle.beforeCustomLaunch(query))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, (appLifeCycle === null || appLifeCycle === void 0 ? void 0 : appLifeCycle.onAppLaunch(query))];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); };
    var onAppShow = function (query) { return __awaiter(_this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, (appLifeCycle === null || appLifeCycle === void 0 ? void 0 : appLifeCycle.onAppShow(app.getLaunchOptionsSync()))];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); };
    // 应用级别事件监听
    if (!alreadyInitAppLifeCycle) {
        onAppLaunch(app.getLaunchOptionsSync());
        onAppShow(app.getLaunchOptionsSync());
        // 预留等客户端来触发
        _HANDLER_MAP = {
            appShow: function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return appLifeCycle.onAppShow.apply(appLifeCycle, __spreadArray([], __read(args), false));
            },
            appHide: function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return appLifeCycle.onAppHide.apply(appLifeCycle, __spreadArray([], __read(args), false));
            },
            error: function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return appLifeCycle.onAppError.apply(appLifeCycle, __spreadArray([], __read(args), false));
            },
            unhandledrejection: function (event) { return appLifeCycle.onAppUnhandledRejection(event === null || event === void 0 ? void 0 : event.reason); },
        };
        for (var event_1 in _HANDLER_MAP) {
            runtime.addEventListener(event_1, _HANDLER_MAP[event_1]);
        }
        alreadyInitAppLifeCycle = true;
    }
}
export function removeAppLifeCycle() {
    for (var event_2 in _HANDLER_MAP) {
        runtime.removeEventListener(event_2, _HANDLER_MAP[event_2]);
    }
    _HANDLER_MAP = {};
    alreadyInitAppLifeCycle = false;
}
var isReachBottom = false;
// web 端使用lifeCycle
export function usePageLifeCycle(_a, context) {
    var _b = _a.beforePageCustomLaunch, beforePageCustomLaunch = _b === void 0 ? function (query) { } : _b, _c = _a.onPageLoad, onPageLoad = _c === void 0 ? function (query) { } : _c, _d = _a.onPageShow, onPageShow = _d === void 0 ? function () { } : _d, _e = _a.onPageReady, onPageReady = _e === void 0 ? function () { } : _e, _f = _a.onPageHide, onPageHide = _f === void 0 ? function () { } : _f, _g = _a.onPageUnload, onPageUnload = _g === void 0 ? function () { } : _g, _h = _a.onPullDownRefresh, onPullDownRefresh = _h === void 0 ? function () { } : _h, _j = _a.onReachBottom, onReachBottom = _j === void 0 ? function () { } : _j, _k = _a.onShareAppMessage, onShareAppMessage = _k === void 0 ? function () { } : _k, _l = _a.onPageScroll, onPageScroll = _l === void 0 ? function () { } : _l, _m = _a.onResize, onResize = _m === void 0 ? function () { } : _m, _o = _a.onAddToFavorites, onAddToFavorites = _o === void 0 ? function () { } : _o, _p = _a.onShareTimeline, onShareTimeline = _p === void 0 ? function () { } : _p, _q = _a.onTabItemTap, onTabItemTap = _q === void 0 ? function () { } : _q;
    runtime['$page'] = context.page;
    var reachBottomDistance = 50;
    try {
        var config = context.app.__internal__.getConfig().pages.find(function (page) { return page.id === context.page.id; });
        reachBottomDistance = config.reachBottomDistance;
        if (typeof reachBottomDistance !== 'number') {
            reachBottomDistance = 50;
        }
    }
    catch (e) { }
    React.useEffect(function () {
        var _a;
        var _onPageLoad = function (query) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, (beforePageCustomLaunch === null || beforePageCustomLaunch === void 0 ? void 0 : beforePageCustomLaunch(query))];
                        case 1:
                            _a.sent();
                            return [2 /*return*/, typeof onPageLoad === 'function' ? onPageLoad(query) : function () { }];
                    }
                });
            });
        };
        try {
            _onPageLoad.call(context.page, getCurrentPageQuery());
            typeof onPageReady === 'function' && onPageReady.call(context.page);
            typeof onPageShow === 'function' && onPageShow.call(context.page);
        }
        catch (e) {
            if (!((_a = context.options) === null || _a === void 0 ? void 0 : _a.looseError)) {
                throw e;
            }
            else {
                console.error('Catched error:', e);
            }
        }
        return function () {
            var _a;
            try {
                typeof onPageHide === 'function' && onPageHide.call(context.page, {});
                typeof onPageUnload === 'function' && onPageUnload.call(context.page, {});
            }
            catch (e) {
                if (!((_a = context.options) === null || _a === void 0 ? void 0 : _a.looseError)) {
                    throw e;
                }
                else {
                    console.error('Catched error:', e);
                }
            }
        };
    }, []);
    React.useEffect(function () {
        if (typeof onPageScroll === 'function' || typeof onReachBottom === 'function') {
            runtime.onscroll = throttle(function () {
                // 变量scrollTop是滚动条滚动时，滚动条上端距离顶部的距离
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                // 变量windowHeight是可视区的高度
                var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
                // 变量scrollHeight是滚动条的总高度（当前可滚动的页面的总高度）
                var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
                if (typeof onPageScroll === 'function') {
                    onPageScroll.call(context.page, {
                        scrollTop: runtime.pageYOffset,
                    });
                }
                // console.log(scrollTop, windowHeight, scrollTop + windowHeight, scrollHeight, isReachBottom)
                // 滚动条到底部
                if (scrollTop + windowHeight >= scrollHeight - reachBottomDistance) {
                    // 要进行的操作
                    if (!isReachBottom) {
                        isReachBottom = true;
                        if (typeof onReachBottom === 'function') {
                            onReachBottom();
                        }
                    }
                }
                else {
                    isReachBottom = false;
                }
            }, 300);
        }
        // todo
        if (typeof onShareAppMessage === 'function') {
            runtime['onShareAppMessage'] = onShareAppMessage.bind(context.page);
        }
        if (typeof onResize === 'function') {
            runtime.onresize = function () {
                onResize.call(context.page, {
                    size: {
                        windowWidth: runtime.innerWidth,
                        windowHeight: runtime.innerHeight,
                    },
                });
            };
        }
        return function () {
            runtime.onscroll = null;
            runtime.onresize = null;
        };
    }, []);
}
function getCurrentPageQuery() {
    var queryObj = querystring.parse((location.search || '').split('?')[1] || '') || {};
    var hashQueryObj = querystring.parse((location.hash || '').split('?')[1] || '') || {};
    var query = __assign(__assign({}, hashQueryObj), queryObj);
    // query string parse decode succeess
    // Object.keys(query).forEach((key) => {
    //   query[key] = decodeURIComponent(query[key] as string);
    // });
    return query;
}
export function initWebConfig(app, appConfig) {
    // miniprogram.config 配置截取
    app.setConfig(appConfig);
}
//# sourceMappingURL=lifecycle.js.map