"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initWebConfig = exports.usePageLifeCycle = exports.removeAppLifeCycle = exports.initAppLifeCycle = void 0;
var tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/no-empty-function */
/**
 * 生命周期处理函数
 */
var React = (0, tslib_1.__importStar)(require("react"));
var lodash_es_1 = require("lodash-es");
var querystring = (0, tslib_1.__importStar)(require("query-string"));
var adapter_1 = require("./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 = {};
function initAppLifeCycle(app, appLifeCycle) {
    var _this = this;
    appLifeCycle = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, APPLIFECYCLE), appLifeCycle);
    var onAppLaunch = function (query) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
        return (0, tslib_1.__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 (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
        return (0, tslib_1.__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, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(args), false));
            },
            appHide: function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return appLifeCycle.onAppHide.apply(appLifeCycle, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(args), false));
            },
            error: function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return appLifeCycle.onAppError.apply(appLifeCycle, (0, tslib_1.__spreadArray)([], (0, tslib_1.__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) {
            adapter_1.runtime.addEventListener(event_1, _HANDLER_MAP[event_1]);
        }
        alreadyInitAppLifeCycle = true;
    }
}
exports.initAppLifeCycle = initAppLifeCycle;
function removeAppLifeCycle() {
    for (var event_2 in _HANDLER_MAP) {
        adapter_1.runtime.removeEventListener(event_2, _HANDLER_MAP[event_2]);
    }
    _HANDLER_MAP = {};
    alreadyInitAppLifeCycle = false;
}
exports.removeAppLifeCycle = removeAppLifeCycle;
var isReachBottom = false;
// web 端使用lifeCycle
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;
    adapter_1.runtime['$page'] = context.page;
    React.useEffect(function () {
        var _a;
        var _onPageLoad = function (query) {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, (beforePageCustomLaunch && 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') {
            adapter_1.runtime.onscroll = (0, lodash_es_1.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: adapter_1.runtime.pageYOffset,
                    });
                }
                // console.log(scrollTop, windowHeight, scrollTop + windowHeight, scrollHeight, isReachBottom)
                //滚动条到底部
                if (scrollTop + windowHeight >= scrollHeight && !isReachBottom) {
                    //要进行的操作
                    isReachBottom = true;
                    if (typeof onReachBottom === 'function') {
                        onReachBottom.call(context.page);
                    }
                }
                // 容许用户回弹50然后执行ReachBottom， 50为测试最佳值
                if (scrollTop + windowHeight < scrollHeight - 50) {
                    isReachBottom = false;
                }
            }, 300);
        }
        // todo
        if (typeof onShareAppMessage === 'function') {
            adapter_1.runtime['onShareAppMessage'] = onShareAppMessage.bind(context.page);
        }
        if (typeof onResize === 'function') {
            adapter_1.runtime.onresize = function () {
                onResize.call(context.page, {
                    size: {
                        windowWidth: adapter_1.runtime.innerWidth,
                        windowHeight: adapter_1.runtime.innerHeight,
                    },
                });
            };
        }
        return function () {
            adapter_1.runtime.onscroll = null;
            adapter_1.runtime.onresize = null;
        };
    }, []);
}
exports.usePageLifeCycle = usePageLifeCycle;
function getCurrentPageQuery() {
    var queryText = location.href.split('?')[1];
    var query = querystring.parse(queryText) || {};
    Object.keys(query).forEach(function (key) {
        query[key] = decodeURIComponent(query[key]);
    });
    return query;
}
function initWebConfig(app, appConfig) {
    // miniprogram.config 配置截取
    app.setConfig(appConfig);
}
exports.initWebConfig = initWebConfig;
//# sourceMappingURL=lifecycle.js.map