"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDataContext = exports.redirectToLogin = exports.checkAuth = exports.checkAnonymous = exports.getAuthConfig = exports.findLoginPage = exports.isScopeSlot = exports.isSlot = exports.isPlainObject = exports.isEmptyObj = exports.camelcase = exports.kebabCase = exports.bindFuncObj = exports.resolveDataBinds = void 0;
var tslib_1 = require("tslib");
var global_api_1 = require("../app/global-api");
var weda_client_1 = require("@cloudbase/weda-client");
var loginScope = weda_client_1.auth.loginScope, getAccessToken = weda_client_1.auth.getAccessToken;
/**
 * All data bindings are generated as functions: (forItems) => any
 * @param {*} dataBinds
 * @param {*} forItems
 */
function resolveDataBinds(dataBinds, forItems, codeContext, scopeContext, throwError, dataContext) {
    var resolvedProps = {};
    for (var prop in dataBinds) {
        var fn = dataBinds[prop];
        try {
            if (codeContext === null || codeContext === void 0 ? void 0 : codeContext.$WEAPPS_COMP) {
                fn = fn.bind(codeContext.$WEAPPS_COMP);
            }
            resolvedProps[prop] = fn(forItems, codeContext === null || codeContext === void 0 ? void 0 : codeContext.event, dataContext);
        }
        catch (e) {
            console.error('Error resolving data binding', prop, dataBinds[prop], e);
            if (throwError) {
                throw e;
            }
        }
    }
    return resolvedProps;
}
exports.resolveDataBinds = resolveDataBinds;
/**
 * 对函数进行批量绑定
 * @param {*} funcObj
 * @param {*} context
 */
function bindFuncObj(funcObj, context) {
    if (funcObj === void 0) { funcObj = {}; }
    return Object.keys(funcObj).reduce(function (obj, fnName) {
        var _a, _b;
        obj[fnName] = (_b = (_a = funcObj[fnName]) === null || _a === void 0 ? void 0 : _a.bind) === null || _b === void 0 ? void 0 : _b.call(_a, context);
        return obj;
    }, {});
}
exports.bindFuncObj = bindFuncObj;
function kebabCase(str) {
    return str.replace(/[A-Z]/g, function (match) {
        return "-".concat(match.toLowerCase());
    });
}
exports.kebabCase = kebabCase;
function camelcase(str, firstUpperCase) {
    if (firstUpperCase === void 0) { firstUpperCase = false; }
    str = str.replace(/[_-]([a-z])/g, function (l) {
        return l[1].toUpperCase();
    });
    if (firstUpperCase)
        str = str.charAt(0).toUpperCase() + str.slice(1);
    return str;
}
exports.camelcase = camelcase;
var isEmptyObj = function (obj) {
    if (!isPlainObject(obj)) {
        return false;
    }
    for (var i in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, i)) {
            return false;
        }
    }
    return true;
};
exports.isEmptyObj = isEmptyObj;
function isPlainObject(src) {
    return Object.prototype.toString.call(src) === '[object Object]';
}
exports.isPlainObject = isPlainObject;
var SCOPE_SLOT_COMPONENT_LIB = ['tea_basis', 'tea_shop', 'crm_basis'];
var SCOPE_SLOT_MAP = SCOPE_SLOT_COMPONENT_LIB.reduce(function (map, lib) {
    map["".concat(lib, ":TableMatching")] = {
        headerSlot: true,
        recordSlot: true,
    };
    map["".concat(lib, ":TableExpanded")] = {
        headerSlot: true,
        recordSlot: true,
    };
    map["".concat(lib, ":TabsTable")] = {
        headerSlot: true,
        recordSlot: true,
    };
    map["".concat(lib, ":Table")] = {
        headerSlot: true,
        recordSlot: true,
    };
    return map;
}, {});
function isSlot(comp) {
    return !comp['module'] && !comp.component;
}
exports.isSlot = isSlot;
/**
 * 判断是否为作用域插槽
 * 1、根据组件dataForm是否有属性包含 x-slot-scope 属性
 * 2、保持历史穷举法不变
 */
function isScopeSlot(comp, slot, context) {
    var _a, _b;
    var sourceKey = comp.module && comp.component && "".concat(comp.module, ":").concat(comp.component);
    var hasXslotScope = false;
    try {
        var dataForm_1 = (_b = (_a = context === null || context === void 0 ? void 0 : context.componentsInfoMap) === null || _a === void 0 ? void 0 : _a[sourceKey]) === null || _b === void 0 ? void 0 : _b.dataForm;
        if (typeof dataForm_1 === 'object') {
            hasXslotScope = Object.keys(dataForm_1).some(function (prop) { var _a; return slot.startsWith("".concat(prop, "_")) && ((_a = dataForm_1[prop]) === null || _a === void 0 ? void 0 : _a['x-slot-scope']); });
        }
    }
    catch (e) { }
    var map = SCOPE_SLOT_MAP[sourceKey];
    return hasXslotScope || (map === null || map === void 0 ? void 0 : map[slot]);
}
exports.isScopeSlot = isScopeSlot;
function findLoginPage(app) {
    if (app === void 0) { app = global_api_1.app; }
    var _a = app.__internal__.getConfig().pages, pages = _a === void 0 ? [] : _a;
    return pages.find(function (item) { return item.type === 'login'; });
}
exports.findLoginPage = findLoginPage;
var _AUTH_CONFIG_CACHE = null;
function getAuthConfig(app) {
    if (app === void 0) { app = global_api_1.app; }
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var res, settingData_1, e_1;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (_AUTH_CONFIG_CACHE) {
                        return [2 /*return*/, _AUTH_CONFIG_CACHE];
                    }
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, app.cloud.callWedaApi({
                            action: 'DescribeRuntimeResourceStrategy',
                            data: {
                                ResourceType: 'app',
                                ResourceId: app.id,
                            },
                        })];
                case 2:
                    res = _a.sent();
                    settingData_1 = {};
                    // 云api不支持map只能传字符串，需要转换
                    res.forEach(function (item) {
                        settingData_1[item.Key] = ['AllowRegister', 'NeedLogin'].includes(item.Key) ? item.Value === '1' : item.Value;
                    });
                    _AUTH_CONFIG_CACHE = settingData_1;
                    return [2 /*return*/, _AUTH_CONFIG_CACHE];
                case 3:
                    e_1 = _a.sent();
                    return [2 /*return*/, {
                            NeedLogin: false,
                            RejectStrategy: 'show_warning',
                        }];
                case 4: return [2 /*return*/];
            }
        });
    });
}
exports.getAuthConfig = getAuthConfig;
var _AUTH_CACHE_MAP = {};
function getAccessPermission(app, appId, pageId) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var cacheKey, isAccess, res, e_2;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    cacheKey = "".concat(appId, "-").concat(pageId);
                    if (_AUTH_CACHE_MAP[cacheKey] !== undefined) {
                        return [2 /*return*/, _AUTH_CACHE_MAP[cacheKey]];
                    }
                    isAccess = false;
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, app.cloud.callWedaApi({
                            action: 'DescribeResourcesPermission',
                            data: {
                                ResourceType: "app",
                                ResourceIdList: [cacheKey],
                                AppResourceId: appId,
                            },
                        })];
                case 2:
                    res = _a.sent();
                    if (Array.isArray(res) && res.length > 0) {
                        isAccess = !!res[0].IsAccess;
                    }
                    _AUTH_CACHE_MAP[cacheKey] = isAccess;
                    return [3 /*break*/, 4];
                case 3:
                    e_2 = _a.sent();
                    console.warn('getAccessPermission', e_2);
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/, isAccess];
            }
        });
    });
}
function checkAnonymous() {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var isAnonymous, _a, scope, accessToken, e_3;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    isAnonymous = true;
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, Promise.all([loginScope(), getAccessToken()])];
                case 2:
                    _a = tslib_1.__read.apply(void 0, [_b.sent(), 2]), scope = _a[0], accessToken = _a[1].accessToken;
                    if (accessToken && scope !== 'anonymous') {
                        isAnonymous = false;
                    }
                    return [3 /*break*/, 4];
                case 3:
                    e_3 = _b.sent();
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/, isAnonymous];
            }
        });
    });
}
exports.checkAnonymous = checkAnonymous;
/**
 * 检查页面权限
 **/
function checkAuth(app, appId, $page) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var loginConfigVersion, requestList, _a, isAccess, authConfig, isAnonymous;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    app.showNavigationBarLoading();
                    loginConfigVersion = app.__internal__.getConfig().loginConfigVersion;
                    requestList = [getAccessPermission(app, appId, $page.id)];
                    // 有登录配置版本号时，才拉取自定义登录配置进行校验
                    if (loginConfigVersion) {
                        requestList.push(getAuthConfig(app));
                        requestList.push(checkAnonymous());
                    }
                    return [4 /*yield*/, Promise.all(requestList)];
                case 1:
                    _a = tslib_1.__read.apply(void 0, [_b.sent(), 3]), isAccess = _a[0], authConfig = _a[1], isAnonymous = _a[2];
                    app.hideNavigationBarLoading();
                    if (loginConfigVersion && isAnonymous) {
                        if (authConfig.NeedLogin || (!isAccess && authConfig.RejectStrategy === 'to_login')) {
                            redirectToLogin($page);
                            return [2 /*return*/, false];
                        }
                    }
                    if (!isAccess) {
                        app.showToast({
                            title: '页面无访问权限',
                            icon: 'error',
                        });
                    }
                    return [2 /*return*/, isAccess];
            }
        });
    });
}
exports.checkAuth = checkAuth;
function redirectToLogin(currentPage) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var app, _a, staticResourceDomain, envId, id, clientId, loginConfigVersion, url;
        return tslib_1.__generator(this, function (_b) {
            // 去登录则清空权限缓存。
            _AUTH_CACHE_MAP = {};
            app = global_api_1.app;
            _a = app.__internal__.getConfig(), staticResourceDomain = _a.staticResourceDomain, envId = _a.envId, id = _a.id, clientId = _a.clientId, loginConfigVersion = _a.loginConfigVersion;
            // 有登录配置版本号时，自定义登录开启，则跳转到自定义登录页面
            if (loginConfigVersion) {
                url = "".concat(location.origin, "/__auth/?redirect_uri=").concat(encodeURIComponent(location.href), "&app_id=").concat(id, "&env_id=").concat(envId, "&client_id=").concat(clientId, "&config_version=").concat(loginConfigVersion, "&s_domain=").concat(staticResourceDomain);
                app.redirectTo({
                    mode: 'web',
                    params: {},
                    url: url,
                });
            }
            else {
                app.showToast({
                    title: '用户未登录',
                    icon: 'error',
                });
            }
            return [2 /*return*/];
        });
    });
}
exports.redirectToLogin = redirectToLogin;
function generateDataContext(widget) {
    var dataContext = {};
    var _loop_1 = function () {
        var current = widget;
        // 此处采用代理的方式，是为了可以获取到最新的 _scope.dataContext 防止 dataContext 引用被重新赋值
        Object.defineProperty(dataContext, current._scope.id, {
            get: function () {
                return current._scope.dataContext;
            },
        });
        widget = widget.parent;
    };
    while (widget === null || widget === void 0 ? void 0 : widget._scope) {
        _loop_1();
    }
    return dataContext;
}
exports.generateDataContext = generateDataContext;
//# sourceMappingURL=common.js.map