"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WedaRouter = exports.InjectContext = void 0;
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var react_router_dom_1 = require("react-router-dom");
var index_1 = tslib_1.__importDefault(require("../pages/index"));
var global_api_1 = require("../app/global-api");
var weda_client_1 = require("@cloudbase/weda-client");
var lowcode_1 = require("../utils/adapter/lowcode");
var generate_1 = require("../utils/adapter/generate");
var dependencies_1 = require("../utils/adapter/dependencies");
var index_2 = require("../utils/index");
var initGlobalVar_1 = require("../utils/initGlobalVar");
var lifecycle_1 = require("../utils/lifecycle");
var cals_1 = require("@cloudbase/cals");
var datasource_1 = require("../utils/adapter/datasource");
var adapter_1 = require("../utils/adapter");
var classnames_1 = tslib_1.__importDefault(require("classnames"));
var react_error_boundary_1 = require("react-error-boundary");
require("./index.css");
var initTcb = weda_client_1._WEDA_CLOUD_SDK.initTcb, setConfig = weda_client_1._WEDA_CLOUD_SDK.setConfig, createStateDataSourceVar = weda_client_1._WEDA_CLOUD_SDK.createStateDataSourceVar, generateParamsParser = weda_client_1._WEDA_CLOUD_SDK.generateParamsParser, EXTRA_API = weda_client_1._WEDA_CLOUD_SDK.EXTRA_API, createDataset = weda_client_1._WEDA_CLOUD_SDK.createDataset;
var getAccessToken = weda_client_1.auth.getAccessToken;
function NotFound(_a) {
    var _b = _a.onNotFound, onNotFound = _b === void 0 ? function () {
        console.error('页面 404，可以在生命周期配置 onAppPageNotFound 并跳转到对应页面');
    } : _b;
    React.useEffect(function () {
        onNotFound();
    }, []);
    return React.createElement(React.Fragment, null, "\u9875\u9762404");
}
function Loading() {
    return (React.createElement(React.Fragment, null,
        React.createElement("style", { type: "text/css", dangerouslySetInnerHTML: {
                __html: ".weda-loading-container {\n            position: fixed;\n            left:0;\n            top:0;\n            width: 100%;\n            display: flex;\n            justify-content: center;\n            align-items: center;\n            flex-direction: column;\n            height:100%;\n\n          }\n          .weda-loading-container .logo {\n            width: 100%;\n            display: flex;\n            justify-content: center;\n            text-align: center;\n            margin-bottom: 50px;\n          }\n\n          .weda-loading-container .sp{\n            width: 48px;\n            height:48px;\n          }\n\n          .weda-loading-container .sp-circle {\n            border: 6px rgba(0,82,217,0.25) solid;\n            border-top: 6px rgba(0,82,217,1) solid;\n            border-radius: 50%;\n            -webkit-animation: spCircRot .6s infinite linear;\n            animation: spCircRot .6s infinite linear;\n          }\n          @-webkit-keyframes spCircRot {\n            from { -webkit-transform: rotate(0deg); }\n            to { -webkit-transform: rotate(359deg); }\n          }\n          @keyframes spCircRot {\n            from { transform: rotate(0deg); }\n            to { transform: rotate(359deg); }\n          }",
            } }),
        React.createElement("div", { id: "loading", className: "weda-loading-container" },
            React.createElement("div", { className: "logo" },
                React.createElement("div", { className: "sp sp-circle" })),
            React.createElement("div", { className: "text", id: "message" }, "\u6B63\u5728\u52A0\u8F7D\u7EC4\u4EF6\u3001\u7F16\u8BD1\u4EE3\u7801..."))));
}
function ErrorStatus(_a) {
    var error = _a.error;
    return (React.createElement(React.Fragment, null,
        React.createElement("style", { type: "text/css", dangerouslySetInnerHTML: {
                __html: ".weda-loading-container {\n            position: fixed;\n            left:0;\n            top:0;\n            width: 100%;\n            display: flex;\n            justify-content: center;\n            align-items: center;\n            flex-direction: column;\n            height:100%;\n            padding: 0 20px;\n          }\n          .weda-loading-container .logo {\n            width: 100%;\n            display: flex;\n            justify-content: center;\n            text-align: center;\n            margin-bottom: 50px;\n          }\n\n          .weda-loading-container .sp{\n            width: 48px;\n            height:48px;\n          }\n\n          .weda-loading-container .sp-circle {\n            border: 6px rgba(0,82,217,0.25) solid;\n            border-top: 6px rgba(0,82,217,1) solid;\n            border-radius: 50%;\n            -webkit-animation: spCircRot .6s infinite linear;\n            animation: spCircRot .6s infinite linear;\n          }\n          @-webkit-keyframes spCircRot {\n            from { -webkit-transform: rotate(0deg); }\n            to { -webkit-transform: rotate(359deg); }\n          }\n          @keyframes spCircRot {\n            from { transform: rotate(0deg); }\n            to { transform: rotate(359deg); }\n          }",
            } }),
        React.createElement("div", { id: "loading", className: "weda-loading-container" },
            React.createElement("div", { className: "logo" },
                React.createElement("img", { width: "50", src: "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PG1hc2sgaWQ9ImEiIHN0eWxlPSJtYXNrLXR5cGU6YWxwaGEiIG1hc2tVbml0cz0idXNlclNwYWNlT25Vc2UiIHg9IjAiIHk9IjIiIHdpZHRoPSIxMCIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTS42MiAyLjE0M2g5LjMxNFYxNy44MkguNjJWMi4xNDN6IiBmaWxsPSIjZmZmIi8+PC9tYXNrPjxnIG1hc2s9InVybCgjYSkiPjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOS45MzMgMTBsLTQuMzIgNy40ODRhLjY3Mi42NzIgMCAwMS0uOTE4LjI0NmwtMy40MDMtMS45NjRBMS4zNDQgMS4zNDQgMCAwMS42MiAxNC42VjUuNGMwLS40OC4yNTYtLjkyNC42NzItMS4xNjRsMy4zMTItMS45MTJjLjQxNS0uMjQuOTI4LS4yNCAxLjM0NCAwbDMuOTg1IDIuM0wxLjY0MSA5LjQyYS42NzIuNjcyIDAgMDAwIDEuMTYzTDQuNjA3IDEyLjNjLjQxNi4yNDIuOTMuMjQyIDEuMzQ2LjAwMWwzLjk4LTIuM3oiIGZpbGw9IiMwMEE4NzAiLz48L2c+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik05LjkzNCAxMGw0LjMyLTcuNDg0YS42NzIuNjcyIDAgMDEuOTE4LS4yNDZsMy40MDMgMS45NjRjLjQxNi4yNC42NzIuNjg0LjY3MiAxLjE2NVYxNC42YzAgLjQ4LS4yNTYuOTI0LS42NzIgMS4xNjRsLTMuMzEyIDEuOTEyYy0uNDE1LjI0LS45MjguMjQtMS4zNDQgMGwtMy45ODUtMi4zIDguMjkyLTQuNzk2YS42NzIuNjcyIDAgMDAwLTEuMTYzTDE1LjI2IDcuN2ExLjM0NCAxLjM0NCAwIDAwLTEuMzQ2IDBMOS45MzQgMTB6IiBmaWxsPSIjNDc4N0YwIi8+PC9zdmc+" })),
            React.createElement("div", { className: "text", id: "message" }, error.message),
            error.stack && (React.createElement("div", { className: "text", id: "stack", style: { whiteSpace: 'pre-line', width: '100%', wordBreak: 'break-all' } }, error.stack.split('\n').slice(0, 5).join('\n'))))));
}
exports.InjectContext = React.createContext({});
function defaultloadDependencies(dependencies, cache) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        return tslib_1.__generator(this, function (_a) {
            (0, dependencies_1.injectExternals)();
            return [2 /*return*/, (0, dependencies_1.loadDependencies)({ dependencies: dependencies }, { cache: cache })];
        });
    });
}
function _WedaApp(_a) {
    var _this = this;
    var _b, _c, _d, _e;
    var cals = _a.cals, _f = _a.dependencies, dependencies = _f === void 0 ? [] : _f, _g = _a._processDependencies, _processDependencies = _g === void 0 ? function (dependencies, cals) {
        var map = {};
        var processedDependiencies = dependencies
            .map(function (item) {
            if (!map["".concat(item.name, "@").concat(item.version)]) {
                map["".concat(item.name, "@").concat(item.version)] = item;
                return item;
            }
            return null;
        })
            .filter(function (item) { return !!item; });
        var usedComponentMap = (0, cals_1.getUsedComps)([cals], processedDependiencies);
        return processedDependiencies.filter(function (item) { return item.name === global_api_1.OFFICIAL_LIB_KEY || !!usedComponentMap[item.name]; });
    } : _g, _h = _a.isHash, isHash = _h === void 0 ? false : _h, _j = _a.historyOption, historyOption = _j === void 0 ? {} : _j, loadDependencies = _a.loadDependencies, loadDependiences = _a.loadDependiences, _k = _a.loadLowcodes, loadLowcodes = _k === void 0 ? function (cals) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
        var codeModulesMap, styleModulesMap, _a, styleCodesMap, _b, state, computedFuncs, common, lifeCycle, handler, keys, lowcodeModuleMap;
        return tslib_1.__generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    codeModulesMap = { global: cals.resources };
                    styleModulesMap = { global: { resources: codeModulesMap.global } };
                    cals.items.forEach(function (page) {
                        if (page.id) {
                            codeModulesMap[page.id] = page.resources || [];
                            styleModulesMap[page.id] = {
                                resources: codeModulesMap[page.id],
                            };
                        }
                    });
                    return [4 /*yield*/, Promise.all([
                            (0, lowcode_1.generateStyleModuleMap)(styleModulesMap),
                            (0, lowcode_1.generateLowcodeModules)({
                                codeModulesMap: codeModulesMap,
                                runtimeWindow: adapter_1.runtime,
                                externals: {
                                    react: 'window.React',
                                    'react-dom': 'window.ReactDOM',
                                },
                            }).catch(function (e) {
                                e.message = "[\u4F4E\u7801\u6A21\u5757\u52A0\u8F7D\u5931\u8D25] ".concat(e.absoluteReqPath ? "[".concat(e.absoluteReqPath, "]") : '', " ").concat(e.message);
                                throw e;
                            }),
                        ])];
                case 1:
                    _a = tslib_1.__read.apply(void 0, [_c.sent(), 2]), styleCodesMap = _a[0], _b = _a[1], state = _b.state, computedFuncs = _b.computedFuncs, common = _b.common, lifeCycle = _b.lifeCycle, handler = _b.handler;
                    keys = tslib_1.__spreadArray([
                        'global'
                    ], tslib_1.__read(cals.items
                        .map(function (page) {
                        return page.id;
                    })
                        .filter(function (item) { return !!item; })), false);
                    lowcodeModuleMap = {};
                    keys.forEach(function (id) {
                        lowcodeModuleMap[id] = {
                            state: state[id] || {},
                            computed: computedFuncs[id] || {},
                            common: common[id] || undefined,
                            lifecycle: lifeCycle[id] || {},
                            handler: handler[id] || {},
                            style: styleCodesMap[id] || [],
                        };
                    });
                    return [2 /*return*/, lowcodeModuleMap];
            }
        });
    }); } : _k, _l = _a.renderLoading, renderLoading = _l === void 0 ? function () { return React.createElement(Loading, null); } : _l, onPageMounted = _a.onPageMounted, _m = _a.onRender, onRender = _m === void 0 ? function () { } : _m, _o = _a.context, context = _o === void 0 ? {
        basic: false,
        looseError: false,
        inIdeEditView: false,
        initAppAPI: initGlobalVar_1.initGlobalVar,
        removeAppAPI: initGlobalVar_1.removeGlobalVar,
        getDatasourceConfig: datasource_1.getConfig,
        // selectedComponentSchemaPath: 'id9',
        // checkVisible: () => true,
        // SlotRender: (props) => {
        //   const { id: slotId } = props;
        //   const isEmptyChildren =
        //     !props.children || (props.children as any).length === 0;
        //   const { selectedComponentSchemaPath } = React.useContext(
        //     InjectContext
        //   ) as any;
        //   return (
        //     <div
        //       className={classnames('_wa-comp-slot-wrapper', {
        //         '_wa-comp-inst-container': true,
        //         [`_wa-comp-id-${slotId}`]: true,
        //         [`_wa-comp-inst`]: true, // 插槽不支持拖拽
        //         '_wa-comp-selected': slotId === selectedComponentSchemaPath,
        //         // @ts-ignore
        //         '_wa-comp-container-empty-children': isEmptyChildren,
        //       })}
        //       title={`插槽: ${slotId}`}
        //       onClick={(e) => {
        //         e.stopPropagation();
        //         console.log(slotId);
        //         // setComponentSchemaPath({ selected: slotId });
        //       }}
        //     >
        //       {isEmptyChildren ? <div className="after" /> : props.children}
        //     </div>
        //   );
        // },
    } : _o;
    var _p = tslib_1.__read(React.useState(false), 2), lowcodeLoaded = _p[0], setLowcodeLoaded = _p[1];
    var _q = tslib_1.__read(React.useState(null), 2), lowcodeError = _q[0], setLowcodeError = _q[1];
    var _r = tslib_1.__read(React.useState(false), 2), dependenciesLoaded = _r[0], setDependenciesLoaded = _r[1];
    var _s = tslib_1.__read(React.useState({}), 2), componentsMap = _s[0], setComponentsMap = _s[1];
    var _t = tslib_1.__read(React.useState({}), 2), componentActionsMap = _t[0], setComponentActionsMap = _t[1];
    var _u = tslib_1.__read(React.useState({}), 2), lowcodeModuleMap = _u[0], setLowcodeModuleMap = _u[1];
    var _v = tslib_1.__read(React.useState({}), 2), componentsInfoMap = _v[0], setComponentsInfoMap = _v[1];
    var processedDependiencies = React.useMemo(function () { return _processDependencies(dependencies, cals); }, [dependencies, cals]);
    var loadedDependienceMapRef = React.useRef({});
    var _loadDependencies = loadDependencies || loadDependiences || defaultloadDependencies;
    var _w = context || {}, _x = _w.looseError, looseError = _x === void 0 ? false : _x, _y = _w.initAppAPI, initAppAPI = _y === void 0 ? initGlobalVar_1.initGlobalVar : _y, _z = _w.removeAppAPI, removeAppAPI = _z === void 0 ? initGlobalVar_1.removeGlobalVar : _z, _0 = _w.getDatasourceConfig, getDatasourceConfig = _0 === void 0 ? datasource_1.getConfig : _0;
    // 数据源初始化
    React.useEffect(function () {
        var _a;
        var isMount = true;
        var datasourceConfig = getDatasourceConfig(cals, { looseError: context.looseError });
        // const time = `==========lowcode ${Date.now()}`;
        global_api_1.app.id = cals.id || cals.appId || '';
        global_api_1.app.domain = ((_a = cals.extra) === null || _a === void 0 ? void 0 : _a.domain) || '';
        global_api_1.app.__internal__.getConfig = function () {
            var _a, _b, _c;
            return {
                id: global_api_1.app.id,
                envId: ((_a = cals.extra) === null || _a === void 0 ? void 0 : _a.envId) || cals.envId,
                clientId: (_b = cals.extra) === null || _b === void 0 ? void 0 : _b.clientId,
                loginConfigVersion: (_c = cals.extra) === null || _c === void 0 ? void 0 : _c.loginConfigVersion,
                staticResourceDomain: global_api_1.app.domain,
                envVersion: datasourceConfig.isProd ? 'production' : 'preview',
                pages: cals.items
                    .map(function (page, index) {
                    var _a, _b, _c;
                    return ({
                        id: page.id,
                        isHome: !((_a = cals.extra) === null || _a === void 0 ? void 0 : _a.rootPath) && (cals.main ? page.id === cals.main : index === 0),
                        type: ((_b = page === null || page === void 0 ? void 0 : page.attributes) === null || _b === void 0 ? void 0 : _b.isCustomLoginPage) ? 'login' : '',
                        reachBottomDistance: (_c = page === null || page === void 0 ? void 0 : page.attributes) === null || _c === void 0 ? void 0 : _c.reachBottomDistance,
                    });
                })
                    .sort(function (item) { return (item.isHome ? -1 : 1); })
                    .map(function (item) { return ({
                    id: item.id,
                    type: item.type,
                    reachBottomDistance: item.reachBottomDistance,
                }); }),
            };
        };
        // 设置数据源请求的 loading 及 toast 处理
        var config = tslib_1.__assign(tslib_1.__assign({}, datasourceConfig), { beforeDSRequest: function (cfg) {
                if (!cfg.options || !cfg.options.showLoading)
                    return;
                global_api_1.app.showLoading();
            }, beforeCallFunction: function (params) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                var loginConfigVersion, skip, accessToken, e_1;
                var _a, _b, _c;
                return tslib_1.__generator(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            if (context.inIdeEditView) {
                                return [2 /*return*/, params];
                            }
                            _d.label = 1;
                        case 1:
                            _d.trys.push([1, 3, , 4]);
                            loginConfigVersion = global_api_1.app.__internal__.getConfig().loginConfigVersion;
                            skip = false;
                            switch ((_a = params === null || params === void 0 ? void 0 : params.data) === null || _a === void 0 ? void 0 : _a.methodName) {
                                case 'callWedaApi': {
                                    if (['GetMiniProgramUserTicket', 'DescribeRuntimeResourceStrategy'].includes((_b = params === null || params === void 0 ? void 0 : params.data) === null || _b === void 0 ? void 0 : _b.params.action)) {
                                        skip = true;
                                    }
                                    break;
                                }
                            }
                            // 后续做过滤处理
                            if (!loginConfigVersion || (((_c = params === null || params === void 0 ? void 0 : params.data) === null || _c === void 0 ? void 0 : _c.mode) === 'c' && skip)) {
                                return [2 /*return*/, params];
                            }
                            return [4 /*yield*/, getAccessToken()];
                        case 2:
                            accessToken = (_d.sent()).accessToken;
                            if (accessToken) {
                                params.data.accessToken = accessToken;
                            }
                            return [3 /*break*/, 4];
                        case 3:
                            e_1 = _d.sent();
                            console.error('beforeCallFunction error', e_1);
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/, params];
                    }
                });
            }); }, afterDSRequest: function (cfg, error, result) {
                if (!cfg.options)
                    return;
                if (cfg.options.showLoading)
                    global_api_1.app.hideLoading();
                if (!cfg.options.showToast)
                    return;
                var isSuccess = !error && result && !result.code;
                global_api_1.app.showToast({ icon: isSuccess ? 'success' : 'error' });
            }, afterCallFunction: function (params, error, res) {
                var _a, _b, _c, _d;
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var loginConfigVersion, authConfig, isAnonymous;
                    return tslib_1.__generator(this, function (_e) {
                        switch (_e.label) {
                            case 0:
                                if (context.inIdeEditView) {
                                    return [2 /*return*/];
                                }
                                if (!(((_b = (_a = params === null || params === void 0 ? void 0 : params.data) === null || _a === void 0 ? void 0 : _a.params) === null || _b === void 0 ? void 0 : _b.action) != 'DescribeRuntimeResourceStrategy' &&
                                    ['InnerError.AuthFailure', 'InvalidAccessToken'].includes((_c = res === null || res === void 0 ? void 0 : res.result) === null || _c === void 0 ? void 0 : _c.code))) return [3 /*break*/, 4];
                                loginConfigVersion = global_api_1.app.__internal__.getConfig().loginConfigVersion;
                                if (!((_d = window === null || window === void 0 ? void 0 : window._WedaHostConfig) === null || _d === void 0 ? void 0 : _d.logout)) return [3 /*break*/, 1];
                                global_api_1.app.showToast({
                                    title: '接口无访问权限',
                                    icon: 'error',
                                });
                                setTimeout(function () {
                                    window._WedaHostConfig.logout();
                                }, 300);
                                return [3 /*break*/, 4];
                            case 1:
                                if (!loginConfigVersion) return [3 /*break*/, 4];
                                return [4 /*yield*/, (0, index_2.getAuthConfig)()];
                            case 2:
                                authConfig = _e.sent();
                                return [4 /*yield*/, (0, index_2.checkAnonymous)()];
                            case 3:
                                isAnonymous = _e.sent();
                                if (isAnonymous && authConfig.RejectStrategy == 'to_login') {
                                    (0, index_2.redirectToLogin)();
                                }
                                else if (authConfig.RejectStrategy == 'show_warning') {
                                    global_api_1.app.showToast({
                                        title: '接口无访问权限',
                                        icon: 'error',
                                    });
                                }
                                _e.label = 4;
                            case 4: return [2 /*return*/];
                        }
                    });
                });
            } });
        setConfig(config);
        if (!context.basic) {
            initTcb();
        }
        loadLowcodes(cals).then(function (lowcodeModuleMap) {
            if (isMount) {
                initAppAPI === null || initAppAPI === void 0 ? void 0 : initAppAPI({
                    common: lowcodeModuleMap.global.common,
                    state: lowcodeModuleMap.global.state,
                    computedFuncs: lowcodeModuleMap.global.computed,
                });
                // 初始化应用生命周期
                (0, lifecycle_1.initAppLifeCycle)(global_api_1.app, tslib_1.__assign(tslib_1.__assign({}, lowcodeModuleMap.global.lifecycle), { beforeCustomLaunch: function (query) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                        return tslib_1.__generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    EXTRA_API.setParams('$global', query || {});
                                    return [4 /*yield*/, createStateDataSourceVar('$global', generateParamsParser({ app: global_api_1.app, $page: {} }))];
                                case 1:
                                    _a.sent();
                                    return [2 /*return*/];
                            }
                        });
                    }); } }));
                setLowcodeModuleMap(lowcodeModuleMap);
                setLowcodeLoaded(true);
                setLowcodeError(null);
                // console.timeEnd(time);
            }
        }, function (e) {
            if (!context.looseError) {
                setLowcodeError(e);
            }
            else {
                console.error(e);
            }
            setLowcodeLoaded(true);
        });
        return function () {
            isMount = false;
            removeAppAPI === null || removeAppAPI === void 0 ? void 0 : removeAppAPI();
            (0, lowcode_1.cleanLowcodeContext)();
            (0, lifecycle_1.removeAppLifeCycle)();
            // 变量先更新， 然后 create 先更新
            // 然后 remove 了
            // 然后 mount 了
            // 然是没有新 create， 这里先不清理了
            // removeHistory();
        };
    }, []);
    React.useEffect(function () {
        // const timeTag = `==========depen ${Date.now()}`;
        // console.time(timeTag);
        if (processedDependiencies.find(function (item) { return !loadedDependienceMapRef.current[item.name]; })) {
            _loadDependencies(processedDependiencies).then(function (_a) {
                var controlMap = _a.controlMap, componentsMap = _a.componentsMap, componentActionsMap = _a.componentActionsMap;
                processedDependiencies.forEach(function (item) {
                    loadedDependienceMapRef.current[item.name] = true;
                });
                setComponentsMap(componentsMap);
                setComponentActionsMap(componentActionsMap);
                setComponentsInfoMap((0, generate_1.getComponentsInfo)(processedDependiencies.map(function (item) {
                    var control = controlMap["".concat(item.name, "@").concat(item.version)];
                    var overwrite = {};
                    if (control) {
                        if (control.schemaVersion) {
                            overwrite['schemaVersion'] = control.schemaVersion;
                        }
                        if (control.components) {
                            overwrite['components'] = control.components;
                        }
                    }
                    return tslib_1.__assign(tslib_1.__assign({}, item), overwrite);
                })));
                // console.timeEnd(timeTag);
                setDependenciesLoaded(true);
            });
        }
        else {
            setDependenciesLoaded(true);
            // if (!componentsMap) {
            //   setComponentsMap({});
            // }
            // if (!componentActionsMap) {
            //   setComponentActionsMap({});
            // }
            // if (!componentsInfoMap) {
            //   setComponentsInfoMap({});
            // }
        }
    }, [processedDependiencies]);
    var basename = historyOption.basename || ((_d = (_c = (_b = cals.extra) === null || _b === void 0 ? void 0 : _b.appConfig) === null || _c === void 0 ? void 0 : _c.window) === null || _d === void 0 ? void 0 : _d.basename) || '/';
    return lowcodeLoaded && dependenciesLoaded ? (lowcodeError ? (React.createElement(ErrorStatus, { error: lowcodeError })) : (React.createElement(React.Fragment, null,
        React.createElement("style", { type: "text/css", dangerouslySetInnerHTML: {
                __html: "".concat((((_e = lowcodeModuleMap.global) === null || _e === void 0 ? void 0 : _e.style) || []).map(function (item) { return item.code; }).join('\n'), "\n              @media screen and (min-width: 1024px) {\n                body {\n                  height: 100%;\n                }\n              }\n              "),
            } }),
        React.createElement(exports.InjectContext.Provider, { value: tslib_1.__assign(tslib_1.__assign({}, context), { componentsInfoMap: componentsInfoMap }) },
            React.createElement(WedaRouter, { historyOptions: { basename: basename, isHash: isHash, type: historyOption === null || historyOption === void 0 ? void 0 : historyOption.type }, routes: cals.items.map(function (page, index) {
                    var _a, _b, _c, _d;
                    return ({
                        id: page.id,
                        isHome: !((_a = cals.extra) === null || _a === void 0 ? void 0 : _a.rootPath) && (cals.main ? page.id === cals.main : index === 0),
                        path: ((_b = cals.extra) === null || _b === void 0 ? void 0 : _b.rootPath) ? "/".concat((_c = cals.extra) === null || _c === void 0 ? void 0 : _c.rootPath, "/").concat(page.id) : "/".concat(page.id),
                        root: ((_d = cals.extra) === null || _d === void 0 ? void 0 : _d.rootPath) || '',
                        render: function () {
                            return (React.createElement(index_1.default, { page: page, generateComponentsMap: function () { return componentsMap; }, generateActionsMap: function () { return componentActionsMap; }, generateLowcodeModule: function () {
                                    return lowcodeModuleMap[page.id] || {};
                                }, generateContext: function (ctx, page) {
                                    var _a = (0, generate_1.getComponentSchema)(ctx, page, false, componentsInfoMap, undefined, { looseError: context.looseError }), widgets = _a.widgets, componentSchema = _a.componentSchema, dataBinds = _a.dataBinds;
                                    return {
                                        widgetContext: widgets,
                                        componentSchema: componentSchema,
                                        dataBinds: dataBinds,
                                    };
                                }, onMounted: onPageMounted, onRender: onRender, initDataContext: context === null || context === void 0 ? void 0 : context.defaultDataContext, injectContext: {
                                    $page: context.$page,
                                    dataContext: context.dataContext,
                                    onDataContextChange: context.onDataContextChange,
                                }, options: {
                                    looseError: context.looseError,
                                    disabledCheckAuth: context.inIdeEditView,
                                } }));
                        },
                    });
                }), onNotFound: function () {
                    var _a, _b;
                    var onNotFound = (_b = (_a = lowcodeModuleMap === null || lowcodeModuleMap === void 0 ? void 0 : lowcodeModuleMap.global) === null || _a === void 0 ? void 0 : _a.lifecycle) === null || _b === void 0 ? void 0 : _b.onAppPageNotFound;
                    if (onNotFound) {
                        onNotFound();
                    }
                    console.error('页面 404，可以在生命周期配置 onAppPageNotFound 并跳转到对应页面');
                } }))))) : (renderLoading());
}
function WedaApp(props) {
    var _a = props.ErrorBoundary, ErrorBoundary = _a === void 0 ? react_error_boundary_1.ErrorBoundary : _a, restProps = tslib_1.__rest(props, ["ErrorBoundary"]);
    return (React.createElement(ErrorBoundary, { FallbackComponent: ErrorStatus },
        React.createElement(_WedaApp, tslib_1.__assign({}, restProps))));
}
exports.default = WedaApp;
function WedaRouter(_a) {
    var historyOptions = _a.historyOptions, _b = _a.routes, routes = _b === void 0 ? [] : _b, onNotFound = _a.onNotFound;
    var basename = historyOptions.basename, isHash = historyOptions.isHash, type = historyOptions.type;
    var history = React.useMemo(function () {
        return (0, index_2.createHistory)({
            basename: basename,
        }, isHash ? 'hash' : type);
    }, [basename, isHash]);
    // let [state, setState] = React.useState({
    //   action: history.action,
    //   location: history.location,
    // });
    // React.useLayoutEffect(() => history.listen(setState), [history]);
    var home = routes.find(function (route) { return !!route.isHome; });
    if (adapter_1.runtime['$$global']) {
        adapter_1.runtime['$$global'].homePageId = (home === null || home === void 0 ? void 0 : home.id) || '';
    }
    return (React.createElement(react_router_dom_1.Router, { history: history },
        React.createElement(React.Suspense, { fallback: React.createElement(Loading, null) },
            React.createElement(react_router_dom_1.Switch, null,
                home && (React.createElement(react_router_dom_1.Route, { path: "/".concat(home.root || ''), exact: true },
                    React.createElement(react_router_dom_1.Redirect, { to: home.path }))),
                routes.map(function (route) {
                    return React.createElement(react_router_dom_1.Route, { key: route.path, path: route.path, render: route.render });
                }),
                React.createElement(react_router_dom_1.Route, null,
                    React.createElement(NotFound, { onNotFound: onNotFound }))))));
}
exports.WedaRouter = WedaRouter;
function editProcess(_a) {
    var controlMap = _a.controlMap, componentsMap = _a.componentsMap, dependencies = _a.dependencies;
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var componentInfo;
        return tslib_1.__generator(this, function (_b) {
            componentInfo = (0, generate_1.getComponentsInfo)(dependencies.map(function (item) {
                var control = controlMap["".concat(item.name, "@").concat(item.version)];
                var overwrite = {};
                if (control) {
                    if (control.schemaVersion) {
                        overwrite['schemaVersion'] = control.schemaVersion;
                    }
                    if (control.components) {
                        overwrite['components'] = control.components;
                    }
                }
                return tslib_1.__assign(tslib_1.__assign({}, item), overwrite);
            }));
            return [2 /*return*/, {
                    controlMap: controlMap,
                    componentsMap: Object.entries(componentsMap).reduce(function (map, _a) {
                        var _b = tslib_1.__read(_a, 2), sourceKey = _b[0], Component = _b[1];
                        map[sourceKey] = function (props) {
                            var _a;
                            var _b, _c, _d;
                            var injectContext = React.useContext(exports.InjectContext);
                            var _e = props.className, className = _e === void 0 ? '' : _e, restProps = tslib_1.__rest(props, ["className"]);
                            var _f = tslib_1.__read(sourceKey.split(':'), 2), module = _f[0], componentName = _f[1];
                            var baseClassName = [];
                            var isContainer = (_b = componentInfo[sourceKey]) === null || _b === void 0 ? void 0 : _b.isContainer;
                            var isContainerEmptyChildren = isContainer && ((_c = props.children) === null || _c === void 0 ? void 0 : _c.length) == 0;
                            if (isContainer) {
                                baseClassName.push('_wa-comp-inst-container');
                            }
                            if (isContainerEmptyChildren) {
                                baseClassName.push('_wa-comp-container-empty-children');
                            }
                            return (React.createElement(Component, tslib_1.__assign({}, restProps, { className: (0, classnames_1.default)(props.className || '', (_a = {
                                        '_wa-editor-selected-disable': ((_d = props.forIndexes) === null || _d === void 0 ? void 0 : _d[0]) > 0
                                    },
                                    _a["_wa-comp-id-".concat(props.id)] = true,
                                    _a['_wa-comp-inst'] = true,
                                    _a['weda-draggable'] = true,
                                    _a._fe = true,
                                    _a["_wa-comp-name-".concat(componentName)] = true,
                                    _a["_sk-".concat(sourceKey.replace(/:/, '__'))] = true,
                                    _a['_wa-comp-inst-container'] = isContainer,
                                    _a['_wa-comp-container-empty-children'] = isContainerEmptyChildren,
                                    _a['_wa-comp-selected'] = (injectContext === null || injectContext === void 0 ? void 0 : injectContext.selectedComponentSchemaPath) === props.id,
                                    _a)) })));
                        };
                        return map;
                    }, {}),
                }];
        });
    });
}
//# sourceMappingURL=index.js.map