"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDataBindForDataset = exports.generateDataBinds = exports.getComponentSchema = exports.getComponentsInfo = exports.toCssStyle = void 0;
var tslib_1 = require("tslib");
var common_1 = require("../common");
var style_1 = require("../style");
var cals_1 = require("@cloudbase/cals");
var lodash_es_1 = require("lodash-es");
/**
 * utils start
 */
function getMetaInfoBySourceKey(sourceKey) {
    if (!sourceKey) {
        return {};
    }
    var _a = (0, tslib_1.__read)(sourceKey.split(':'), 2), materialName = _a[0], name = _a[1];
    return {
        materialName: materialName,
        name: name,
        variableName: (0, common_1.camelcase)(materialName + '_' + name),
    };
}
// Convert WeApps common style to css styles(React.CSSProperties)
function toCssStyle(commonStyle, options) {
    if (commonStyle === void 0) { commonStyle = {}; }
    if (options === void 0) { options = { toRem: true, ignoreSelf: false, addPXUnit: false, toRpx: false }; }
    var size = commonStyle.size, 
    // transform,
    text = commonStyle.text, border = commonStyle.border, background = commonStyle.background, margin = commonStyle.margin, padding = commonStyle.padding, zIndex = commonStyle.zIndex, position = commonStyle.position, display = commonStyle.display, flexConfig = commonStyle.flexConfig, custom = commonStyle.custom, self = commonStyle.self;
    var style = {};
    if (size) {
        (0, style_1.setStyleValue)(style, 'width', (0, style_1._handleStyleNumValue)(size.width, !!options.addPXUnit));
        (0, style_1.setStyleValue)(style, 'height', (0, style_1._handleStyleNumValue)(size.height, !!options.addPXUnit));
    }
    // if (transform) {
    //   const { rotate, opacity, scale, radius } = transform
    //   if ((rotate && rotate !== 0) || (scale && scale !== 1)) {
    //     style.transform = `${rotate ? `rotate(${rotate}deg) ` : ''}${scale ? `scale(${scale})` : ''}`
    //   }
    //   setStyleValue(style, 'opacity', opacity)
    //   setStyleValue(style, 'borderRadius', radius)
    // }
    if (margin) {
        (0, style_1.setDistanceStyle)(style, margin, 'margin', !!options.addPXUnit);
    }
    if (padding) {
        (0, style_1.setDistanceStyle)(style, padding, 'padding', !!options.addPXUnit);
    }
    if (display) {
        (0, style_1.setStyleValue)(style, 'display', display);
    }
    if (display === 'flex' && flexConfig) {
        if (flexConfig.justifyContent)
            (0, style_1.setStyleValue)(style, 'justifyContent', flexConfig.justifyContent);
        if (flexConfig.alignItems)
            (0, style_1.setStyleValue)(style, 'alignItems', flexConfig.alignItems);
        if (flexConfig.flexWrap && flexConfig.flexDirection) {
            (0, style_1.setStyleValue)(style, 'flexFlow', flexConfig.flexDirection + " " + flexConfig.flexWrap);
        }
        else {
            if (flexConfig.flexWrap)
                (0, style_1.setStyleValue)(style, 'flexWrap', flexConfig.flexWrap);
            if (flexConfig.flexDirection)
                (0, style_1.setStyleValue)(style, 'flexDirection', flexConfig.flexDirection);
        }
    }
    if (typeof zIndex === 'number' || ("" + zIndex).search(/^\d+$/) === 0) {
        style.zIndex = zIndex;
    }
    if (text) {
        (0, style_1.setStyleValue)(style, 'color', text.color);
        (0, style_1.setStyleValue)(style, 'fontSize', (0, style_1._handleStyleNumValue)(text.fontSize, !!options.addPXUnit));
        (0, style_1.setStyleValue)(style, 'lineHeight', text.lineHeight);
        (0, style_1.setStyleValue)(style, 'textAlign', text.textAlign);
        (0, style_1.setStyleValue)(style, 'fontWeight', text.weight);
        if (text.opacity) {
            (0, style_1.setStyleValue)(style, 'opacity', text.opacity / 100);
        }
    }
    if (border) {
        var type = border.type, color = border.color, width = border.width, radius = border.radius, radiusInfo = border.radiusInfo;
        if (width !== undefined) {
            if (type) {
                (0, style_1.setStyleValue)(style, 'border', (0, style_1._handleStyleNumValue)(width, !!options.addPXUnit) + " " + type + " " + (color || ''));
            }
            else {
                (0, style_1.setStyleValue)(style, 'borderWidth', (0, style_1._handleStyleNumValue)(width, !!options.addPXUnit));
                if (color)
                    (0, style_1.setStyleValue)(style, 'borderColor', color);
            }
        }
        if (radius !== undefined) {
            (0, style_1.setStyleValue)(style, 'borderRadius', (0, style_1._handleStyleNumValue)(radius, !!options.addPXUnit));
        }
        if (radiusInfo && !(0, common_1.isEmptyObj)(radiusInfo)) {
            if (Object.keys(radiusInfo).length === 4) {
                if ((0, lodash_es_1.uniq)((0, lodash_es_1.map)(radiusInfo, function (val) { return val; })).length === 1) {
                    // 4个值全相等的情况
                    (0, style_1.setStyleValue)(style, 'borderRadius', (0, style_1._handleStyleNumValue)(radiusInfo.topLeft, !!options.addPXUnit));
                }
                else if (radiusInfo.topLeft === radiusInfo.bottomRight &&
                    radiusInfo.topRight === radiusInfo.bottomLeft) {
                    // 俩俩相等的情况
                    (0, style_1.setStyleValue)(style, 'borderRadius', (0, style_1._handleStyleNumValue)(radiusInfo.topLeft, !!options.addPXUnit) + " " + (0, style_1._handleStyleNumValue)(radiusInfo.topRight, !!options.addPXUnit));
                }
                else if (radiusInfo.topRight === radiusInfo.bottomLeft) {
                    (0, style_1.setStyleValue)(style, 'borderRadius', (0, style_1._handleStyleNumValue)(radiusInfo.topLeft, !!options.addPXUnit) + " " + (0, style_1._handleStyleNumValue)(radiusInfo.topRight, !!options.addPXUnit) + " " + (0, style_1._handleStyleNumValue)(radiusInfo.bottomRight, !!options.addPXUnit));
                }
                else {
                    (0, style_1.setStyleValue)(style, 'borderRadius', (0, style_1._handleStyleNumValue)(radiusInfo.topLeft, !!options.addPXUnit) + " " + (0, style_1._handleStyleNumValue)(radiusInfo.topRight, !!options.addPXUnit) + " " + (0, style_1._handleStyleNumValue)(radiusInfo.bottomRight, !!options.addPXUnit) + " " + (0, style_1._handleStyleNumValue)(radiusInfo.bottomLeft, !!options.addPXUnit));
                }
            }
            else {
                (0, style_1.setStyleValue)(style, 'borderTopLeftRadius', (0, style_1._handleStyleNumValue)(radiusInfo.topLeft, !!options.addPXUnit));
                (0, style_1.setStyleValue)(style, 'borderTopRightRadius', (0, style_1._handleStyleNumValue)(radiusInfo.topRight, !!options.addPXUnit));
                (0, style_1.setStyleValue)(style, 'borderBottomRightRadius', (0, style_1._handleStyleNumValue)(radiusInfo.bottomRight, !!options.addPXUnit));
                (0, style_1.setStyleValue)(style, 'borderBottomLeftRadius', (0, style_1._handleStyleNumValue)(radiusInfo.bottomLeft, !!options.addPXUnit));
            }
        }
    }
    if (background) {
        var bgType = background.bgType, color = background.color, image = background.image, size_1 = background.size, repeat = background.repeat, position_1 = background.position, positionObj = background.positionObj;
        if (bgType === 'color') {
            (0, style_1.setStyleValue)(style, 'background', color);
        }
        else if (bgType === 'image') {
            // 如 radial-gradient(crimson, skyblue);
            if (image != null) {
                if (image.search(/[()]/) >= 0) {
                    style.background = image;
                }
                else {
                    style.background = "url(" + image + ")";
                }
            }
            if (repeat)
                style.background += " " + repeat;
            if (size_1) {
                (0, style_1.setStyleValue)(style, 'backgroundSize', (0, style_1._handleStyleNumValue)(size_1, !!options.addPXUnit));
            }
            (0, style_1.setStyleValue)(style, 'backgroundPosition', position_1);
            if (positionObj && !(0, common_1.isEmptyObj)(positionObj)) {
                style.background += " " + (0, style_1._handleStyleNumValue)(positionObj.left, !!options.addPXUnit) + " " + (0, style_1._handleStyleNumValue)(positionObj.top, !!options.addPXUnit);
            }
        }
        // FIXME: 这里兼容原有应用的数据，后面应去掉
        if (bgType === undefined) {
            (0, style_1.setStyleValue)(style, 'backgroundColor', color);
            if (image != null) {
                style.backgroundImage = "url(" + image + ")";
                (0, style_1.setStyleValue)(style, 'backgroundRepeat', repeat);
                (0, style_1.setStyleValue)(style, 'backgroundSize', (0, style_1._handleStyleNumValue)(size_1, !!options.addPXUnit));
                (0, style_1.setStyleValue)(style, 'backgroundPosition', position_1);
            }
        }
    }
    if (position) {
        (0, style_1.setStyleValue)(style, 'position', position.position);
        if (position.left !== undefined) {
            (0, style_1.setStyleValue)(style, 'left', (0, style_1._handleStyleNumValue)(position.left, !!options.addPXUnit));
        }
        if (position.right !== undefined) {
            (0, style_1.setStyleValue)(style, 'right', (0, style_1._handleStyleNumValue)(position.right, !!options.addPXUnit));
        }
        if (position.top !== undefined) {
            (0, style_1.setStyleValue)(style, 'top', (0, style_1._handleStyleNumValue)(position.top, !!options.addPXUnit));
        }
        if (position.bottom !== undefined) {
            (0, style_1.setStyleValue)(style, 'bottom', (0, style_1._handleStyleNumValue)(position.bottom, !!options.addPXUnit));
        }
    }
    if (custom && custom.length > 0) {
        custom.map(function (item) {
            (0, style_1.setStyleValue)(style, item.key, item.value);
        });
    }
    if (self && !options.ignoreSelf) {
        Object.assign(style, self);
    }
    if (options.toRpx) {
        return (0, style_1.translateStyleToRpx)(style);
    }
    return options.toRem ? (0, style_1.translateStyleToRem)(style) : style;
}
exports.toCssStyle = toCssStyle;
function getComponentsInfo(dependencies) {
    var outputObj = {};
    dependencies.forEach(function (_a) {
        var materialName = _a.name, components = _a.components, isComposite = _a.isComposite;
        if (isComposite) {
            components.forEach(function (component) {
                var compItem = component;
                var sourceKey = materialName + ":" + compItem.name;
                outputObj[sourceKey] = (0, tslib_1.__assign)({ isComposite: isComposite }, compItem);
            });
        }
        else {
            components.forEach(function (_a) {
                var name = _a.name, meta = _a.meta, emitEvents = _a.emitEvents, _b = _a.events, events = _b === void 0 ? undefined : _b, isContainer = _a.isContainer, compConfig = _a.compConfig;
                outputObj[materialName + ':' + name] = (0, tslib_1.__assign)((0, tslib_1.__assign)({ isComposite: isComposite }, meta), { events: events, emitEvents: emitEvents, isContainer: isContainer, compConfig: compConfig });
            });
        }
    });
    return outputObj;
}
exports.getComponentsInfo = getComponentsInfo;
function getInputProps(componentsMetaMap) {
    var outputObj = {};
    var _loop_1 = function (key) {
        var component = componentsMetaMap[key];
        var sourceKey = key;
        if (component.isComposite) {
            var compItem_1 = component;
            Object.keys(compItem_1.dataForm || {}).forEach(function (key) {
                var _a;
                var _b, _c;
                var inputProps = ((_b = compItem_1.dataForm[key]) === null || _b === void 0 ? void 0 : _b.inputProp) || ((_c = compItem_1.dataForm[key]) === null || _c === void 0 ? void 0 : _c.syncProp);
                if (inputProps) {
                    outputObj[sourceKey] = (0, tslib_1.__assign)((_a = {}, _a[key] = inputProps, _a), (outputObj[sourceKey] || {}));
                }
            });
        }
        else {
            var inputProps = (component === null || component === void 0 ? void 0 : component.inputProps) || (component === null || component === void 0 ? void 0 : component.syncProps);
            if (inputProps) {
                outputObj[sourceKey] = inputProps;
            }
        }
    };
    for (var key in componentsMetaMap) {
        _loop_1(key);
    }
    return outputObj;
}
/**
 * utils end
 */
function splitDynamicMap(data) {
    var staticData = {};
    var dataBinds = [];
    for (var key in data) {
        var meta = data[key];
        if (!meta.type || meta.type === cals_1.PropBindType.static) {
            staticData[key] = meta.value;
        }
        else if (meta.type === cals_1.PropBindType.slot) {
            continue;
        }
        else {
            dataBinds.push({
                type: meta.type,
                bindDataPath: meta.value,
                propertyPath: key,
            });
        }
    }
    return { staticData: staticData, dataBinds: dataBinds };
}
function walkThroughCals(cals, process) {
    var e_1, _a;
    var _b;
    var _c = cals.items, items = _c === void 0 ? [] : _c;
    cals.extra = cals.extra || {};
    if (((_b = cals === null || cals === void 0 ? void 0 : cals.directives) === null || _b === void 0 ? void 0 : _b[':if']) === false) {
        cals.items = [];
    }
    try {
        for (var items_1 = (0, tslib_1.__values)(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
            var item = items_1_1.value;
            item.extra = item.extra || {};
            item.extra.__parent = cals;
            walkThroughCals(item, process);
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    process(cals);
    return cals;
}
function getComponentSchema(ctx, page, isComposite, componentsInfoMap, wrapperClass, options) {
    if (isComposite === void 0) { isComposite = false; }
    if (componentsInfoMap === void 0) { componentsInfoMap = {}; }
    var componentInputProps = getInputProps(componentsInfoMap) || {};
    var copyJson = JSON.parse(JSON.stringify(page));
    var compWidgets = {};
    var compDataBinds = {};
    var componentSchemaJson = walkThroughCals(copyJson, function (component) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
        if ((0, common_1.isSlot)(component)) {
            return;
        }
        var componentName = component.component, module = component.module, _s = component.attributes, attributes = _s === void 0 ? {} : _s;
        var _t = (component.extra || {}).commonStyle, commonStyle = _t === void 0 ? {} : _t;
        var processedCommonStyle = attributes.style
            ? attributes.style
            : toCssStyle(commonStyle);
        if (processedCommonStyle && !(0, common_1.isEmptyObj)(processedCommonStyle)) {
            component.extra.commonStyle = processedCommonStyle;
        }
        var sourceKey = module + ":" + componentName;
        var _u = attributes.class, className = _u === void 0 ? '' : _u;
        var deserializeCtx = { page: page };
        var dynamicStyle = component[':style']
            ? (0, cals_1.deserializeValue)(deserializeCtx, ':style', component[':style']).value
            : undefined;
        var dynamicClassList = component[':class']
            ? (0, cals_1.deserializeValue)(deserializeCtx, ':class', component[':class']).value
            : undefined;
        var dynamicIf = ((_a = component.directives) === null || _a === void 0 ? void 0 : _a[':if'])
            ? (0, cals_1.deserializeValue)(deserializeCtx, ':if', (_b = component.directives) === null || _b === void 0 ? void 0 : _b[':if'])
                .value
            : undefined;
        var dynamicFor = ((_c = component.directives) === null || _c === void 0 ? void 0 : _c[':for'])
            ? (0, cals_1.deserializeValue)(deserializeCtx, ':for', (_d = component.directives) === null || _d === void 0 ? void 0 : _d[':for'])
                .value
            : undefined;
        if (dynamicIf != undefined &&
            (dynamicIf.value == undefined ||
                dynamicIf.value === true ||
                dynamicIf.value === false)) {
            dynamicIf = undefined;
        }
        if (dynamicFor) {
            var type = dynamicFor.type, value = dynamicFor.value;
            if (type === cals_1.PropBindType.expression) {
                dynamicFor.value = value.replace(/^(.*?in\s)/, '');
            }
        }
        var data = (0, cals_1.deserializeAttributes)(deserializeCtx, attributes);
        var _v = splitDynamicMap(data), dataBinds = _v.dataBinds, staticData = _v.staticData;
        var componentInfo = componentsInfoMap[sourceKey];
        if ((_e = componentInfo) === null || _e === void 0 ? void 0 : _e.compConfig) {
            component.extra.compConfig = (_f = componentInfo) === null || _f === void 0 ? void 0 : _f.compConfig;
        }
        if ((_g = componentInfo) === null || _g === void 0 ? void 0 : _g.events) {
            component.extra.emitEvents = (_h = componentInfo) === null || _h === void 0 ? void 0 : _h.events.map(function (item) { return item.name; });
        }
        else if ((_j = componentInfo) === null || _j === void 0 ? void 0 : _j.emitEvents) {
            component.extra.emitEvents = componentInfo.emitEvents.map(function (item) { return item.eventName; });
        }
        // 生成 widgets/dataBinds
        if (!(0, common_1.isSlot)(component) && component.id) {
            var parentComponent = component.extra.__parent;
            var _visible = undefined;
            switch ((_k = component.directives) === null || _k === void 0 ? void 0 : _k[':if']) {
                case true:
                case false: {
                    _visible = (_l = component.directives) === null || _l === void 0 ? void 0 : _l[':if'];
                    break;
                }
                case undefined: {
                    _visible = true;
                    break;
                }
            }
            compWidgets[component.id] = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, Object.entries(staticData).reduce(function (data, _a) {
                var _b = (0, tslib_1.__read)(_a, 2), propsKey = _b[0], propsValue = _b[1];
                var value = propsValue;
                if (value && Array.isArray(value)) {
                    value = value.map(function (_, index) {
                        var _a, _b;
                        var block = (_a = attributes === null || attributes === void 0 ? void 0 : attributes[propsKey]) === null || _a === void 0 ? void 0 : _a[index];
                        var blockInstances = (_b = block === null || block === void 0 ? void 0 : block.selectableBlock) === null || _b === void 0 ? void 0 : _b.listeners;
                        if (blockInstances) {
                            block.selectableBlock['listenerInstances'] =
                                generateListnerInstances(ctx, blockInstances || [], {
                                    isComposite: isComposite,
                                    looseError: options === null || options === void 0 ? void 0 : options.looseError,
                                });
                        }
                        return block;
                    });
                }
                data[propsKey] = value;
                return data;
            }, {})), { _visible: _visible, style: (0, tslib_1.__assign)({}, processedCommonStyle), classList: className.split(/\s/).filter(function (item) { return !!item; }), widgetType: sourceKey, _parentId: parentComponent
                    ? (0, common_1.isSlot)(parentComponent)
                        ? (_o = (_m = parentComponent.extra) === null || _m === void 0 ? void 0 : _m.__parent) === null || _o === void 0 ? void 0 : _o.id
                        : parentComponent.id
                    : null, getConfig: function () {
                    var _a, _b;
                    return (_b = (_a = componentInfo) === null || _a === void 0 ? void 0 : _a.compConfig) !== null && _b !== void 0 ? _b : {};
                } });
            var processedDataBinds = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(dataBinds), false);
            if (dynamicIf === null || dynamicIf === void 0 ? void 0 : dynamicIf.value) {
                processedDataBinds.push({
                    type: dynamicIf.type,
                    bindDataPath: dynamicIf.value,
                    propertyPath: '_visible',
                });
            }
            if (dynamicFor === null || dynamicFor === void 0 ? void 0 : dynamicFor.value) {
                processedDataBinds.push({
                    type: dynamicFor.type,
                    bindDataPath: dynamicFor.value,
                    propertyPath: '_waFor',
                });
            }
            if (dynamicStyle === null || dynamicStyle === void 0 ? void 0 : dynamicStyle.value) {
                processedDataBinds.push({
                    type: dynamicStyle.type,
                    bindDataPath: dynamicStyle.value,
                    propertyPath: 'style',
                });
            }
            if (dynamicClassList) {
                processedDataBinds.push({
                    type: dynamicClassList.type,
                    bindDataPath: dynamicClassList.value,
                    propertyPath: 'classList',
                });
            }
            if (processedDataBinds.length > 0) {
                compDataBinds[component.id] = generateDataBinds(ctx, processedDataBinds, { isComposite: isComposite, looseError: options === null || options === void 0 ? void 0 : options.looseError });
            }
        }
        component['listenerInstances'] = generateListnerInstances(ctx, component.listeners || [], { isComposite: isComposite, looseError: options === null || options === void 0 ? void 0 : options.looseError });
        delete component.listeners;
        if (!(0, common_1.isEmptyObj)(attributes)) {
            // 如果是复合组件的根节点，则补充 wrapperClass
            if (isComposite) {
                if (!((_r = (_q = (_p = component === null || component === void 0 ? void 0 : component.extra) === null || _p === void 0 ? void 0 : _p.__parent) === null || _q === void 0 ? void 0 : _q.extra) === null || _r === void 0 ? void 0 : _r.__parent)) {
                    component.attributes = {};
                    component.attributes.class = component.attributes.class + " " + wrapperClass;
                }
            }
            // 组件双向绑定
            var syncProps_1 = componentInputProps[sourceKey];
            if (syncProps_1) {
                Object.keys(syncProps_1).forEach(function (syncPropKey) {
                    var syncPropArr = [];
                    var syncProp = syncProps_1[syncPropKey];
                    // 统一转成数组处理
                    if (!Array.isArray(syncProp)) {
                        syncPropArr = [syncProp];
                    }
                    syncPropArr.forEach(function (_a) {
                        // 双向绑定需要优先第一个执行，否则会出现输入框的拼音被打断的问题
                        var changeEvent = _a.changeEvent, valueFromEvent = _a.valueFromEvent;
                        function withContext(context) {
                            var instance = new Function('context', "return ({ event, forItems }) => {\n                  const $for = forItems;\n                  const wid = " + (isComposite ? 'this.widgets' : '$page.widgets') + "." + component.id + ";\n                  const widgetData = $for.forIndexes && $for.forIndexes.length > 0 ? context.get(wid, forItems.forIndexes) : wid;\n                  widgetData." + syncPropKey + " = " + valueFromEvent + "\n                }")(context);
                            return ctx.this ? instance.bind(this) : instance;
                        }
                        component['listenerInstances'].unshift({
                            trigger: changeEvent,
                            instanceFunction: withContext({ get: lodash_es_1.get }),
                        });
                    });
                });
            }
        }
    });
    return {
        widgets: compWidgets,
        dataBinds: compDataBinds,
        componentSchema: componentSchemaJson,
    };
}
exports.getComponentSchema = getComponentSchema;
// convert data binds to functions for performance & simplicity
function generateDataBinds(ctx, dataBinds, options) {
    var dataBindFuncs = {};
    dataBinds.forEach(function (bind) {
        var _a;
        if (!bind.bindDataPath) {
            return console.warn('无 bindDataPath', bind.propertyPath);
        }
        var funcCode = function () { };
        try {
            if (bind.type === cals_1.PropBindType.forItem) {
                funcCode = new Function('context', "return (forItems) => forItems." + bind.bindDataPath)(ctx);
            }
            else if (bind.type === 'scope') {
                funcCode = new Function('context', "return () => ({__type: \"scopedValue\", getValue: ($scope)=>$scope." + bind.bindDataPath + "})}")(ctx);
            }
            else if (bind.type === cals_1.PropBindType.expression) {
                if (options === null || options === void 0 ? void 0 : options.isComposite) {
                    funcCode = new Function('context', "const { $page, app, $app } = context || {};\n            return (forItems, $context) => {const $for = forItems; return (\n" + (bind.bindDataPath
                        .replace(/\$comp/g, 'this.$WEAPPS_COMP')
                        .replace(/;$/, '') || 'undefined') + "\n)}")(ctx);
                }
                else {
                    var code = bind.bindDataPath.replace(/;$/, '');
                    funcCode = new Function('context', "const { $page, app, $app } = context || {};\n\n            return " + (/\$scope\./.test(code)
                        ? "(forItems, event, $context) => ({__type: \"scopedValue\", getValue: ($scope) => { const $for = forItems; return (\n" + code + "\n)}})"
                        : "(forItems, event, $context) => { const $for = forItems; return (\n" + (code || 'undefined') + "\n)}"))(ctx);
                }
            }
            else if (bind.type === cals_1.PropBindType.prop) {
                var bindDataPath = bind.bindDataPath;
                var isNegated = bindDataPath.startsWith('!');
                if (isNegated)
                    bindDataPath = bindDataPath.replace(/^!/, '');
                if (options === null || options === void 0 ? void 0 : options.isComposite) {
                    // 复合组件在预览时其实就是page，所以沿用page的变量即可
                    funcCode = new Function('context', "const { $page, app, $app } = context || {};\n            return () => " + (isNegated ? '!' : '') + 'this.$WEAPPS_COMP' + ".props.data." + bindDataPath)(ctx);
                }
                else {
                    // 复合组件在预览时其实就是page，所以沿用page的变量即可
                    funcCode = new Function('context', "const { $page, app, $app } = context || {};\n            return () => " + (isNegated ? '!' : '') + "$page.props.data." + bindDataPath)(ctx);
                }
            }
            else {
                var isGlobal = bind.bindDataPath.startsWith('global.');
                var returnValue = '';
                var PREFIX_MAP = (_a = {},
                    _a[cals_1.PropBindType.state] = 'state',
                    _a[cals_1.PropBindType.computed] = 'computed',
                    // [PropBindType.dataVar]: 'dataVar',
                    _a[cals_1.PropBindType.stateData] = 'dataset.state',
                    _a[cals_1.PropBindType.paramData] = 'dataset.params',
                    _a);
                switch (bind.type) {
                    case cals_1.PropBindType.state:
                    case cals_1.PropBindType.computed:
                    // case PropBindType.dataVar:
                    case cals_1.PropBindType.stateData:
                    case cals_1.PropBindType.paramData: {
                        if (isGlobal) {
                            returnValue = bind.bindDataPath.replace(/^global./, "app." + PREFIX_MAP[bind.type] + ".");
                        }
                        else {
                            if (options === null || options === void 0 ? void 0 : options.isComposite) {
                                returnValue = bind.bindDataPath
                                    .replace(/^comp-\w+./, "this.$WEAPPS_COMP." + PREFIX_MAP[bind.type] + ".")
                                    .replace(/^\$\w+_\d+./, "this.$WEAPPS_COMP." + PREFIX_MAP[bind.type] + ".");
                            }
                            else {
                                returnValue = bind.bindDataPath.replace(/^\w+./, "$page." + PREFIX_MAP[bind.type] + ".");
                            }
                        }
                        funcCode = new Function('context', "const { $page, app, $app } = context || {};\n              return () => " + returnValue)(ctx);
                        break;
                    }
                }
            }
        }
        catch (e) {
            if (options === null || options === void 0 ? void 0 : options.looseError) {
                console.error('generate dynamic data error:', e);
                funcCode = function () {
                    throw e;
                };
            }
            else {
                throw e;
            }
        }
        dataBindFuncs[bind.propertyPath] = funcCode;
    });
    return dataBindFuncs;
}
exports.generateDataBinds = generateDataBinds;
/**
 * dataset 特殊的绑定格式
 * 要求：入参分别为 app ， page
 * 绑定只有变量，参数，表达式的绑定
 */
function generateDataBindForDataset(bind) {
    var _a;
    var expr = '';
    var type = bind.type, bindDataPath = bind.bindDataPath;
    if (type === cals_1.PropBindType.static || !type) {
        expr =
            typeof bindDataPath === 'string'
                ? "'" + bindDataPath + "'"
                : JSON.stringify(bindDataPath);
    }
    else if (type === cals_1.PropBindType.expression) {
        expr = bindDataPath;
    }
    else {
        var isGlobal = bindDataPath.startsWith('global.');
        var isCopositive = bindDataPath.startsWith('comp-') || bindDataPath.startsWith('$comp_');
        var PREFIX_MAP = (_a = {},
            _a[cals_1.PropBindType.state] = 'state',
            _a[cals_1.PropBindType.computed] = 'computed',
            _a[cals_1.PropBindType.dataVar] = 'dataVar',
            _a[cals_1.PropBindType.stateData] = 'dataset.state',
            _a[cals_1.PropBindType.paramData] = 'dataset.params',
            _a);
        switch (type) {
            case cals_1.PropBindType.state:
            case cals_1.PropBindType.computed:
            case cals_1.PropBindType.dataVar:
            case cals_1.PropBindType.stateData:
            case cals_1.PropBindType.paramData: {
                if (isCopositive) {
                    expr = bindDataPath
                        .replace(/^comp-\w+/, "$comp." + PREFIX_MAP[type])
                        .replace(/^\$comp_\w+/, "$comp." + PREFIX_MAP[type]);
                }
                else {
                    expr = bindDataPath
                        .replace(/^\w+./, (isGlobal ? 'app' : '$page') + "." + PREFIX_MAP[type] + ".")
                        .replace(/^comp-\w+/, "$comp." + PREFIX_MAP[type])
                        .replace(/^\$comp_\w+/, "$comp." + PREFIX_MAP[type]);
                }
            }
        }
    }
    return new Function('app, $page', "const $app = app; return (\n" + (expr || 'undefined') + "\n)");
}
exports.generateDataBindForDataset = generateDataBindForDataset;
function generateListnerInstances(ctx, listenerInstances, options) {
    var _this = this;
    if (options === void 0) { options = {
        isComposite: false,
    }; }
    var _a = options.isComposite, isComposite = _a === void 0 ? false : _a;
    return listenerInstances.map(function (listener) {
        var _a, _b, _c, _d, _e;
        var generatedListener = {
            key: listener.id,
            trigger: listener.eventName,
            isCapturePhase: !!listener.isCapturePhase,
            noPropagation: listener['noPropagation'],
            instanceFunction: function () { },
            data: {},
            dataBinds: {},
        };
        if (listener.type === cals_1.ActionType.Material) {
            var _f = listener.handler || {}, name_1 = _f.name, module_1 = _f.module;
            generatedListener.instanceFunction = new Function('context', "const { $page, app, $app, actionsMap = {} } = context || {};\n        return (...args) => actionsMap[\"" + module_1 + ":" + name_1 + "\"]?.apply?.(null, args)")(ctx);
        }
        else if (listener.type === cals_1.ActionType.PropEvent) {
            if (isComposite) {
                var instance = new Function('{ data, event, forItems }', "\n          event.detail.data = data;\n          this.props.emit('" + (
                // TODO: CHECK listener.handler.name 具体是什么
                listener.handler.name || listener['jsCode']) + "', event.detail);");
                generatedListener.instanceFunction = ctx.this
                    ? instance.bind(_this)
                    : instance;
            }
            else {
                generatedListener.instanceFunction = new Function('context', "return (...args) => context.$page.props.events." + (((_a = listener.handler) === null || _a === void 0 ? void 0 : _a.name) || listener['jsCode']) + ".apply(null, args)")(ctx);
            }
        }
        else if (listener.type === cals_1.ActionType.Inline) {
            // 内联 handler
            var instance = new Function('{event, domEvent, customEventData, data, forItems}', "return " + listener['jsCode']);
            if (isComposite) {
                generatedListener.instanceFunction = ctx.this
                    ? instance.bind(_this)
                    : instance;
            }
            else {
                generatedListener.instanceFunction = instance.bind(ctx.$page);
            }
        }
        else if (listener.type === cals_1.ActionType.Platform) {
            var name_2 = ((_b = listener.handler) === null || _b === void 0 ? void 0 : _b.name) || listener['jsCode'];
            generatedListener.instanceFunction = new Function('{data}', "return app." + name_2 + "(data)");
        }
        else if (listener.type === cals_1.ActionType.DataSource) {
            generatedListener.instanceFunction = new Function('{data}', "return app.cloud.callDataSource(data)");
        }
        else {
            // Lowcode action(handler)
            if (isComposite) {
                generatedListener.instanceFunction = new Function('', "return this.handler." + (((_c = listener.handler) === null || _c === void 0 ? void 0 : _c.name) || listener['jsCode']) + ".bind(this)").bind(ctx.this)();
            }
            else {
                var name_3 = ((_d = listener.handler) === null || _d === void 0 ? void 0 : _d.name) || listener['jsCode'];
                generatedListener.instanceFunction = new Function('context', "return context.$page.handler." + name_3)(ctx);
            }
        }
        var processedParams = (0, cals_1.deserializeDynamicMap)({
            page: { id: ctx.$page.id, type: cals_1.EComponentType.PAGE },
        }, (_e = listener.handler) === null || _e === void 0 ? void 0 : _e.params);
        var _g = splitDynamicMap(processedParams), staticData = _g.staticData, dataBinds = _g.dataBinds;
        generatedListener.data = staticData;
        generatedListener.dataBinds = generateDataBinds(ctx, dataBinds, options);
        return generatedListener;
    });
}
//# sourceMappingURL=generate.js.map