"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getConfig = exports.getDatasetProfiles = exports.getDatasourceProfiles = void 0;
var cals_1 = require("@cloudbase/cals");
var common_1 = require("../common");
var generate_1 = require("./generate");
/**
 * 将对象的key的首字母转换为小写
 * { UserName: 'xxx', Id: 'xxxx'} => { userName: 'xxx', id: 'xxx' }
 * 默认只处理最外层, 若 deep 为 true, 则递归处理
 */
function lowercaseKey(obj, deep) {
    if (!obj || typeof obj !== 'object')
        return obj;
    if (Array.isArray(obj))
        return obj.map(function (item) { return lowercaseKey(item, deep); });
    var result = {};
    return Object.keys(obj).reduce(function (acc, key) {
        var smallCase = key.charAt(0).toLowerCase() + key.slice(1);
        var val = obj[key];
        acc[smallCase] = deep ? lowercaseKey(val, deep) : val;
        return acc;
    }, result);
}
/**
 * 标准化从云API获取的数据源结构
 *  1. 将大写转换为小写
 *  2. 将 methods 和 methods 从字符串转换为对象
 */
function standardizeDataSource(ds) {
    var transformed = lowercaseKey(ds, false);
    try {
        var schema = ds.schema;
        if (typeof transformed.schema === 'string') {
            transformed.schema = JSON.parse(transformed.schema);
        }
        if (!transformed.schema || typeof transformed.schema !== 'object') {
            // console.warn(
            //   '[standardizeDataSource]invalid schema',
            //   schema,
            //   'in datasource',
            //   transformed
            // );
            transformed.schema = {};
        }
    }
    catch (error) {
        // console.warn(
        //   '[standardizeDataSource] unable to transform schema',
        //   transformed.schema
        // );
        transformed.schema = {};
    }
    try {
        var methods = ds.methods;
        if (typeof transformed.methods === 'string') {
            transformed.methods = JSON.parse(transformed.methods);
        }
        if (!Array.isArray(transformed.methods)) {
            // console.warn(
            //   '[standardizeDataSource]invalid methods',
            //   methods,
            //   'in datasource',
            //   transformed
            // );
            transformed.methods = [];
        }
    }
    catch (error) {
        // console.warn(
        //   '[standardizeDataSource]unable to transform methods',
        //   transformed.methods
        // );
        transformed.methods = [];
    }
    return transformed;
}
/**
 * 简化数据源描述信息数组, 以供低码运行时使用
 * @param datasources 完整的数据源描述信息数组
 */
function getDatasourceProfiles(datasources) {
    return ((datasources === null || datasources === void 0 ? void 0 : datasources.map(function (item) {
        var ds = standardizeDataSource(item);
        return {
            id: ds.id,
            title: ds.title,
            name: ds.name,
            type: ds.type,
            childDataSourceNames: ds.childDataSourceNames,
            schema: ds.schema,
            methods: ds.methods.map(function (method) {
                return {
                    name: method.name,
                    type: method.type,
                    outParams: method.outParams,
                };
            }),
        };
    })) || []);
}
exports.getDatasourceProfiles = getDatasourceProfiles;
function _generateDynamicDataset(ctx, dataset) {
    var _a;
    var _b = ctx.looseError, looseError = _b === void 0 ? false : _b;
    // 这里的动作实际上是一个有副作用的动作，所以这里进行一个简单的深拷贝
    var result = JSON.parse(JSON.stringify(dataset));
    var state = result.state;
    if (state) {
        for (var key in state) {
            var config = state[key];
            if (config.varType === 'datasource' && ((_a = config.initMethod) === null || _a === void 0 ? void 0 : _a.params)) {
                var params = (0, cals_1.deserializeDynamicMap)(ctx, config.initMethod.params || {});
                if (params && !(0, common_1.isEmptyObj)(params)) {
                    var processed = {};
                    for (var paramKey in params) {
                        var bind = params[paramKey];
                        try {
                            processed[paramKey] = (0, generate_1.generateDataBindForDataset)({
                                propertyPath: paramKey,
                                bindDataPath: bind.value,
                                type: bind.type,
                            });
                        }
                        catch (e) {
                            if (!looseError) {
                                throw e;
                            }
                            else {
                                console.warn("generate dataset ".concat(key, "'s param: ").concat(paramKey, " error:"), e);
                            }
                        }
                    }
                    config.initMethod.params = processed;
                }
            }
        }
    }
    return result;
}
function getDatasetProfiles(cals, apps, options) {
    var result = {};
    if (cals.dataset) {
        result['$global'] = _generateDynamicDataset({ app: cals, looseError: options.looseError }, cals.dataset);
    }
    (apps || []).forEach(function (app) {
        var _a;
        (_a = app.items) === null || _a === void 0 ? void 0 : _a.forEach(function (page) {
            var _a;
            if (page.dataset) {
                result[((_a = app.extra) === null || _a === void 0 ? void 0 : _a.rootPath) ? "".concat(app.extra.rootPath, "/").concat(page.id) : page.id] = _generateDynamicDataset({ app: cals, page: page, looseError: options.looseError }, page.dataset);
            }
        });
    });
    return result;
}
exports.getDatasetProfiles = getDatasetProfiles;
function getConfig(cals, options) {
    var _a, _b, _c, _d, _e;
    return {
        /** 当前是否处于正式发布模式 */
        isProd: false || ((_a = options === null || options === void 0 ? void 0 : options.deployOptions) === null || _a === void 0 ? void 0 : _a.mode) === 'production',
        /** 低码应用ID */
        appID: cals.id || cals.appId || '',
        /** 云开发环境ID */
        envID: ((_b = cals.extra) === null || _b === void 0 ? void 0 : _b.envId) || cals.envId,
        /** 应用端ID */
        tcbClientId: (_c = cals.extra) === null || _c === void 0 ? void 0 : _c.clientId,
        /** 数据源描述对象数组 */
        dataSourceProfiles: getDatasourceProfiles(cals.dataSources || []),
        /**
         * 新的dataset变量配置对象
         *  key 为页面ID(全局为$global), val 为变量配置数组
         */
        datasetProfiles: getDatasetProfiles(cals, [cals], {
            looseError: options === null || options === void 0 ? void 0 : options.looseError,
        }),
        tcbApiOrigin: window['_isPrivate'] && ((_d = cals.extra) === null || _d === void 0 ? void 0 : _d.domain) ? "".concat(location.protocol, "//").concat((_e = cals.extra) === null || _e === void 0 ? void 0 : _e.domain) : '',
        isPrivate: window['_isPrivate'] || false,
    };
}
exports.getConfig = getConfig;
//# sourceMappingURL=datasource.js.map