"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCompApi = exports.createPageApi = exports.removeGlboalApi = exports.registerApp = exports.$w = exports.app = exports.subPackageName = void 0;
const tslib_1 = require("tslib");
const app_h5_sdk_1 = tslib_1.__importDefault(require("@tcwd/weapps-sdk/lib/app-h5-sdk"));
const weda_client_1 = require("@cloudbase/weda-client");
const index_1 = require("../utils/adapter/index");
const initGlobalVar_1 = require("../utils/initGlobalVar");
const lodash_es_1 = require("lodash-es");
const cals_1 = require("@cloudbase/cals");
const mobx_1 = require("mobx");
const utils_1 = require("../utils");
const querystring = tslib_1.__importStar(require("query-string"));
// enum EPLATFORM {
//   WEB = 'WEB',
//   /**
//    * 拼写错误
//    * 兼容性无法修改
//    */
//   MINIPROGRAM = 'MINIPROGRAME',
// }
const DEFAULT_INIT_DATA = {
    processAction: (key, action) => {
        switch (key) {
            case weda_client_1._ACTIONS_KEY.showModal: {
                return function (obj) {
                    var _a, _b, _c;
                    const showModal = (_b = (_a = index_1.runtime[`@weapps-materials-main-${cals_1.OFFICIAL_LIB_KEY}`]) === null || _a === void 0 ? void 0 : _a.actions) === null || _b === void 0 ? void 0 : _b.showModal;
                    const isMobile = (_c = exports.app === null || exports.app === void 0 ? void 0 : exports.app.__internal__) === null || _c === void 0 ? void 0 : _c.isMobile;
                    if (isMobile && !isMobile() && showModal) {
                        return showModal({ data: obj, _origin: action });
                    }
                    return action(obj);
                };
            }
            case weda_client_1._ACTIONS_KEY.showToast: {
                return function (obj) {
                    var _a, _b;
                    const showMessage = (_b = (_a = index_1.runtime[`@weapps-materials-main-${cals_1.OFFICIAL_LIB_KEY}`]) === null || _a === void 0 ? void 0 : _a.actions) === null || _b === void 0 ? void 0 : _b.showMessage;
                    if (showMessage) {
                        return showMessage({ data: obj, _origin: action });
                    }
                    return action(obj);
                };
            }
        }
        return action;
    },
};
exports.subPackageName = '';
exports.app = createGlboalApi(DEFAULT_INIT_DATA);
exports.$w = new Proxy(exports.app.__internal__.$w, {
    get(_, prop) {
        var _a;
        if (prop === '$app' || prop === 'app') {
            return exports.app;
        }
        return (_a = exports.app.__internal__.$w) === null || _a === void 0 ? void 0 : _a[prop];
    },
});
function registerApp(_app = createGlboalApi(DEFAULT_INIT_DATA)) {
    _injectApp2Runtime(_app, true);
    exports.app = _app;
}
exports.registerApp = registerApp;
mountAPIs(app_h5_sdk_1.default);
function createGlboalApi(initData = {}) {
    const webApp = (0, weda_client_1.createWebApp)(initData);
    const globalAPI = new Proxy(Object.assign(webApp, Object.assign(Object.assign({ domain: initData.domain || '', state: {}, computed: {}, dataset: {}, common: {}, enumOptions: {} }, webApp), { utils: Object.assign(Object.assign({}, webApp.utils), { formatEnum: (path, optionname, app) => {
                var _a, _b, _c;
                let isSingle = Array.isArray(path);
                // 这个app是后来添加进去的
                let options = app === null || app === void 0 ? void 0 : app.enumOptions;
                let parseOptions = options[optionname] ? options[optionname] : (0, initGlobalVar_1.getEnumOptions)(optionname);
                if (parseOptions === '') {
                    return !isSingle ? path : path.join(',');
                }
                let multiTmp = [];
                let value = !isSingle
                    ? (_b = (_a = JSON.parse(parseOptions)) === null || _a === void 0 ? void 0 : _a.find((item) => item.key === path)) === null || _b === void 0 ? void 0 : _b.value
                    : (_c = JSON.parse(parseOptions)) === null || _c === void 0 ? void 0 : _c.filter((item) => path.some((pathValue) => item.key === pathValue)).map((item) => multiTmp.push(item.value));
                return !isSingle ? value : multiTmp.join(',');
            } }), 
        /**
         * setState
         */
        setState: (userSetState) => {
            Object.keys(userSetState).forEach((keyPath) => {
                globalAPI.utils.set(globalAPI.dataset.state, keyPath, userSetState[keyPath]);
            });
        }, 
        /**
         * @deprecated
         */
        invoke(params) {
            const $page = globalAPI.utils.getCurrentPage();
            return $page.invokeComponentMethod(params);
        } })), {
        get: (obj, prop) => {
            if (prop === 'app' || prop === '$app') {
                return exports.app;
            }
            else {
                return obj[prop];
            }
        },
        // set: (obj, prop, value) => {
        //   if (prop === 'app' || prop === '$app') {
        //     console.warn('$app 对象中 app/$app 为只读');
        //     return false;
        //   } else {
        //     // 修改 obj
        //     return true;
        //   }
        // },
    });
    _injectApp2Runtime(globalAPI);
    return globalAPI;
}
function _injectApp2Runtime(globalAPI, hard = false) {
    var _a;
    // 给全局挂上 mainApp/subApp
    // The global api exposed to lowcode
    if (exports.subPackageName) {
        globalAPI.mainApp = index_1.runtime.$app;
        index_1.runtime[`$$subapp_${exports.subPackageName}`] = globalAPI;
    }
    else {
        // 预览区调试栏可调试
        // 暴露给复合组件，代码组件来引用
        index_1.runtime.app = hard ? globalAPI : index_1.runtime.app || globalAPI;
        index_1.runtime.$app = new Proxy(index_1.runtime.app, {
            get(obj, prop) {
                return obj ? obj[prop] : undefined;
            },
            set(obj, prop, value) {
                if (obj) {
                    return (obj[prop] = value);
                }
                else {
                    return undefined;
                }
            },
        });
        index_1.runtime.$w = new Proxy(exports.$w || ((_a = globalAPI === null || globalAPI === void 0 ? void 0 : globalAPI.__internal__) === null || _a === void 0 ? void 0 : _a.$w) || {}, {
            get(_, prop) {
                var _a, _b, _c, _d, _e, _f;
                const $page = ((_b = (_a = index_1.runtime.app) === null || _a === void 0 ? void 0 : _a.__internal__) === null || _b === void 0 ? void 0 : _b.activePage) || index_1.runtime.$page;
                if ((_d = (_c = $page === null || $page === void 0 ? void 0 : $page.__internal__) === null || _c === void 0 ? void 0 : _c.$w) === null || _d === void 0 ? void 0 : _d[prop]) {
                    return (_f = (_e = $page === null || $page === void 0 ? void 0 : $page.__internal__) === null || _e === void 0 ? void 0 : _e.$w) === null || _f === void 0 ? void 0 : _f[prop];
                }
                if (_[prop]) {
                    return _[prop];
                }
                return null;
            },
        });
    }
}
function removeGlboalApi() {
    if (exports.subPackageName) {
        index_1.runtime[`$$subapp_${exports.subPackageName}`] = undefined;
    }
    else {
        index_1.runtime.app = undefined;
        index_1.runtime.$app = undefined;
    }
}
exports.removeGlboalApi = removeGlboalApi;
function createPageApi() {
    const $page = new Proxy({
        __internal__: {
            active: false,
        },
        state: {},
        computed: {},
        handler: {},
        widgets: (0, mobx_1.observable)({}),
        dataset: {},
        setState: (userSetState) => {
            Object.keys(userSetState).forEach((keyPath) => {
                var _a;
                exports.app.utils.set((_a = $page.dataset) === null || _a === void 0 ? void 0 : _a.state, keyPath, userSetState[keyPath]);
            });
        },
        setParams: (_params) => {
            var _a;
            const params = Array.isArray(_params)
                ? _params.reduce((map, meta) => {
                    var _a, _b, _c;
                    let { key, value } = meta;
                    if ((_a = key === null || key === void 0 ? void 0 : key.startsWith) === null || _a === void 0 ? void 0 : _a.call(key, '$page.')) {
                        key = key.replace(/^\$page\./, '');
                    }
                    if ((_b = key === null || key === void 0 ? void 0 : key.trim) === null || _b === void 0 ? void 0 : _b.call(key)) {
                        map[(_c = key === null || key === void 0 ? void 0 : key.trim) === null || _c === void 0 ? void 0 : _c.call(key)] = value;
                    }
                    return map;
                }, {})
                : _params;
            Object.keys(params).forEach((keyPath) => {
                var _a;
                exports.app.utils.set((_a = $page.dataset) === null || _a === void 0 ? void 0 : _a.params, keyPath, params[keyPath]);
            });
            let queryObj;
            try {
                queryObj =
                    querystring.parse((index_1.runtime._WEAPPS_HISTORY.location.search || '').split('?')[1] || '') || {};
            }
            catch (e) {
                queryObj = Object.assign({}, (_a = $page.dataset) === null || _a === void 0 ? void 0 : _a.params);
            }
            Object.keys(params)
                .map((keyPath) => {
                const matched = keyPath.match(/(^.*?)[.[]/);
                if (matched) {
                    return matched[0];
                }
                return keyPath;
            })
                .forEach((key) => {
                var _a, _b;
                queryObj[key] = (_b = (_a = $page.dataset) === null || _a === void 0 ? void 0 : _a.params) === null || _b === void 0 ? void 0 : _b[key];
            });
            exports.app.redirectTo({
                pageId: $page.id,
                params: queryObj,
            });
        },
        _dataBinds: {},
        invokeComponentMethod({ component, method, params }) {
            var _a;
            let userWidget;
            if (typeof component === 'string') {
                const widgetData = (0, lodash_es_1.get)($page.widgets, component);
                if (Array.isArray(widgetData)) {
                    throw new Error(`调用方法失败：id为${component}的组件拥有多个实例`);
                }
                userWidget = widgetData === null || widgetData === void 0 ? void 0 : widgetData._userWidget;
            }
            else {
                userWidget = component;
            }
            const action = (_a = userWidget === null || userWidget === void 0 ? void 0 : userWidget.custom) === null || _a === void 0 ? void 0 : _a[method];
            if (typeof action !== 'function') {
                throw new Error(`调用方法失败：未找到id为${userWidget === null || userWidget === void 0 ? void 0 : userWidget.sys.id}下的方法${method}`);
            }
            return action(params);
        },
    }, {
        get(obj, prop) {
            return prop === '$page' ? obj : obj[prop];
        },
    });
    return $page;
}
exports.createPageApi = createPageApi;
// 分app 和 wx 挂载app
function mountAPIs(sdks) {
    Object.keys(sdks).forEach((item) => {
        let action = sdks[item];
        if (!(item in weda_client_1._ACTIONS_KEY) && !(item in weda_client_1._ROUTER_KEY)) {
            exports.app[item] = action;
        }
    });
    return exports.app;
}
function createCompApi({ id, ref, state = (0, mobx_1.observable)({}), computed = {}, _dataBinds = {}, compConfig = {}, widgets = {}, node, events, props, handler = {}, propsData, }) {
    const $comp = new Proxy({
        id,
        __internal__: {
            $w: new Proxy({}, {
                get(_, prop) {
                    var _a, _b, _c;
                    // 尝试代理页面级别组件实例
                    let pageWidget = (_a = $comp.widgets) === null || _a === void 0 ? void 0 : _a[prop];
                    if (pageWidget) {
                        return pageWidget._userWidget;
                    }
                    return (_c = (_b = exports.app === null || exports.app === void 0 ? void 0 : exports.app.__internal__) === null || _b === void 0 ? void 0 : _b.$w) === null || _c === void 0 ? void 0 : _c[prop];
                },
            }),
        },
        _dataBinds,
        compConfig,
        widgets,
        node,
        // lib: { const: constObj, tools: toolsObj },
        get props() {
            const _a = props || {}, { forwardRef } = _a, restProps = tslib_1.__rest(_a, ["forwardRef"]);
            return Object.assign(Object.assign({}, restProps), { events, data: propsData });
        },
        get state() {
            return state;
        },
        computed: {},
        get _instanceRef() {
            return ref;
        },
        get methods() {
            var _a;
            return (_a = ref.current) === null || _a === void 0 ? void 0 : _a.methods;
        },
        set methods(value) {
            if (!ref.current) {
                ref.current = {};
            }
            ref.current.methods = value;
        },
    }, {
        get: (obj, prop) => {
            return prop === '$WEAPPS_COMP' || prop === '$comp' ? obj : obj[prop];
        },
    });
    return Object.assign($comp, {
        computed: (0, utils_1.createComputed)(computed, $comp),
        handler: (0, utils_1.bindFuncObj)(handler || {}, $comp),
    });
}
exports.createCompApi = createCompApi;
//# sourceMappingURL=global-api.js.map