"use strict";
var _Query_instances, _Query_schema, _Query_context, _Query_triggered, _Query_disposes, _Query_dataBinds, _Query_action, _Query_paramsRef, _Query_emit, _Query_currentRequestKey, _Query_observableValue, _Query_innerTrigger, _Query_debounceTrigger, _Query_resolveParams;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Query = void 0;
const tslib_1 = require("tslib");
const cals_1 = require("@cloudbase/cals");
const mobx_1 = require("mobx");
const generate_1 = require("./adapter/generate");
const runtime_1 = require("./runtime");
const lodash_es_1 = require("lodash-es");
var EQUERY_PARAM_TYPE;
(function (EQUERY_PARAM_TYPE) {
    EQUERY_PARAM_TYPE["ARRAY"] = "ARRAY";
    EQUERY_PARAM_TYPE["BOOLEAN"] = "BOOLEAN";
    EQUERY_PARAM_TYPE["NUMBER"] = "NUMBER";
    EQUERY_PARAM_TYPE["OBJECT"] = "OBJECT";
    EQUERY_PARAM_TYPE["STRING"] = "STRING";
})(EQUERY_PARAM_TYPE || (EQUERY_PARAM_TYPE = {}));
class Query {
    constructor({ schema, context, options, }) {
        var _a, _b, _c;
        _Query_instances.add(this);
        _Query_schema.set(this, void 0);
        _Query_context.set(this, void 0);
        _Query_triggered.set(this, false);
        _Query_disposes.set(this, []);
        _Query_dataBinds.set(this, {});
        _Query_action.set(this, void 0);
        _Query_paramsRef.set(this, (0, mobx_1.observable)({ current: null }));
        _Query_emit.set(this, void 0);
        _Query_currentRequestKey.set(this, null);
        _Query_observableValue.set(this, (0, mobx_1.observable)({
            data: null,
            error: null,
            isFetching: false,
        }));
        _Query_debounceTrigger.set(this, (0, lodash_es_1.debounce)(tslib_1.__classPrivateFieldGet(this, _Query_instances, "m", _Query_innerTrigger), 300));
        const { looseError = false, useScopeWidgetData = false } = options;
        const { $w, $app, $page } = context;
        tslib_1.__classPrivateFieldSet(this, _Query_schema, (0, cals_1.normalizeQuery)(schema), "f");
        tslib_1.__classPrivateFieldSet(this, _Query_context, context, "f");
        if (((_a = tslib_1.__classPrivateFieldGet(this, _Query_schema, "f")) === null || _a === void 0 ? void 0 : _a.trigger) === 'auto') {
            tslib_1.__classPrivateFieldGet(this, _Query_disposes, "f").push((0, mobx_1.autorun)((r) => {
                try {
                    const data = tslib_1.__classPrivateFieldGet(this, _Query_instances, "m", _Query_resolveParams).call(this);
                    if (tslib_1.__classPrivateFieldGet(this, _Query_triggered, "f")) {
                        tslib_1.__classPrivateFieldGet(this, _Query_debounceTrigger, "f").call(this, data);
                    }
                }
                catch (e) {
                    console.error(e);
                }
            }, { delay: 50 }));
        }
        const deserializeContext = ($page === null || $page === void 0 ? void 0 : $page.id)
            ? {
                page: { id: $page.id, type: cals_1.EComponentType.PAGE },
            }
            : {};
        const processedParams = (0, cals_1.deserializeDynamicMap)(deserializeContext, ((_b = tslib_1.__classPrivateFieldGet(this, _Query_schema, "f").handler) === null || _b === void 0 ? void 0 : _b.params) || {});
        const { staticData, dataBinds = [] } = (0, generate_1.splitDynamicMap)(processedParams);
        tslib_1.__classPrivateFieldGet(this, _Query_paramsRef, "f").current = staticData;
        tslib_1.__classPrivateFieldSet(this, _Query_dataBinds, (0, generate_1.generateDataBinds)({ $page, $app }, dataBinds === null || dataBinds === void 0 ? void 0 : dataBinds.filter((item) => {
            return !/[\s+\-*/!&|%]*?SERVER\./.test(item.propertyPath);
        }), Object.assign(Object.assign({ looseError,
            useScopeWidgetData }, options), { key: `${this.id} method.params` })), "f");
        tslib_1.__classPrivateFieldSet(this, _Query_action, tslib_1.__classPrivateFieldGet(this, _Query_schema, "f").type === 'sql'
            ? function (data) {
                return tslib_1.__awaiter(this, void 0, void 0, function* () {
                    const Data = yield $w.cloud.callWedaApi({
                        action: 'RunPluginQuery',
                        data: {
                            EnvId: $w.env.envId,
                            MainAppId: $w.app.id,
                            Name: data.sqlTemplateId,
                            Parameter: JSON.stringify(Object.entries(data.params || {}).reduce((list, [key, value]) => {
                                if (value !== undefined) {
                                    let type = EQUERY_PARAM_TYPE.OBJECT;
                                    const typeofValue = typeof value;
                                    switch (typeofValue) {
                                        case 'boolean': {
                                            type = EQUERY_PARAM_TYPE.BOOLEAN;
                                            break;
                                        }
                                        case 'number': {
                                            type = EQUERY_PARAM_TYPE.NUMBER;
                                            break;
                                        }
                                        case 'string': {
                                            type = EQUERY_PARAM_TYPE.STRING;
                                            break;
                                        }
                                        default: {
                                            if (Array.isArray(value)) {
                                                type = EQUERY_PARAM_TYPE.ARRAY;
                                            }
                                            else {
                                                type = EQUERY_PARAM_TYPE.OBJECT;
                                            }
                                        }
                                    }
                                    list.push({
                                        Key: key,
                                        Type: type,
                                        Value: type === EQUERY_PARAM_TYPE.STRING ? value : JSON.stringify(value),
                                    });
                                }
                                return list;
                            }, []) || []),
                        },
                    });
                    const { ExecuteResultList = [], Total } = Data || {};
                    return {
                        records: ExecuteResultList.map((item) => JSON.parse(item)),
                        total: Total || ExecuteResultList.length,
                    };
                });
            }
            : (0, lodash_es_1.get)($w.app, (_c = tslib_1.__classPrivateFieldGet(this, _Query_schema, "f").handler) === null || _c === void 0 ? void 0 : _c.name) ||
                function (data) {
                    throw new Error('Invalue query handler');
                }, "f");
        tslib_1.__classPrivateFieldSet(this, _Query_emit, (trigger, eventData, originalEvent) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            var _d;
            return (0, runtime_1.generateEmit)($w)(trigger, (0, generate_1.generateListnerInstances)({
                $app,
                $page,
                actionsMap: tslib_1.__classPrivateFieldGet(this, _Query_context, "f").actionsMap,
            }, tslib_1.__classPrivateFieldGet(this, _Query_schema, "f").listeners || []), eventData, {}, originalEvent, {}, {}, 
            /**
             * 当 app 全局情况下
             * 不进行 pageId 判断
             */
            (_d = $w.page) === null || _d === void 0 ? void 0 : _d.id, true);
        }), "f");
        return this;
    }
    get id() {
        var _a;
        return ((_a = tslib_1.__classPrivateFieldGet(this, _Query_schema, "f")) === null || _a === void 0 ? void 0 : _a.id) || '';
    }
    get label() {
        var _a;
        return ((_a = tslib_1.__classPrivateFieldGet(this, _Query_schema, "f")) === null || _a === void 0 ? void 0 : _a.label) || '';
    }
    get description() {
        var _a;
        return ((_a = tslib_1.__classPrivateFieldGet(this, _Query_schema, "f")) === null || _a === void 0 ? void 0 : _a.description) || '';
    }
    get data() {
        return tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").data;
    }
    get error() {
        return tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").error;
    }
    get isFetching() {
        return tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").isFetching;
    }
    trigger(additionalScope, options = {}) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            tslib_1.__classPrivateFieldSet(this, _Query_triggered, true, "f");
            return tslib_1.__classPrivateFieldGet(this, _Query_instances, "m", _Query_innerTrigger).call(this, tslib_1.__classPrivateFieldGet(this, _Query_instances, "m", _Query_resolveParams).call(this, additionalScope), options);
        });
    }
    reset() {
        tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").data = null;
        tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").error = null;
        tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").isFetching = false;
    }
    destroy() {
        tslib_1.__classPrivateFieldGet(this, _Query_disposes, "f").forEach((dispose) => dispose());
    }
    /**
     * 用于调试
     */
    _toSchema() {
        console.warn('调试使用，结构可能发生更改，请不要用于生产环境');
        return tslib_1.__classPrivateFieldGet(this, _Query_schema, "f");
    }
    toJSON() {
        const KEYS = ['id', 'label', 'description', 'data', 'error', 'isFetching', 'trigger', 'reset'];
        return KEYS.reduce((obj, key) => {
            obj[key] = this[key];
            return obj;
        }, {});
    }
}
exports.Query = Query;
_Query_schema = new WeakMap(), _Query_context = new WeakMap(), _Query_triggered = new WeakMap(), _Query_disposes = new WeakMap(), _Query_dataBinds = new WeakMap(), _Query_action = new WeakMap(), _Query_paramsRef = new WeakMap(), _Query_emit = new WeakMap(), _Query_currentRequestKey = new WeakMap(), _Query_observableValue = new WeakMap(), _Query_debounceTrigger = new WeakMap(), _Query_instances = new WeakSet(), _Query_innerTrigger = function _Query_innerTrigger(data, options = {}) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        tslib_1.__classPrivateFieldSet(this, _Query_currentRequestKey, Date.now(), "f");
        const key = tslib_1.__classPrivateFieldGet(this, _Query_currentRequestKey, "f");
        try {
            tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").isFetching = true;
            const res = yield tslib_1.__classPrivateFieldGet(this, _Query_action, "f").call(this, data);
            if (key === tslib_1.__classPrivateFieldGet(this, _Query_currentRequestKey, "f")) {
                tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").isFetching = false;
                tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").data = res;
                tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").error = null;
                tslib_1.__classPrivateFieldGet(this, _Query_emit, "f").call(this, `success`, res);
            }
            return res;
        }
        catch (e) {
            if (key === tslib_1.__classPrivateFieldGet(this, _Query_currentRequestKey, "f")) {
                tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").isFetching = false;
                tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").data = null;
                tslib_1.__classPrivateFieldGet(this, _Query_observableValue, "f").error = e;
                tslib_1.__classPrivateFieldGet(this, _Query_emit, "f").call(this, `fail`, e);
            }
            throw e;
        }
    });
}, _Query_resolveParams = function _Query_resolveParams(additionalScope = {}) {
    /**
     * 这里万一其中某个字段计算失败
     * 好像会阻塞其他字段的计算
     * 从而导致 autorun 没有添加依赖
     */
    return (0, runtime_1.mergeDynamic2StaticData)((0, mobx_1.toJS)(tslib_1.__classPrivateFieldGet(this, _Query_paramsRef, "f").current), tslib_1.__classPrivateFieldGet(this, _Query_dataBinds, "f"), {
        $w: tslib_1.__classPrivateFieldGet(this, _Query_context, "f").$w,
        paramsContext: additionalScope,
    });
};
//# sourceMappingURL=query.js.map