"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = (0, tslib_1.__importStar)(require("react"));
var mobx_react_lite_1 = require("mobx-react-lite");
var mobx_1 = require("mobx");
var RenderWrapper_1 = require("/src/handlers/RenderWrapper");
var index_1 = require("/src/utils/index");
var state_js_1 = (0, tslib_1.__importDefault)(require("./lowcode/state.js"));
var computed_js_1 = (0, tslib_1.__importDefault)(require("./lowcode/computed.js"));
var lifecycle_js_1 = (0, tslib_1.__importDefault)(require("./lowcode/lifecycle.js"));
// import i18n from '@tcwd/weapps-sdk/lib/i18n'
var index_2 = (0, tslib_1.__importDefault)(require("./lowcode/index"));
var lodash_es_1 = require("lodash-es");
var getTabbarStyle_js_1 = (0, tslib_1.__importDefault)(require("./lowcode/handler/getTabbarStyle.js"));
var onTabItemClick_js_1 = (0, tslib_1.__importDefault)(require("./lowcode/handler/onTabItemClick.js"));
// Import Components outof sandbox
var components_1 = require("/src/libraries/gsd-h5-react@0.0.70/web/components");
var Icon_1 = (0, tslib_1.__importDefault)(require("/src/libraries/CLOUDBASE_STANDARD@1634202837896/components/Icon"));
var TabBarItem_1 = (0, tslib_1.__importDefault)(require("/src/libraries/CLOUDBASE_STANDARD@1634202837896/components/TabBarItem"));
var constObj = (0, tslib_1.__importStar)(require("../../libCommonRes/const"));
var toolsObj = (0, tslib_1.__importStar)(require("../../libCommonRes/tools"));
require("./lowcode/style.css");
var libCode = 'CLOUDBASE_STANDARD';
var CompositeCompWrapper = /** @class */ (function (_super) {
    (0, tslib_1.__extends)(CompositeCompWrapper, _super);
    function CompositeCompWrapper(props) {
        var _this_1 = _super.call(this, props) || this;
        _this_1.$WEAPPS_COMP = {};
        _this_1.compConfig = {};
        // Import Components in sandbox
        _this_1.virtualFields = Object.assign({}, props.pageVirtualFields || {}, {
            'gsd-h5-react:Slot': function (props) { return (React.createElement(components_1.Slot, (0, tslib_1.__assign)({}, (0, index_1.resolveComponentProps)(props, 1)))); },
            'CLOUDBASE_STANDARD:Icon': function (props) { return (React.createElement(Icon_1.default, (0, tslib_1.__assign)({}, (0, index_1.resolveComponentProps)(props, 0)))); },
            'CLOUDBASE_STANDARD:TabBarItem': function (props) { return (React.createElement(TabBarItem_1.default, (0, tslib_1.__assign)({}, (0, index_1.resolveComponentProps)(props, 0)))); },
            'gsd-h5-react:Container': function (props) { return (React.createElement(components_1.Container, (0, tslib_1.__assign)({}, (0, index_1.resolveComponentProps)(props, 1)))); },
        });
        // 挂载给到 $comp.props.events 使用
        _this_1.events = ['change'].reduce(function (obj, trigger) {
            obj[trigger] = function (eventData, domEvent) {
                _this_1.props.emit(trigger, eventData, domEvent);
                _this_1.node._listeners &&
                    _this_1.node._listeners.emit(trigger, eventData, domEvent);
            };
            return obj;
        }, {});
        _this_1.handler = _this_1.$WEAPPS_COMP.handler = {
            getTabbarStyle: getTabbarStyle_js_1.default.bind(_this_1),
            onTabItemClick: onTabItemClick_js_1.default.bind(_this_1),
        };
        var widgetContext = {
            id3: {
                name: 'tabbar',
                _visible: true,
                style: {},
                classList: [],
                widgetType: 'gsd-h5-react:Slot',
                _parentId: 'id2',
            },
            id5: {
                name: 'success',
                _visible: true,
                style: {},
                classList: [],
                widgetType: 'CLOUDBASE_STANDARD:Icon',
                _parentId: 'id4',
            },
            id4: {
                circle: false,
                textSize: 24,
                underline: false,
                activeIcon: '',
                circleSize: 100,
                costomIcon: '',
                style: {},
                classList: [],
                widgetType: 'CLOUDBASE_STANDARD:TabBarItem',
                _parentId: 'id2',
            },
            id2: {
                title: '',
                _visible: true,
                style: {},
                classList: ['lcap-tabbar', 'wa-comp-CLOUDBASE_STANDARD-TabBar'],
                widgetType: 'gsd-h5-react:Container',
            },
        };
        var dataBinds = (_this_1._dataBinds = {
            id5: {
                src: function (forItems) { return forItems.id4.activeIcon; },
                size: function () { return _this_1.$WEAPPS_COMP.props.data.iconSize; },
                color: function (forItems) {
                    var $for = forItems;
                    return _this_1.$WEAPPS_COMP.props.data.value === forItems.id4.name
                        ? _this_1.$WEAPPS_COMP.props.data.activeColor
                        : _this_1.$WEAPPS_COMP.props.data.color;
                },
            },
            id4: {
                icon: function (forItems) {
                    var $for = forItems;
                    return forItems.id4.name === _this_1.$WEAPPS_COMP.props.data.value
                        ? ''
                        : forItems.id4.icon;
                },
                name: function (forItems) { return forItems.id4.name; },
                color: function () { return _this_1.$WEAPPS_COMP.props.data.color; },
                title: function (forItems) { return forItems.id4.title; },
                actived: function (forItems) {
                    var $for = forItems;
                    return forItems.id4.name === _this_1.$WEAPPS_COMP.props.data.value;
                },
                activeColor: function () { return _this_1.$WEAPPS_COMP.props.data.activeColor; },
                childIconSize: function () { return _this_1.$WEAPPS_COMP.props.data.iconSize; },
                _waFor: function () { return _this_1.$WEAPPS_COMP.props.data.tabs; },
                classList: function () { return _this_1.$WEAPPS_COMP.props.data.tabs; },
            },
            id2: {
                style: function (forItems) {
                    var $for = forItems;
                    return _this_1.$WEAPPS_COMP.handler.getTabbarStyle();
                },
                classList: function () { return _this_1.$WEAPPS_COMP.props.data.position; },
            },
        });
        _this_1.componentSchema = {
            type: 'object',
            properties: {
                id2: {
                    key: 'id2',
                    'x-component': 'gsd-h5-react:container',
                    'x-props': {
                        sourceKey: 'gsd-h5-react:Container',
                        customDataForm: {},
                        staticResourceAttribute: [],
                        classNameList: ['lcap-tabbar', 'wa-comp-CLOUDBASE_STANDARD-TabBar'],
                    },
                    'x-index': 1,
                    emitEvents: [
                        'tap',
                        'longpress',
                        'touchstart',
                        'touchmove',
                        'touchcancel',
                        'touchend',
                    ],
                    properties: {
                        id3: {
                            key: 'id3',
                            'x-component': 'gsd-h5-react:slot',
                            'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                            },
                            'x-index': 0,
                        },
                        id4: {
                            key: 'id4',
                            'x-component': 'cloudbase_standard:tabbaritem',
                            'x-props': {
                                sourceKey: 'CLOUDBASE_STANDARD:TabBarItem',
                                customDataForm: {},
                                staticResourceAttribute: [],
                                listenerInstances: [
                                    {
                                        key: '',
                                        trigger: 'click',
                                        instanceFunction: _this_1.handler.onTabItemClick.bind(_this_1),
                                        dataBinds: {
                                            target: function (forItems) { return forItems.id4.name; },
                                        },
                                    },
                                ],
                            },
                            'x-index': 2,
                            emitEvents: ['click'],
                            properties: {
                                activeIcon: {
                                    key: 'activeIcon',
                                    properties: {
                                        id5: {
                                            key: 'id5',
                                            'x-component': 'cloudbase_standard:icon',
                                            'x-props': {
                                                sourceKey: 'CLOUDBASE_STANDARD:Icon',
                                                customDataForm: {},
                                                staticResourceAttribute: [],
                                            },
                                            'x-index': 1,
                                            emitEvents: [],
                                        },
                                    },
                                },
                                costomIcon: {
                                    key: 'costomIcon',
                                },
                            },
                        },
                    },
                },
            },
        };
        var defaultProps = {
            tabs: [
                {
                    icon: 'https://imgcache.qq.com/qcloud/tcloud_dtc/static/low_code/c868cd77-8454-46d5-bd13-54539707e9f2.svg',
                    name: 'value1',
                    title: '标题1',
                    activeIcon: 'https://imgcache.qq.com/qcloud/tcloud_dtc/static/low_code/ad23c89d-e318-4f1c-b336-c818ca8dc3cc.svg',
                },
                {
                    icon: 'https://imgcache.qq.com/qcloud/tcloud_dtc/static/low_code/d60e9fcf-3ed2-4b89-b227-795a12c43eb0.svg',
                    name: 'value2',
                    title: '标题2',
                    activeIcon: 'https://imgcache.qq.com/qcloud/tcloud_dtc/static/low_code/a4de8c70-92cb-4a8d-a173-d77f29be8495.svg',
                },
            ],
            color: '#444444',
            route: false,
            value: 'value1',
            tabbar: '',
            iconSize: 40,
            position: 'bottom',
            routeType: 'redirectTo',
            activeColor: '#006EFF',
            backgroundColor: '#FFF',
            backgroundImage: '',
        };
        _this_1.propsData = (0, mobx_1.observable)(Object.assign({}, defaultProps, _this_1.props.data || {}));
        _this_1.$WEAPPS_COMP.lib = { const: constObj, tools: toolsObj };
        /*
        this.i18n = this.$WEAPPS_COMP.i18n = {
          ...i18n,
          t (key, data) {
            return i18n.t(libCode + ':' + key, data)
          },
        }
        */
        _this_1.$WEAPPS_COMP.props = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _this_1.props), { events: _this_1.events, data: _this_1.propsData });
        _this_1.state = _this_1.$WEAPPS_COMP.state = (0, mobx_1.observable)(state_js_1.default.bind(_this_1)());
        _this_1.computed = _this_1.$WEAPPS_COMP.computed = (0, index_1.createComputed)(computed_js_1.default, _this_1);
        _this_1.node = _this_1.$WEAPPS_COMP.node = _this_1.createWidgetNode(_this_1) || {};
        _this_1.initPublicMethods();
        _this_1.widgets = _this_1.$WEAPPS_COMP.widgets = (0, index_1.createWidgets)(widgetContext, dataBinds);
        // widgets 内的 dataBinds 可能需要关联 widgets，需要重新执行 dataBinds
        (0, index_1.retryDataBinds)();
        Object.keys(_this_1.widgets || {}).forEach(function (widgetId) {
            // 将实例 ownerWidget 挂到内部组件上。内部组件就可以通过 $comp.node.ownerWidget 获取到所在的组件实例
            var node = _this_1.widgets[widgetId];
            if (Array.isArray(node)) {
                node.forEach(function (item) {
                    item.ownerWidget = _this_1.node;
                    item.getOwnerWidget = function () { return _this_1.node; };
                });
            }
            else {
                node.ownerWidget = _this_1.node;
                node.getOwnerWidget = function () { return _this_1.node; };
            }
            // this.widgets[widgetId].ownerWidget = this.node
            // this.widgets[widgetId].getOwnerWidget = () => this.node
        });
        _this_1.pageListenerInstances = [];
        _this_1.createCompAPI(_this_1);
        return _this_1;
    }
    CompositeCompWrapper.prototype.componentDidUpdate = function () {
        var _this_1 = this;
        (0, mobx_1.runInAction)(function () {
            var data = _this_1.props.data;
            for (var prop in data) {
                // 更新 propsData
                if (typeof data[prop] !== 'function') {
                    _this_1.propsData[prop] = data[prop];
                }
            }
        });
    };
    // publicMthods 挂载内部，使用 $comp.api。挂载到外部使用 $comp.node.api
    CompositeCompWrapper.prototype.initPublicMethods = function () {
        var _this_1 = this;
        var publicMethods = index_2.default.publicMethods || {};
        Object.keys(publicMethods).map(function (fnName) {
            var bindFunc = publicMethods[fnName].bind(_this_1);
            _this_1[fnName] = bindFunc;
            _this_1.$WEAPPS_COMP[fnName] = bindFunc;
            if (_this_1.node)
                _this_1.node[fnName] = bindFunc;
        });
    };
    // 创建自身节点
    CompositeCompWrapper.prototype.createWidgetNode = function (compThis) {
        // 当为数组时，需要判断自己属于 widgets 的哪一项
        var _a = compThis.props, compositeParent = _a.compositeParent, forIndexes = _a.forIndexes, id = _a.id;
        var widgetData = compositeParent.$WEAPPS_COMP
            ? compositeParent.$WEAPPS_COMP.widgets[id]
            : compositeParent.$page.widgets[id];
        if (Array.isArray(widgetData)) {
            widgetData = widgetData.length > 0 ? (0, lodash_es_1.get)(widgetData, forIndexes) : {};
        }
        widgetData = widgetData || {};
        Object.assign(widgetData, {
            getConfig: function () { return compThis.compConfig; },
        }, (0, index_1.bindFuncObj)(index_2.default.publicMethods || {}, compThis));
        return widgetData;
    };
    CompositeCompWrapper.prototype.createCompAPI = function (compThis) {
        compThis.$WEAPPS_COMP = {
            _dataBinds: compThis._dataBinds,
            compConfig: compThis.compConfig,
            widgets: compThis.widgets,
            node: compThis.node,
            handler: compThis.handler,
            lib: { const: constObj, tools: toolsObj },
            // i18n: compThis.i18n,
            get props() {
                return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, compThis.props), { events: compThis.events, data: compThis.propsData });
            },
            get state() {
                return compThis.state;
            },
            get computed() {
                return compThis.computed;
            },
        };
    };
    CompositeCompWrapper.prototype.initWatchMethods = function () {
        var _this_1 = this;
        var _a = index_2.default.watch, watch = _a === void 0 ? {} : _a, _b = index_2.default.watchState, watchState = _b === void 0 ? {} : _b, _c = index_2.default.watchWidget, watchWidget = _c === void 0 ? {} : _c, _d = index_2.default.watchEffects, watchEffects = _d === void 0 ? {} : _d;
        var _this = this;
        var weappInst = _this.$WEAPPS_COMP;
        // # watch effect
        this.watchEffectDisposers = Object.keys(watchEffects).map(function (fnName) {
            return (0, mobx_1.autorun)(watchEffects[fnName].bind(_this_1));
        });
        var disposers = this.watchEffectDisposers;
        // # watch props
        Object.keys(watch).map(function (key) {
            return runWatcher(parseWatcher(watch[key]), weappInst.props.data, key, 'watch');
        });
        // # watch state
        Object.keys(watchState).map(function (key) {
            return runWatcher(parseWatcher(watchState[key]), weappInst.state, key, 'watchState');
        });
        // # watch widgets
        Object.keys(watchWidget).map(function (key) {
            return runWatcher(parseWatcher(watchWidget[key]), weappInst.widgets, key, 'watchWidgets');
        });
        function runWatcher(_a, target, key, label) {
            var _b = _a === void 0 ? {} : _a, handler = _b.handler, immediate = _b.immediate;
            if (!handler) {
                console.error("Invalid " + label + "(" + key + ") of " + weappInst.node.widgetType + ", watch must a function or {handler: function}");
                return;
            }
            var disposer = (0, mobx_1.reaction)(function () { return (0, lodash_es_1.get)(target, key); }, handler.bind(_this), {
                fireImmediately: immediate,
            });
            disposers.push(disposer);
        }
    };
    CompositeCompWrapper.prototype.componentDidMount = function () {
        this.initPublicMethods();
        this.initWatchMethods();
        lifecycle_js_1.default.onAttached && lifecycle_js_1.default.onAttached.bind(this)();
        lifecycle_js_1.default.onReady && lifecycle_js_1.default.onReady.bind(this)();
    };
    CompositeCompWrapper.prototype.componentWillUnmount = function () {
        if (this.watchEffectDisposers) {
            this.watchEffectDisposers.forEach(function (disposer) { return disposer(); });
            this.watchEffectDisposers = null;
        }
        this.node._listeners && this.node._listeners.clear();
        lifecycle_js_1.default.onDetached && lifecycle_js_1.default.onDetached.bind(this)();
    };
    CompositeCompWrapper.prototype.render = function () {
        console.log('------------', this.componentSchema);
        return (React.createElement(index_1.WidgetsContext.Provider, { value: { parent: this } },
            React.createElement(RenderWrapper_1.AppRender, { className: this.props.className, virtualFields: this.virtualFields, componentSchema: this.componentSchema, codeContext: this })));
    };
    return CompositeCompWrapper;
}(React.Component));
CompositeCompWrapper.contextType = index_1.WidgetsContext;
exports.default = (0, mobx_react_lite_1.observer)(function (props) { return (React.createElement(CompositeCompWrapper, (0, tslib_1.__assign)({}, props))); });
function parseWatcher(watcher) {
    if (!watcher)
        return;
    if (watcher instanceof Function) {
        return { handler: watcher, immediate: false };
    }
    var handler = watcher.handler, _a = watcher.immediate, immediate = _a === void 0 ? false : _a;
    if (!(handler instanceof Function))
        return;
    return { handler: handler, immediate: immediate };
}
//# sourceMappingURL=index.js.map