import { __assign } from "tslib";
import sdk from '@tcwd/weapps-sdk/lib/app-h5-sdk';
import { createWebApp, _ACTIONS_KEY as ACTIONS_KEY, _ROUTER_KEY as ROUTER_KEY, } from '@cloudbase/weda-client';
import { runtime } from '../utils/adapter/index';
import { getEnumOptions } from '../utils/initGlobalVar';
import { get as lodashGet } from 'lodash-es';
var EPLATFORM;
(function (EPLATFORM) {
    EPLATFORM["WEB"] = "WEB";
    /**
     * 拼写错误
     * 兼容性无法修改
     */
    EPLATFORM["MINIPROGRAM"] = "MINIPROGRAME";
})(EPLATFORM || (EPLATFORM = {}));
export var subPackageName = '';
export var app = createGlboalApi();
export function registerApp(_app) {
    if (_app === void 0) { _app = createGlboalApi(); }
    _injectApp2Runtime(_app, true);
    app = _app;
}
mountAPIs(sdk);
function createGlboalApi(initData) {
    if (initData === void 0) { initData = {}; }
    var webApp = createWebApp(initData);
    var globalAPI = new Proxy(__assign(__assign({ id: initData.id || '', domain: initData.domain || '', state: {}, computed: {}, dataset: {}, common: {}, enumOptions: {} }, webApp), { utils: __assign(__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] : 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 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 (subPackageName) {
        globalAPI.mainApp = runtime["$app"];
        runtime["$$subapp_" + subPackageName] = globalAPI;
    }
    else {
        // 预览区调试栏可调试
        // 暴露给复合组件，代码组件来引用
        runtime['app'] = hard ? globalAPI : runtime['app'] || globalAPI;
        runtime["$app"] = runtime['app'];
    }
}
export function removeGlboalApi() {
    if (subPackageName) {
        runtime["$$subapp_" + subPackageName] = undefined;
    }
    else {
        runtime['app'] = undefined;
        runtime["$app"] = undefined;
    }
}
export function createPageApi() {
    var $page = new Proxy({
        state: {},
        computed: {},
        handler: {},
        props: {},
        widgets: {},
        dataset: {},
        setState: function (userSetState) {
            Object.keys(userSetState).forEach(function (keyPath) {
                var _a;
                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 = lodashGet($page.widgets, component);
            if (Array.isArray(widgetData)) {
                throw new Error("\u8C03\u7528\u65B9\u6CD5\u5931\u8D25\uFF1Aid\u4E3A" + 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" + component + "\u4E0B\u7684\u65B9\u6CD5" + method);
                }
                return widgetData._methods[method](params);
            }
        },
    }, {
        get: function (obj, prop) {
            return prop === '$page' ? obj : obj[prop];
        },
    });
    return $page;
}
// 分app 和 wx 挂载app
function mountAPIs(sdks) {
    Object.keys(sdks).forEach(function (item) {
        var action = sdks[item];
        if (!(item in ACTIONS_KEY) && !(item in ROUTER_KEY)) {
            app[item] = action;
        }
    });
    return app;
}
//# sourceMappingURL=global-api.js.map