import { __awaiter, __rest } from "tslib";
import * as React from 'react';
import { Router, Route, Redirect, Switch } from 'react-router-dom';
import PageRender from '../pages/index';
import { app, $w as baseAPI } from '../app/global-api';
import { _WEDA_CLOUD_SDK as WEDA_CLOUD_SDK, auth } from '@cloudbase/weda-client';
import { cleanLowcodeContext, generateLowcodeModules, generateStyleModuleMap } from '../utils/adapter/lowcode';
import { getComponentsInfo, getComponentSchema, generateDatasetQuery } from '../utils/adapter/generate';
import { loadDependencies as _loadDependencies, injectExternals, loadExternalResources as _loadExternalResources, loadRuntimeDependencies, upsertFavicon, loadMockDependencies, WrapComponentFieldWithPropsHook, } from '../utils/adapter/dependencies';
import { getAuthConfig, redirectToLogin, dealCache, checkAnonymous, defaultGenerateLoginUrl, CALC_RPX_ROOT_VAL_NAME, } from '../utils/index';
import { initGlobalVar, removeGlobalVar } from '../utils/initGlobalVar';
import { initAppLifeCycle, removeAppLifeCycle } from '../utils/lifecycle';
import { getUsedComps, parseVersion, OFFICIAL_LIB_KEY } from '@cloudbase/cals';
import { getConfig as _getConfig } from '../utils/adapter/datasource';
import { runtime } from '../utils/adapter';
import classnames from 'classnames';
import { ErrorBoundary as ReactErrorBoundary } from 'react-error-boundary';
import { start } from 'qiankun';
import './index.css';
import { isEnableWecom, setEnableObserverRef, setEnablePageRoot, setEnableWecom, simpleCheckAdminPortal, getNetworkType, } from '../utils/common';
import { OwnerComponentContext, useHistoryMemo } from '../utils/hooks';
import { debounce } from 'lodash-es';
import { generateCompositeComponent } from '../pages/comositeComponent';
import { APP_TEMPLATE_KEY } from '../utils/constants';
const { initTcb, setConfig, createStateDataSourceVar, generateParamsParser, EXTRA_API } = WEDA_CLOUD_SDK;
const { getAccessToken } = auth;
const STATUS_STYLE = `.weda-loading-container {
  position: fixed;
  left:0;
  top:0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height:100%;
  padding: 0 20px;
}
.weda-loading-container .logo {
  width: 100%;
  display: flex;
  justify-content: center;
  text-align: center;
  margin-bottom: 50px;
}

.weda-loading-container .sp{
  width: 48px;
  height:48px;
}

.weda-loading-container .sp-circle {
  border: 6px rgba(0,82,217,0.25) solid;
  border-top: 6px rgba(0,82,217,1) solid;
  border-radius: 50%;
  -webkit-animation: spCircRot .6s infinite linear;
  animation: spCircRot .6s infinite linear;
}
@-webkit-keyframes spCircRot {
  from { -webkit-transform: rotate(0deg); }
  to { -webkit-transform: rotate(359deg); }
}
@keyframes spCircRot {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}`;
function NotFound({ path = '', onNotFound = () => {
    console.error('页面 404，可以在生命周期配置 onAppPageNotFound 并跳转到对应页面');
}, }) {
    React.useEffect(() => {
        onNotFound();
    }, []);
    return (React.createElement(React.Fragment, null,
        React.createElement("style", { type: "text/css", dangerouslySetInnerHTML: {
                __html: STATUS_STYLE,
            } }),
        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" },
                "\u5F53\u524D\u9875\u9762 ",
                path,
                " \u65E0\u6CD5\u8BBF\u95EE\uFF0C\u53EF\u80FD\u7531\u4E8E\u7F51\u5740\u5DF2\u5220\u9664\u6216\u5C1A\u672A\u751F\u6548"))));
}
function Loading({ message = '正在加载组件、编译代码...' }) {
    const [visible, setVisible] = React.useState(false);
    React.useEffect(() => {
        setTimeout(() => {
            setVisible(true);
        }, 100);
    }, []);
    return (visible && (React.createElement(React.Fragment, null,
        React.createElement("style", { type: "text/css", dangerouslySetInnerHTML: {
                __html: STATUS_STYLE,
            } }),
        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" }, message)))));
}
function ErrorStatus({ error }) {
    return (React.createElement(React.Fragment, null,
        React.createElement("style", { type: "text/css", dangerouslySetInnerHTML: {
                __html: STATUS_STYLE,
            } }),
        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'))))));
}
export const InjectContext = React.createContext({});
function defaultloadDependencies(dependencies, cache) {
    return __awaiter(this, void 0, void 0, function* () {
        injectExternals();
        return _loadDependencies({ dependencies }, { cache });
    });
}
const _WedaApp = React.forwardRef((props, ref) => {
    const { cals, loadExternalResources = _loadExternalResources, renderLoading = ({ message }) => React.createElement(Loading, { message: message }), } = props;
    const [externalResourceLoaded, setExternalResourceLoaded] = React.useState(false);
    React.useEffect(() => {
        loadExternalResources({ externalResources: cals.externalResources || [] }, { cache: true }).then(() => {
            setExternalResourceLoaded(true);
        });
    }, []);
    return externalResourceLoaded ? (React.createElement(WedaAppContent, Object.assign({}, props, { ref: ref }))) : (renderLoading({ message: '加载外部资源...' }));
});
_WedaApp.displayName = '_WedaApp';
const WedaAppContent = React.forwardRef(({ cals, dependencies = [], _processDependencies = (dependencies, cals) => {
    let map = {};
    let processedDependiencies = dependencies
        .map((item) => {
        if (!map[`${item.name}@${item.version}`]) {
            map[`${item.name}@${item.version}`] = item;
            return item;
        }
        return null;
    })
        .filter((item) => !!item);
    let usedComponentMap = getUsedComps([cals], processedDependiencies);
    return processedDependiencies.filter((item) => item.name === OFFICIAL_LIB_KEY || !!usedComponentMap[item.name]);
}, isHash = false, historyOption = {}, loadDependencies, loadDependiences, loadLowcodes = (cals) => __awaiter(void 0, void 0, void 0, function* () {
    const FEATURE_MAP = parseVersion(cals.schemaVersion, []);
    const processCssUnit = FEATURE_MAP.defaultDynamicCssUnit ? 'rem' : 'rpx';
    const codeModulesMap = { global: cals.resources };
    const styleModulesMap = { global: { resources: codeModulesMap.global, processCssUnit } };
    cals.items.forEach((page) => {
        if (page.id) {
            codeModulesMap[page.id] = page.resources || [];
            styleModulesMap[page.id] = {
                resources: codeModulesMap[page.id],
                processCssUnit,
            };
        }
    });
    const [styleCodesMap, { state, computedFuncs, common, lifeCycle, handler }] = yield Promise.all([
        generateStyleModuleMap(styleModulesMap),
        generateLowcodeModules({
            codeModulesMap,
            runtimeWindow: runtime,
            externals: {
                react: 'window.React',
                'react-dom': 'window.ReactDOM',
            },
        }).catch((e) => {
            e.message = `[低码模块加载失败] ${e.absoluteReqPath ? `[${e.absoluteReqPath}]` : ''} ${e.message}`;
            throw e;
        }),
    ]);
    const keys = [
        'global',
        ...cals.items
            .map((page) => {
            return page.id;
        })
            .filter((item) => !!item),
    ];
    const lowcodeModuleMap = {};
    keys.forEach((id) => {
        lowcodeModuleMap[id] = {
            state: state[id] || {},
            computed: computedFuncs[id] || {},
            common: common[id] || undefined,
            lifecycle: lifeCycle[id] || {},
            handler: handler[id] || {},
            style: styleCodesMap[id] || [],
        };
    });
    return lowcodeModuleMap;
}), renderLoading = ({ message }) => React.createElement(Loading, { message: message }), onPageMounted, onRender = () => { }, context = {
    basic: false,
    looseError: false,
    reuseWidget: false,
    // 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>
    //   );
    // },
}, }, ref) => {
    var _a, _b, _c, _d;
    const [lowcodeLoaded, setLowcodeLoaded] = React.useState(false);
    const [lowcodeError, setLowcodeError] = React.useState(null);
    const [dependenciesLoaded, setDependenciesLoaded] = React.useState(false);
    const [beforeAppLoadDone, setBeforeAppLoadDone] = React.useState(false);
    const [componentsMap, setComponentsMap] = React.useState({});
    const [componentActionsMap, setComponentActionsMap] = React.useState({});
    const [lowcodeModuleMap, setLowcodeModuleMap] = React.useState({});
    const [componentsInfoMap, setComponentsInfoMap] = React.useState({});
    const processedDependiencies = React.useMemo(() => _processDependencies(dependencies, cals), [dependencies, cals]);
    const loadedDependienceMapRef = React.useRef({});
    const _loadDependencies = loadDependencies || loadDependiences || defaultloadDependencies;
    const isMountRef = React.useRef(false);
    const { looseError = false, initAppAPI = (app) => { }, removeAppAPI = removeGlobalVar, getDatasourceConfig = _getConfig, generateLoginUrl = defaultGenerateLoginUrl, } = context || {};
    /**
     * 在 page lifecycle 之前就创建 history 对象
     */
    const history = useHistoryMemo({
        basename: historyOption.basename || ((_c = (_b = (_a = cals.extra) === null || _a === void 0 ? void 0 : _a.appConfig) === null || _b === void 0 ? void 0 : _b.window) === null || _c === void 0 ? void 0 : _c.basename) || '/',
        isHash,
        type: historyOption.type,
    });
    const applyLowcodes = React.useCallback((cals, patch = false) => {
        return loadLowcodes(cals).then((lowcodeModuleMap) => {
            var _a;
            if (isMountRef.current) {
                removeAppAPI === null || removeAppAPI === void 0 ? void 0 : removeAppAPI();
                cleanLowcodeContext();
                removeAppLifeCycle();
                if (lowcodeModuleMap.global) {
                    initGlobalVar({
                        common: lowcodeModuleMap.global.common,
                        state: lowcodeModuleMap.global.state,
                        computedFuncs: lowcodeModuleMap.global.computed,
                    }, initAppAPI);
                    app.dataset.query = generateDatasetQuery(((_a = cals.dataset) === null || _a === void 0 ? void 0 : _a.query) || {}, { $w: app.__internal__.$w, $app: app, $page: null }, { isComposite: false, useScopeWidgetData: true, looseError });
                    // 初始化应用生命周期
                    initAppLifeCycle(app, Object.assign(Object.assign({}, lowcodeModuleMap.global.lifecycle), { beforeCustomLaunch: (query) => __awaiter(void 0, void 0, void 0, function* () {
                            var _b, _c, _d, _e, _f, _g, _h;
                            try {
                                EXTRA_API.setParams('$global', query || {});
                                /**
                                 * 全局模型变量的初始化
                                 * 阻塞流程
                                 */
                                yield createStateDataSourceVar('$global', generateParamsParser({ app, $page: {}, $w: (_b = app === null || app === void 0 ? void 0 : app.__internal__) === null || _b === void 0 ? void 0 : _b.$w }));
                                // eslint-disable-next-line no-restricted-syntax
                                for (const queryId in ((_c = cals.dataset) === null || _c === void 0 ? void 0 : _c.query) || {}) {
                                    if (((_d = cals.dataset.query[queryId]) === null || _d === void 0 ? void 0 : _d.trigger) === 'auto') {
                                        try {
                                            (_h = (_g = (_f = (_e = app.dataset) === null || _e === void 0 ? void 0 : _e.query) === null || _f === void 0 ? void 0 : _f[queryId]) === null || _g === void 0 ? void 0 : _g.trigger) === null || _h === void 0 ? void 0 : _h.call(_g);
                                        }
                                        catch (e) {
                                            console.error(`query ${queryId} 初始化失败：`, e);
                                        }
                                    }
                                }
                            }
                            catch (e) {
                                throw e;
                            }
                            finally {
                                setBeforeAppLoadDone(true);
                            }
                        }) }), !!patch);
                }
                else {
                    setBeforeAppLoadDone(true);
                }
                if (patch) {
                    setLowcodeModuleMap((current) => {
                        return Object.assign(Object.assign({}, current), lowcodeModuleMap);
                    });
                }
                else {
                    setLowcodeModuleMap(lowcodeModuleMap);
                }
                setLowcodeLoaded(true);
                setLowcodeError(null);
                // console.timeEnd(time);
            }
        }, (e) => {
            if (!context.looseError) {
                setLowcodeError(e);
            }
            else {
                console.error(e);
            }
            setBeforeAppLoadDone(true);
            setLowcodeLoaded(true);
        });
    }, [loadLowcodes, initAppAPI, removeAppAPI]);
    React.useImperativeHandle(ref, () => {
        return {
            applyLowcodes,
        };
    }, [applyLowcodes]);
    React.useEffect(() => {
        const adminPortal = simpleCheckAdminPortal();
        if (!adminPortal) {
            start();
        }
        if (!(window === null || window === void 0 ? void 0 : window.__WEDA_LOG_LEVEL__)) {
            try {
                window.__WEDA_LOG_LEVEL__ = localStorage.getItem('__WEDA_LOG_LEVEL__');
            }
            catch (e) { }
        }
    }, []);
    // 数据源初始化
    React.useEffect(() => {
        var _a, _b, _c;
        isMountRef.current = true;
        const datasourceConfig = getDatasourceConfig(cals, { looseError: context.looseError });
        /**
         * 初始化 feature map
         */
        if (isEnableWecom(datasourceConfig.envID)) {
            setEnableWecom(true);
        }
        else {
            setEnableWecom(false);
        }
        // const time = `==========lowcode ${Date.now()}`;
        app.id = datasourceConfig.appID;
        app.domain = ((_a = cals.extra) === null || _a === void 0 ? void 0 : _a.domain) || '';
        app.label = app.label || (cals === null || cals === void 0 ? void 0 : cals.label);
        app.version = app.version || (cals === null || cals === void 0 ? void 0 : cals.version) || '';
        // 初始化系统变量
        const isMobile = (_b = app === null || app === void 0 ? void 0 : app.__internal__) === null || _b === void 0 ? void 0 : _b.isMobile;
        // 设备信息
        baseAPI.device.viewport = {
            width: runtime.innerWidth,
            height: runtime.innerHeight,
        };
        if (isMobile === null || isMobile === void 0 ? void 0 : isMobile()) {
            baseAPI.device.networkType = getNetworkType(runtime);
        }
        else {
            baseAPI.device.networkType = '';
        }
        const { _deployType } = runtime;
        if (datasourceConfig.isPrivate && ['hybrid', 'hybrid-private'].includes(_deployType)) {
            app.domain = location.hostname;
        }
        app.__internal__.getConfig = () => {
            var _a;
            return {
                id: app.id,
                label: app.label,
                version: app.version,
                envId: datasourceConfig.envID,
                clientId: datasourceConfig.tcbClientId,
                loginConfigVersion: (_a = cals.extra) === null || _a === void 0 ? void 0 : _a.loginConfigVersion,
                staticResourceDomain: app.domain,
                envVersion: datasourceConfig.isProd ? 'production' : 'preview',
                pages: cals.items
                    .map((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((item) => (item.isHome ? -1 : 1))
                    .map((item) => ({
                    id: item.id,
                    type: item.type,
                    reachBottomDistance: item.reachBottomDistance,
                })),
            };
        };
        // 设置数据源请求的 loading 及 toast 处理
        const config = Object.assign(Object.assign({}, datasourceConfig), { beforeDSRequest: (cfg) => {
                if (!cfg.options || !cfg.options.showLoading)
                    return;
                app.showLoading({});
            }, beforeCallFunction: (params) => __awaiter(void 0, void 0, void 0, function* () {
                var _d, _e, _f;
                if (context.basic) {
                    return params;
                }
                try {
                    const { loginConfigVersion } = app.__internal__.getConfig();
                    let skip = false;
                    switch ((_d = params === null || params === void 0 ? void 0 : params.data) === null || _d === void 0 ? void 0 : _d.methodName) {
                        case 'callWedaApi': {
                            if (['GetMiniProgramUserTicket', 'DescribeRuntimeResourceStrategy'].includes((_e = params === null || params === void 0 ? void 0 : params.data) === null || _e === void 0 ? void 0 : _e.params.action)) {
                                skip = true;
                            }
                            break;
                        }
                    }
                    // 后续做过滤处理
                    if (!loginConfigVersion || (((_f = params === null || params === void 0 ? void 0 : params.data) === null || _f === void 0 ? void 0 : _f.mode) === 'c' && skip)) {
                        return params;
                    }
                    const { accessToken } = yield getAccessToken();
                    if (accessToken) {
                        params.data.accessToken = accessToken;
                    }
                }
                catch (e) {
                    console.error('beforeCallFunction error', e);
                }
                return params;
            }), afterDSRequest: (cfg, error, result) => {
                if (!cfg.options)
                    return;
                if (cfg.options.showLoading)
                    app.hideLoading();
                if (!cfg.options.showToast)
                    return;
                const isSuccess = !error && result && !result.code;
                app.showToast({ title: '', icon: isSuccess ? 'success' : 'error' });
            }, afterCallFunction(params, error, res) {
                var _a, _b, _c, _d, _e, _f, _g;
                return __awaiter(this, void 0, void 0, function* () {
                    if (context.basic) {
                        return;
                    }
                    const oauthError = ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes('PERMISSION_DENIED')) ||
                        (error === null || error === void 0 ? void 0 : error.code) === 'unauthenticated' ||
                        (error === null || error === void 0 ? void 0 : error.error) === 'unauthenticated' ||
                        (error === null || error === void 0 ? void 0 : error.code) === 'invalid_grant' ||
                        (error === null || error === void 0 ? void 0 : error.error) === 'invalid_grant' ||
                        (error === null || error === void 0 ? void 0 : error.code) === 'INVALID_ACCESS_TOKEN' ||
                        ((error === null || error === void 0 ? void 0 : error.code) === 'OPERATION_FAIL' && /^\[INVALID_ACCESS_TOKEN\]/.test((error === null || error === void 0 ? void 0 : error.message) || ''));
                    if (((_c = (_b = params === null || params === void 0 ? void 0 : params.data) === null || _b === void 0 ? void 0 : _b.params) === null || _c === void 0 ? void 0 : _c.action) !== 'DescribeRuntimeResourceStrategy' &&
                        (['InnerError.AuthFailure', 'InvalidAccessToken'].includes((_d = res === null || res === void 0 ? void 0 : res.result) === null || _d === void 0 ? void 0 : _d.code) || oauthError)) {
                        const { loginConfigVersion } = app.__internal__.getConfig();
                        if ((_e = window === null || window === void 0 ? void 0 : window._WedaHostConfig) === null || _e === void 0 ? void 0 : _e.logout) {
                            dealCache({ key: 'RENDER_ACCESS', type: 'remove' });
                            app.showToast({
                                title: '接口无访问权限',
                                icon: 'error',
                            });
                            if (['InvalidAccessToken'].includes((_f = res === null || res === void 0 ? void 0 : res.result) === null || _f === void 0 ? void 0 : _f.code) || oauthError) {
                                setTimeout(() => {
                                    window._WedaHostConfig.logout();
                                }, 300);
                            }
                        }
                        else if (loginConfigVersion) {
                            const authConfig = yield getAuthConfig();
                            if (authConfig.RejectStrategy === 'to_login') {
                                if (['InnerError.AuthFailure'].includes((_g = res === null || res === void 0 ? void 0 : res.result) === null || _g === void 0 ? void 0 : _g.code)) {
                                    const isAnonymous = yield checkAnonymous();
                                    if (!isAnonymous)
                                        return;
                                    // 匿名用户越权去登录
                                }
                                redirectToLogin(generateLoginUrl);
                            }
                            else if (authConfig.RejectStrategy === 'show_warning') {
                                if (oauthError) {
                                    const isAnonymous = yield checkAnonymous();
                                    if (!isAnonymous) {
                                        redirectToLogin(generateLoginUrl);
                                        return;
                                    }
                                }
                                app.showToast({
                                    title: '接口无访问权限',
                                    icon: 'error',
                                });
                            }
                        }
                    }
                });
            } });
        setConfig(config);
        /**
         * debug 编辑器 无envId 需要跳过 tcb 初始化
         * 理想做法应该debug编辑器主动声明是不初始化资源的
         */
        if (!context.basic && config.envID) {
            initTcb();
        }
        else if (!context.checkPageAuth) {
            context.checkPageAuth = () => true;
        }
        applyLowcodes(cals);
        upsertFavicon((_c = cals === null || cals === void 0 ? void 0 : cals.extra) === null || _c === void 0 ? void 0 : _c.favicon, app, runtime.document);
        return () => {
            isMountRef.current = false;
            removeAppAPI === null || removeAppAPI === void 0 ? void 0 : removeAppAPI();
            cleanLowcodeContext();
            removeAppLifeCycle();
            // 变量先更新， 然后 create 先更新
            // 然后 remove 了
            // 然后 mount 了
            // 然是没有新 create， 这里先不清理了
            // removeHistory();
        };
    }, []);
    const FEATURE_MAP = React.useMemo(() => {
        return parseVersion(cals.schemaVersion, []);
    }, [cals.schemaVersion]);
    React.useEffect(() => {
        // const timeTag = `==========depen ${Date.now()}`;
        // console.time(timeTag);
        if (processedDependiencies.find((item) => !loadedDependienceMapRef.current[item.name])) {
            Promise.all([
                _loadDependencies(processedDependiencies),
                loadRuntimeDependencies(),
                loadMockDependencies(),
            ]).then(([dependenceMap = {}, runtimeDependenceMap = {}, mockDependencies = {}]) => __awaiter(void 0, void 0, void 0, function* () {
                var _a, _b;
                processedDependiencies.forEach((item) => {
                    loadedDependienceMapRef.current[item.name] = true;
                });
                function mergeDependencies(list) {
                    const keys = ['controlMap', 'componentsMap', 'componentActionsMap'];
                    return list.reduce((map, dependenceMap) => {
                        for (const key of keys) {
                            map[key] = Object.assign(Object.assign({}, map[key]), dependenceMap[key]);
                        }
                        return map;
                    }, {
                        controlMap: {},
                        componentsMap: {},
                        componentActionsMap: {},
                    });
                }
                const { enableObserverRef, enablePageRoot } = parseVersion(cals === null || cals === void 0 ? void 0 : cals.schemaVersion, processedDependiencies);
                setEnableObserverRef(enableObserverRef);
                setEnablePageRoot(enablePageRoot);
                const { controlMap, componentsMap, componentActionsMap } = mergeDependencies([
                    runtimeDependenceMap,
                    dependenceMap,
                    mockDependencies,
                ]);
                const componentsInfoMap = getComponentsInfo(processedDependiencies.map((item) => {
                    const control = controlMap[`${item.name}@${item.version}`];
                    let overwrite = {};
                    if (control) {
                        if (control.schemaVersion) {
                            overwrite.schemaVersion = control.schemaVersion;
                        }
                        if (control.components) {
                            overwrite.components = control.components;
                        }
                    }
                    return Object.assign(Object.assign({}, item), overwrite);
                }));
                const templateComponents = (yield Promise.all(((_b = (_a = cals.templates) === null || _a === void 0 ? void 0 : _a.map) === null || _b === void 0 ? void 0 : _b.call(_a, (item) => __awaiter(void 0, void 0, void 0, function* () {
                    var _c, _d;
                    try {
                        const sourceKey = `${APP_TEMPLATE_KEY}:${item.name}`;
                        const component = WrapComponentFieldWithPropsHook({
                            Field: yield generateCompositeComponent({
                                comp: item,
                                module: OFFICIAL_LIB_KEY,
                                componentsMap,
                                componentActionsMap,
                                componentsInfoMap,
                                options: {
                                    looseError: true,
                                    processCssUnit: (FEATURE_MAP.defaultDynamicCssUnit ? 'rem' : 'px'),
                                },
                            }),
                            isPlainProps: false,
                            sourceKey,
                        });
                        const componentInfo = {
                            name: item.name,
                            title: item.name,
                            compConfig: item.compConfig,
                            dataForm: item.dataForm || ((_c = item.data) === null || _c === void 0 ? void 0 : _c.properties) || {},
                            emitEvents: item.emitEvents ||
                                ((_d = item.events) === null || _d === void 0 ? void 0 : _d.map((item) => {
                                    return { eventName: item.name, name: item.title };
                                })),
                            isComposite: true,
                            /**
                             * default value
                             */
                            isContainer: false,
                            platform: [],
                            inputProps: undefined,
                            shortcut: undefined,
                            properties: undefined,
                        };
                        return { sourceKey, component, componentInfo };
                    }
                    catch (e) { }
                }))) || [])).filter((item) => !!item);
                templateComponents === null || templateComponents === void 0 ? void 0 : templateComponents.forEach(({ sourceKey, component, componentInfo }) => {
                    componentsMap[sourceKey] = component;
                    componentsInfoMap[sourceKey] = componentInfo;
                });
                setComponentsMap(componentsMap);
                setComponentActionsMap(componentActionsMap);
                setComponentsInfoMap(componentsInfoMap);
                // console.timeEnd(timeTag);
                setDependenciesLoaded(true);
            }));
        }
        else {
            setDependenciesLoaded(true);
            // if (!componentsMap) {
            //   setComponentsMap({});
            // }
            // if (!componentActionsMap) {
            //   setComponentActionsMap({});
            // }
            // if (!componentsInfoMap) {
            //   setComponentsInfoMap({});
            // }
        }
    }, [processedDependiencies]);
    const { options: pageOptions } = React.useMemo(() => {
        return {
            options: {
                looseError: context.looseError,
                reuseWidget: context.reuseWidget,
                processCssUnit: (FEATURE_MAP.defaultDynamicCssUnit ? 'rem' : 'px'),
            },
        };
    }, [context.$page, context.dataContext, context.onDataContextChange, context.looseError, context.reuseWidget]);
    const ratio = React.useMemo(() => {
        function flex() {
            try {
                let htmlDom = runtime.document.documentElement;
                let width = runtime.innerWidth || htmlDom.clientWidth;
                let fontSize = width / (375 / 14);
                if (width > 768 &&
                    !navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) {
                    return 2;
                    // htmlDom.style.setProperty(CALC_RPX_ROOT_VAL_NAME, '2');
                }
                else {
                    return 28 / fontSize;
                    // htmlDom.style.setProperty(CALC_RPX_ROOT_VAL_NAME, `${28 / fontSize}`);
                }
            }
            catch (e) {
                console.error(e);
            }
            return 2;
        }
        return flex();
        // runtime.addEventListener('resize', flex);
        // return () => {
        //   runtime.removeEventListener('resize', flex);
        // };
    }, []);
    return lowcodeLoaded && dependenciesLoaded && beforeAppLoadDone ? (lowcodeError ? (React.createElement(ErrorStatus, { error: lowcodeError })) : (React.createElement(React.Fragment, null,
        React.createElement("style", { type: "text/css", dangerouslySetInnerHTML: {
                __html: `body {
                ${CALC_RPX_ROOT_VAL_NAME}: ${ratio}
              }
              `,
            } }),
        React.createElement("style", { id: "wd-app-style-tag", type: "text/css", dangerouslySetInnerHTML: {
                __html: `${(((_d = lowcodeModuleMap.global) === null || _d === void 0 ? void 0 : _d.style) || []).map((item) => item.code).join('\n')}
              @media screen and (min-width: 768px) {
                body {
                  height: 100%;
                }
              }
              `,
            } }),
        React.createElement(InjectContext.Provider, { value: Object.assign(Object.assign({ processCssUnit: pageOptions.processCssUnit }, context), { componentsInfoMap }) },
            React.createElement(WedaRouter, { history: history, routes: cals.items.map((page, index) => {
                    var _a, _b, _c, _d;
                    let path = ((_a = cals.extra) === null || _a === void 0 ? void 0 : _a.rootPath) ? `/${(_b = cals.extra) === null || _b === void 0 ? void 0 : _b.rootPath}/${page.id}` : `/${page.id}`;
                    if (historyOption === null || historyOption === void 0 ? void 0 : historyOption._indexPage) {
                        path += '/';
                    }
                    return {
                        id: page.id,
                        isHome: !((_c = cals.extra) === null || _c === void 0 ? void 0 : _c.rootPath) && (cals.main ? page.id === cals.main : index === 0),
                        path,
                        root: ((_d = cals.extra) === null || _d === void 0 ? void 0 : _d.rootPath) || '',
                        render: () => {
                            return (React.createElement(PageRender, { page: page, generateComponentsMap: () => componentsMap, generateActionsMap: () => componentActionsMap, generateLowcodeModule: () => {
                                    return lowcodeModuleMap[page.id] || {};
                                }, generateContext: (ctx, page) => {
                                    const { widgets, componentSchema, dataBinds } = getComponentSchema(ctx, page, componentsInfoMap, undefined, {
                                        isComposite: false,
                                        looseError: pageOptions.looseError,
                                        processCssUnit: pageOptions.processCssUnit,
                                    });
                                    return {
                                        widgetContext: widgets,
                                        componentSchema,
                                        dataBinds,
                                    };
                                }, onMounted: onPageMounted, onRender: onRender, initDataContext: context === null || context === void 0 ? void 0 : context.defaultDataContext, options: pageOptions, renderLoading: renderLoading }));
                        },
                    };
                }), onNotFound: () => {
                    var _a, _b;
                    const 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({ message: '正在加载组件、编译代码...' }));
});
WedaAppContent.displayName = 'WedaAppContent';
const WedaApp = React.forwardRef((props, ref) => {
    const { ErrorBoundary = ReactErrorBoundary, cals } = props, restProps = __rest(props, ["ErrorBoundary", "cals"]);
    const resetErrorBoundaryRef = React.useRef(() => { });
    const errorRef = React.useRef(null);
    const debounceRestError = React.useCallback(debounce(() => {
        var _a;
        if (errorRef.current) {
            (_a = resetErrorBoundaryRef.current) === null || _a === void 0 ? void 0 : _a.call(resetErrorBoundaryRef);
        }
    }), []);
    React.useEffect(() => {
        debounceRestError();
    }, [cals]);
    return (React.createElement(ErrorBoundary, { FallbackComponent: ({ error, resetErrorBoundary }) => {
            errorRef.current = error;
            resetErrorBoundaryRef.current = React.useMemo(() => resetErrorBoundary, [resetErrorBoundary]);
            return React.createElement(ErrorStatus, { error: error });
        } },
        React.createElement(_WedaApp, Object.assign({ cals: cals }, restProps, { ref: ref }))));
});
WedaApp.displayName = 'WedaApp';
export default WedaApp;
export function WedaRouter({ history, routes = [], onNotFound, }) {
    // let [state, setState] = React.useState({
    //   action: history.action,
    //   location: history.location,
    // });
    // React.useLayoutEffect(() => history.listen(setState), [history]);
    const home = routes.find((route) => !!route.isHome);
    if (runtime.$$global) {
        runtime.$$global.homePageId = (home === null || home === void 0 ? void 0 : home.id) || '';
    }
    const context = React.useMemo(() => ({ attached: true }), []);
    return (React.createElement(OwnerComponentContext.Provider, { value: context },
        React.createElement(Router, { history: history },
            React.createElement(React.Suspense, { fallback: React.createElement(Loading, null) },
                React.createElement(Switch, null,
                    home && (React.createElement(Route, { path: `/${home.root || ''}`, exact: true, render: ({ location }) => {
                            return (React.createElement(Redirect, { to: Object.assign(Object.assign({}, location), { pathname: home.path }) }));
                        } })),
                    routes.map((route) => {
                        // 采用 render 的方式 企业工作台内路由会有两次变化
                        // 从而两次 render page 导致 widgets 引用异常
                        // __POWERED_BY_QIANKUN__
                        const Component = route.render;
                        const adminPortal = simpleCheckAdminPortal();
                        return (React.createElement(Route, { key: route.path, path: route.path, render: adminPortal ? undefined : Component }, adminPortal ? React.createElement(Component, null) : null));
                    }),
                    React.createElement(Route, null, ({ location }) => React.createElement(NotFound, { path: location === null || location === void 0 ? void 0 : location.pathname, onNotFound: onNotFound })))))));
}
function editProcess({ controlMap, componentsMap, dependencies }) {
    return __awaiter(this, void 0, void 0, function* () {
        const componentInfo = getComponentsInfo(dependencies.map((item) => {
            const control = controlMap[`${item.name}@${item.version}`];
            let overwrite = {};
            if (control) {
                if (control.schemaVersion) {
                    overwrite.schemaVersion = control.schemaVersion;
                }
                if (control.components) {
                    overwrite.components = control.components;
                }
            }
            return Object.assign(Object.assign({}, item), overwrite);
        }));
        return {
            controlMap,
            componentsMap: Object.entries(componentsMap).reduce((map, [sourceKey, Component]) => {
                map[sourceKey] = (props) => {
                    var _a, _b, _c;
                    const injectContext = React.useContext(InjectContext);
                    const { className = '' } = props, restProps = __rest(props, ["className"]);
                    const [module, componentName] = sourceKey.split(':');
                    const baseClassName = [];
                    const isContainer = (_a = componentInfo[sourceKey]) === null || _a === void 0 ? void 0 : _a.isContainer;
                    const isContainerEmptyChildren = isContainer && ((_b = props.children) === null || _b === void 0 ? void 0 : _b.length) === 0;
                    if (isContainer) {
                        baseClassName.push('_wa-comp-inst-container');
                    }
                    if (isContainerEmptyChildren) {
                        baseClassName.push('_wa-comp-container-empty-children');
                    }
                    return (React.createElement(Component, Object.assign({}, restProps, { className: classnames(props.className || '', {
                            '_wa-editor-selected-disable': ((_c = props.forIndexes) === null || _c === void 0 ? void 0 : _c[0]) > 0,
                            [`_wa-comp-id-${props.id}`]: true,
                            '_wa-comp-inst': true,
                            'weda-draggable': true,
                            _fe: true,
                            [`_wa-comp-name-${componentName}`]: true,
                            [`_sk-${sourceKey.replace(/:/, '__')}`]: true,
                            '_wa-comp-inst-container': isContainer,
                            '_wa-comp-container-empty-children': isContainerEmptyChildren,
                            '_wa-comp-selected': (injectContext === null || injectContext === void 0 ? void 0 : injectContext.selectedComponentSchemaPath) === props.id,
                        }) })));
                };
                return map;
            }, {}),
        };
    });
}
