"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WedaRouter = exports.InjectContext = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_router_dom_1 = require("react-router-dom");
const index_1 = tslib_1.__importDefault(require("../pages/index"));
const global_api_1 = require("../app/global-api");
const weda_client_1 = require("@cloudbase/weda-client");
const lowcode_1 = require("../utils/adapter/lowcode");
const generate_1 = require("../utils/adapter/generate");
const dependencies_1 = require("../utils/adapter/dependencies");
const index_2 = require("../utils/index");
const initGlobalVar_1 = require("../utils/initGlobalVar");
const lifecycle_1 = require("../utils/lifecycle");
const cals_1 = require("@cloudbase/cals");
const datasource_1 = require("../utils/adapter/datasource");
const adapter_1 = require("../utils/adapter");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const react_error_boundary_1 = require("react-error-boundary");
const qiankun_1 = require("qiankun");
require("./index.css");
const common_1 = require("../utils/common");
const hooks_1 = require("../utils/hooks");
const lodash_es_1 = require("lodash-es");
const comositeComponent_1 = require("../pages/comositeComponent");
const constants_1 = require("../utils/constants");
const { initTcb, setConfig, createStateDataSourceVar, generateParamsParser, EXTRA_API } = weda_client_1._WEDA_CLOUD_SDK;
const { getAccessToken } = weda_client_1.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'))))));
}
exports.InjectContext = React.createContext({});
function defaultloadDependencies(dependencies, cache) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        (0, dependencies_1.injectExternals)();
        return (0, dependencies_1.loadDependencies)({ dependencies }, { cache });
    });
}
const _WedaApp = React.forwardRef((props, ref) => {
    const { cals, loadExternalResources = dependencies_1.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 = (0, cals_1.getUsedComps)([cals], processedDependiencies);
    return processedDependiencies.filter((item) => item.name === cals_1.OFFICIAL_LIB_KEY || !!usedComponentMap[item.name]);
}, isHash = false, historyOption = {}, loadDependencies, loadDependiences, loadLowcodes = (cals) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const FEATURE_MAP = (0, cals_1.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([
        (0, lowcode_1.generateStyleModuleMap)(styleModulesMap),
        (0, lowcode_1.generateLowcodeModules)({
            codeModulesMap,
            runtimeWindow: adapter_1.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 = initGlobalVar_1.removeGlobalVar, getDatasourceConfig = datasource_1.getConfig, generateLoginUrl = index_2.defaultGenerateLoginUrl, } = context || {};
    /**
     * 在 page lifecycle 之前就创建 history 对象
     */
    const history = (0, hooks_1.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();
                (0, lowcode_1.cleanLowcodeContext)();
                (0, lifecycle_1.removeAppLifeCycle)();
                if (lowcodeModuleMap.global) {
                    (0, initGlobalVar_1.initGlobalVar)({
                        common: lowcodeModuleMap.global.common,
                        state: lowcodeModuleMap.global.state,
                        computedFuncs: lowcodeModuleMap.global.computed,
                    }, initAppAPI);
                    global_api_1.app.dataset.query = (0, generate_1.generateDatasetQuery)(((_a = cals.dataset) === null || _a === void 0 ? void 0 : _a.query) || {}, { $w: global_api_1.app.__internal__.$w, $app: global_api_1.app, $page: null }, { isComposite: false, useScopeWidgetData: true, looseError });
                    // 初始化应用生命周期
                    (0, lifecycle_1.initAppLifeCycle)(global_api_1.app, Object.assign(Object.assign({}, lowcodeModuleMap.global.lifecycle), { beforeCustomLaunch: (query) => tslib_1.__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: global_api_1.app, $page: {}, $w: (_b = global_api_1.app === null || global_api_1.app === void 0 ? void 0 : global_api_1.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 = global_api_1.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 = (0, common_1.simpleCheckAdminPortal)();
        if (!adminPortal) {
            (0, qiankun_1.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 ((0, common_1.isEnableWecom)(datasourceConfig.envID)) {
            (0, common_1.setEnableWecom)(true);
        }
        else {
            (0, common_1.setEnableWecom)(false);
        }
        // const time = `==========lowcode ${Date.now()}`;
        global_api_1.app.id = datasourceConfig.appID;
        global_api_1.app.domain = ((_a = cals.extra) === null || _a === void 0 ? void 0 : _a.domain) || '';
        global_api_1.app.label = global_api_1.app.label || (cals === null || cals === void 0 ? void 0 : cals.label);
        global_api_1.app.version = global_api_1.app.version || (cals === null || cals === void 0 ? void 0 : cals.version) || '';
        // 初始化系统变量
        const isMobile = (_b = global_api_1.app === null || global_api_1.app === void 0 ? void 0 : global_api_1.app.__internal__) === null || _b === void 0 ? void 0 : _b.isMobile;
        // 设备信息
        global_api_1.$w.device.viewport = {
            width: adapter_1.runtime.innerWidth,
            height: adapter_1.runtime.innerHeight,
        };
        if (isMobile === null || isMobile === void 0 ? void 0 : isMobile()) {
            global_api_1.$w.device.networkType = (0, common_1.getNetworkType)(adapter_1.runtime);
        }
        else {
            global_api_1.$w.device.networkType = '';
        }
        const { _deployType } = adapter_1.runtime;
        if (datasourceConfig.isPrivate && ['hybrid', 'hybrid-private'].includes(_deployType)) {
            global_api_1.app.domain = location.hostname;
        }
        global_api_1.app.__internal__.getConfig = () => {
            var _a;
            return {
                id: global_api_1.app.id,
                label: global_api_1.app.label,
                version: global_api_1.app.version,
                envId: datasourceConfig.envID,
                clientId: datasourceConfig.tcbClientId,
                loginConfigVersion: (_a = cals.extra) === null || _a === void 0 ? void 0 : _a.loginConfigVersion,
                staticResourceDomain: global_api_1.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;
                global_api_1.app.showLoading({});
            }, beforeCallFunction: (params) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
                var _d, _e, _f;
                if (context.basic) {
                    return params;
                }
                try {
                    const { loginConfigVersion } = global_api_1.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)
                    global_api_1.app.hideLoading();
                if (!cfg.options.showToast)
                    return;
                const isSuccess = !error && result && !result.code;
                global_api_1.app.showToast({ title: '', icon: isSuccess ? 'success' : 'error' });
            }, afterCallFunction(params, error, res) {
                var _a, _b, _c, _d, _e, _f, _g;
                return tslib_1.__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 } = global_api_1.app.__internal__.getConfig();
                        if ((_e = window === null || window === void 0 ? void 0 : window._WedaHostConfig) === null || _e === void 0 ? void 0 : _e.logout) {
                            (0, index_2.dealCache)({ key: 'RENDER_ACCESS', type: 'remove' });
                            global_api_1.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 (0, index_2.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 (0, index_2.checkAnonymous)();
                                    if (!isAnonymous)
                                        return;
                                    // 匿名用户越权去登录
                                }
                                (0, index_2.redirectToLogin)(generateLoginUrl);
                            }
                            else if (authConfig.RejectStrategy === 'show_warning') {
                                if (oauthError) {
                                    const isAnonymous = yield (0, index_2.checkAnonymous)();
                                    if (!isAnonymous) {
                                        (0, index_2.redirectToLogin)(generateLoginUrl);
                                        return;
                                    }
                                }
                                global_api_1.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);
        (0, dependencies_1.upsertFavicon)((_c = cals === null || cals === void 0 ? void 0 : cals.extra) === null || _c === void 0 ? void 0 : _c.favicon, global_api_1.app, adapter_1.runtime.document);
        return () => {
            isMountRef.current = false;
            removeAppAPI === null || removeAppAPI === void 0 ? void 0 : removeAppAPI();
            (0, lowcode_1.cleanLowcodeContext)();
            (0, lifecycle_1.removeAppLifeCycle)();
            // 变量先更新， 然后 create 先更新
            // 然后 remove 了
            // 然后 mount 了
            // 然是没有新 create， 这里先不清理了
            // removeHistory();
        };
    }, []);
    const FEATURE_MAP = React.useMemo(() => {
        return (0, cals_1.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),
                (0, dependencies_1.loadRuntimeDependencies)(),
                (0, dependencies_1.loadMockDependencies)(),
            ]).then(([dependenceMap = {}, runtimeDependenceMap = {}, mockDependencies = {}]) => tslib_1.__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 } = (0, cals_1.parseVersion)(cals === null || cals === void 0 ? void 0 : cals.schemaVersion, processedDependiencies);
                (0, common_1.setEnableObserverRef)(enableObserverRef);
                (0, common_1.setEnablePageRoot)(enablePageRoot);
                const { controlMap, componentsMap, componentActionsMap } = mergeDependencies([
                    runtimeDependenceMap,
                    dependenceMap,
                    mockDependencies,
                ]);
                const componentsInfoMap = (0, generate_1.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) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
                    var _c, _d;
                    try {
                        const sourceKey = `${constants_1.APP_TEMPLATE_KEY}:${item.name}`;
                        const component = (0, dependencies_1.WrapComponentFieldWithPropsHook)({
                            Field: yield (0, comositeComponent_1.generateCompositeComponent)({
                                comp: item,
                                module: cals_1.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 = adapter_1.runtime.document.documentElement;
                let width = adapter_1.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 {
                ${index_2.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(exports.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(index_1.default, { page: page, generateComponentsMap: () => componentsMap, generateActionsMap: () => componentActionsMap, generateLowcodeModule: () => {
                                    return lowcodeModuleMap[page.id] || {};
                                }, generateContext: (ctx, page) => {
                                    const { widgets, componentSchema, dataBinds } = (0, generate_1.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 = react_error_boundary_1.ErrorBoundary, cals } = props, restProps = tslib_1.__rest(props, ["ErrorBoundary", "cals"]);
    const resetErrorBoundaryRef = React.useRef(() => { });
    const errorRef = React.useRef(null);
    const debounceRestError = React.useCallback((0, lodash_es_1.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';
exports.default = WedaApp;
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 (adapter_1.runtime.$$global) {
        adapter_1.runtime.$$global.homePageId = (home === null || home === void 0 ? void 0 : home.id) || '';
    }
    const context = React.useMemo(() => ({ attached: true }), []);
    return (React.createElement(hooks_1.OwnerComponentContext.Provider, { value: context },
        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: `/${home.root || ''}`, exact: true, render: ({ location }) => {
                            return (React.createElement(react_router_dom_1.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 = (0, common_1.simpleCheckAdminPortal)();
                        return (React.createElement(react_router_dom_1.Route, { key: route.path, path: route.path, render: adminPortal ? undefined : Component }, adminPortal ? React.createElement(Component, null) : null));
                    }),
                    React.createElement(react_router_dom_1.Route, null, ({ location }) => React.createElement(NotFound, { path: location === null || location === void 0 ? void 0 : location.pathname, onNotFound: onNotFound })))))));
}
exports.WedaRouter = WedaRouter;
function editProcess({ controlMap, componentsMap, dependencies }) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const componentInfo = (0, generate_1.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(exports.InjectContext);
                    const { className = '' } = props, restProps = tslib_1.__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: (0, classnames_1.default)(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;
            }, {}),
        };
    });
}
//# sourceMappingURL=index.js.map