"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPageApi = exports.removeGlboalApi = exports.registerApp = exports.app = exports.subPackageName = exports.OFFICIAL_LIB_KEY = void 0;
var tslib_1 = require("tslib");
var app_h5_sdk_1 = tslib_1.__importDefault(require("@tcwd/weapps-sdk/lib/app-h5-sdk"));
var weda_client_1 = require("@cloudbase/weda-client");
var index_1 = require("../utils/adapter/index");
var initGlobalVar_1 = require("../utils/initGlobalVar");
var lodash_es_1 = require("lodash-es");
exports.OFFICIAL_LIB_KEY = 'gsd-h5-react';
var EPLATFORM;
(function (EPLATFORM) {
    EPLATFORM["WEB"] = "WEB";
    /**
     * 拼写错误
     * 兼容性无法修改
     */
    EPLATFORM["MINIPROGRAM"] = "MINIPROGRAME";
})(EPLATFORM || (EPLATFORM = {}));
var DEFAULT_INIT_DATA = {
    processAction: function (key, action) {
        switch (key) {
            case weda_client_1._ACTIONS_KEY.showModal: {
                return function (obj) {
                    var _a, _b, _c;
                    var showModal = (_b = (_a = index_1.runtime["@weapps-materials-main-".concat(exports.OFFICIAL_LIB_KEY)]) === null || _a === void 0 ? void 0 : _a.actions) === null || _b === void 0 ? void 0 : _b.showModal;
                    var 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 });
                    }
                    return action(obj);
                };
            }
        }
        return action;
    },
};
exports.subPackageName = '';
exports.app = createGlboalApi(DEFAULT_INIT_DATA);
function registerApp(_app) {
    if (_app === void 0) { _app = createGlboalApi(DEFAULT_INIT_DATA); }
    _injectApp2Runtime(_app, true);
    exports.app = _app;
}
exports.registerApp = registerApp;
mountAPIs(app_h5_sdk_1.default);
function createGlboalApi(initData) {
    if (initData === void 0) { initData = {}; }
    var webApp = (0, weda_client_1.createWebApp)(initData);
    var globalAPI = new Proxy(tslib_1.__assign(tslib_1.__assign({ id: initData.id || '', domain: initData.domain || '', state: {}, computed: {}, dataset: {}, common: {}, enumOptions: {} }, webApp), { utils: tslib_1.__assign(tslib_1.__assign({}, webApp.utils), { formatEnum: function (path, optionname, app) {
                var _a, _b, _c;
                var isSingle = Array.isArray(path);
                // 这个app是后来添加进去的
                var options = app === null || app === void 0 ? void 0 : app.enumOptions;
                var parseOptions = options[optionname] ? options[optionname] : (0, initGlobalVar_1.getEnumOptions)(optionname);
                if (parseOptions === '') {
                    return !isSingle ? path : path.join(',');
                }
                var multiTmp = [];
                var value = !isSingle
                    ? (_b = (_a = JSON.parse(parseOptions)) === null || _a === void 0 ? void 0 : _a.find(function (item) { return item.key === path; })) === null || _b === void 0 ? void 0 : _b.value
                    : (_c = JSON.parse(parseOptions)) === null || _c === void 0 ? void 0 : _c.filter(function (item) { return path.some(function (pathValue) { return item.key === pathValue; }); }).map(function (item) { return multiTmp.push(item.value); });
                return !isSingle ? value : multiTmp.join(',');
            } }), 
        /**
         * setState
         */
        setState: function (userSetState) {
            Object.keys(userSetState).forEach(function (keyPath) {
                globalAPI.utils.set(globalAPI.dataset.state, keyPath, userSetState[keyPath]);
            });
        }, invoke: function (params) {
            var $page = globalAPI.utils.getCurrentPage();
            return $page.invokeComponentMethod(params);
        } }), {
        get: function (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) {
    if (hard === void 0) { hard = false; }
    // 给全局挂上 mainApp/subApp
    // The global api exposed to lowcode
    if (exports.subPackageName) {
        globalAPI.mainApp = index_1.runtime["$app"];
        index_1.runtime["$$subapp_".concat(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: function (obj, prop) {
                return index_1.runtime['app'] ? index_1.runtime['app'][prop] : undefined;
            },
            set: function (obj, prop, value) {
                if (index_1.runtime['app']) {
                    return (index_1.runtime['app'][prop] = value);
                }
                else {
                    return undefined;
                }
            },
        });
    }
}
function removeGlboalApi() {
    if (exports.subPackageName) {
        index_1.runtime["$$subapp_".concat(exports.subPackageName)] = undefined;
    }
    else {
        index_1.runtime['app'] = undefined;
        index_1.runtime["$app"] = undefined;
    }
}
exports.removeGlboalApi = removeGlboalApi;
function createPageApi() {
    var $page = new Proxy({
        state: {},
        computed: {},
        handler: {},
        props: {},
        widgets: {},
        dataset: {},
        setState: function (userSetState) {
            Object.keys(userSetState).forEach(function (keyPath) {
                var _a;
                exports.app.utils.set((_a = $page.dataset) === null || _a === void 0 ? void 0 : _a.state, keyPath, userSetState[keyPath]);
            });
        },
        _dataBinds: {},
        invokeComponentMethod: function (_a) {
            var component = _a.component, method = _a.method, params = _a.params;
            var widgetData = (0, lodash_es_1.get)($page.widgets, component);
            if (Array.isArray(widgetData)) {
                throw new Error("\u8C03\u7528\u65B9\u6CD5\u5931\u8D25\uFF1Aid\u4E3A".concat(component, "\u7684\u7EC4\u4EF6\u62E5\u6709\u591A\u4E2A\u5B9E\u4F8B"));
                // widgetData.forEach(widget => {
                //   if(!widget._methods[method]) {
                //     throw new Error('NOT_FOUND')
                //   } else {
                //     actions.push(widget._methods[method])
                //   }
                // })
            }
            else {
                if (!widgetData._methods[method] || typeof widgetData._methods[method] != 'function') {
                    throw new Error("\u8C03\u7528\u65B9\u6CD5\u5931\u8D25\uFF1A\u672A\u627E\u5230id\u4E3A".concat(component, "\u4E0B\u7684\u65B9\u6CD5").concat(method));
                }
                return widgetData._methods[method](params);
            }
        },
    }, {
        get: function (obj, prop) {
            return prop === '$page' ? obj : obj[prop];
        },
    });
    return $page;
}
exports.createPageApi = createPageApi;
// 分app 和 wx 挂载app
function mountAPIs(sdks) {
    Object.keys(sdks).forEach(function (item) {
        var 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;
}
//# sourceMappingURL=global-api.js.map