"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.redirectToLogin = exports.checkAuth = exports.checkAnonymous = exports.getAuthConfig = exports.findLoginPage = exports.getStaticResourceAttribute = exports.isScopeSlot = exports.isSlot = exports.resolveComponentProps = exports.isPlainObject = exports.isEmptyObj = exports.camelcase = exports.kebabCase = exports.bindFuncObj = exports.resolveDataBinds = void 0;
var tslib_1 = require("tslib");
var widgets_1 = require("./widgets");
var adapter_1 = require("./adapter");
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 && codeContext.$WEAPPS_COMP) {
                fn = fn.bind(codeContext.$WEAPPS_COMP);
            }
            resolvedProps[prop] = fn(forItems, codeContext && 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 '-' + 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;
/**
 * 用于处理自定义组件props传参结构，对系统变量进行保留
 */
function resolveComponentProps(props, isPlainProps) {
    var _a;
    var staticResourceAttribute = props.staticResourceAttribute;
    staticResourceAttribute &&
        staticResourceAttribute.map(function (property) {
            if (props.data && props.data[property]) {
                props.data[property] = getStaticResourceAttribute(props.data[property]);
            }
        });
    if (!isPlainProps) {
        return (0, tslib_1.__assign)({}, props);
    }
    var _b = props.data, data = _b === void 0 ? {} : _b, _c = props.events, events = _c === void 0 ? [] : _c, restProps = (0, tslib_1.__rest)(props, ["data", "events"]);
    var customProps = (0, tslib_1.__assign)({}, data);
    var builtinProps = (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([
        // react 保留字
        'ref',
        'key',
        'dangerouslySetInnerHTML',
        'className',
        'htmlFor',
        'style',
        'contentEditable',
        // lowcode 保留字
        'events',
        'children',
        '_parentId',
        '_visible',
        '_listeners'
    ], (0, tslib_1.__read)(widgets_1.widgetKeys), false), [
        'classList',
        'widgetType',
        'staticResourceAttribute',
        // 小程序保留字
        'id',
        'class',
        'hidden',
        'slot',
    ], false);
    // delete builtin props
    builtinProps.map(function (prop) { return delete customProps[prop]; });
    // 选区events处理
    var _selectableBlockEvents = customProps._selectableBlockEvents, restData = (0, tslib_1.__rest)(customProps, ["_selectableBlockEvents"]);
    var _selectableBlockEmit = _selectableBlockEvents.emit;
    var selectableBlockEvents = ((_a = _selectableBlockEvents === null || _selectableBlockEvents === void 0 ? void 0 : _selectableBlockEvents.events) === null || _a === void 0 ? void 0 : _a.reduce(function (events, item) {
        var propName = item;
        events[propName] = function (e) { return _selectableBlockEmit(propName, e); };
        return events;
    }, {})) || {};
    try {
        _selectableBlockEvents.events = new Proxy(selectableBlockEvents, {
            get: function (obj, prop) {
                return prop in obj ? obj[prop] : function (e) { return _selectableBlockEmit(prop, e); };
            },
        });
    }
    catch (e) {
        console.warn('selectableBlockEvents', selectableBlockEvents);
    }
    return (0, tslib_1.__assign)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, restData), restProps), { _selectableBlockEvents: _selectableBlockEvents, events: new Proxy(events.reduce(function (events, item) {
            var propName = item;
            events[propName] = function (e) { return restProps.emit(propName, e); };
            return events;
        }, {}), {
            get: function (obj, prop) {
                return prop in obj ? obj[prop] : function (e) { return restProps.emit(prop, e); };
            },
        }) });
}
exports.resolveComponentProps = resolveComponentProps;
var SCOPE_SLOT_COMPONENT_LIB = ['tea_basis', 'tea_shop', 'crm_basis'];
var SCOPE_SLOT_MAP = SCOPE_SLOT_COMPONENT_LIB.reduce(function (map, lib) {
    map[lib + ":TableMatching"] = {
        headerSlot: true,
        recordSlot: true,
    };
    map[lib + ":TableExpanded"] = {
        headerSlot: true,
        recordSlot: true,
    };
    map[lib + ":TabsTable"] = {
        headerSlot: true,
        recordSlot: true,
    };
    map[lib + ":Table"] = {
        headerSlot: true,
        recordSlot: true,
    };
    return map;
}, {});
function isSlot(comp) {
    return !comp['module'] && !comp.component;
}
exports.isSlot = isSlot;
function isScopeSlot(comp, slot) {
    var sourceKey = comp.module && comp.component && comp.module + ":" + comp.component;
    var map = SCOPE_SLOT_MAP[sourceKey];
    return map && map[slot];
}
exports.isScopeSlot = isScopeSlot;
function getStaticResourceAttribute(staticUrl) {
    if (/^\//.test(staticUrl)) {
        var _a = (adapter_1.runtime['app'] || {}).domain, domain = _a === void 0 ? '' : _a;
        var url = "https://" + domain + staticUrl;
        return url;
    }
    return staticUrl;
}
exports.getStaticResourceAttribute = getStaticResourceAttribute;
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 (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var res, settingData_1, e_1;
        return (0, 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 (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var cacheKey, isAccess, res, e_2;
        return (0, tslib_1.__generator)(this, function (_a) {
            switch (_a.label) {
                case 0:
                    cacheKey = appId + "-" + 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 (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var isAnonymous, _a, scope, accessToken, e_3;
        return (0, 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 (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var loginPage, requestList, _a, isAccess, authConfig, isAnonymous;
        return (0, tslib_1.__generator)(this, function (_b) {
            switch (_b.label) {
                case 0:
                    loginPage = findLoginPage(app);
                    if ((loginPage === null || loginPage === void 0 ? void 0 : loginPage.id) === $page.id) {
                        return [2 /*return*/, true];
                    }
                    app.showNavigationBarLoading();
                    requestList = [getAccessPermission(app, appId, $page.id)];
                    // 暂时先认为有登录页则自定义登录功能开启且生效
                    if (loginPage) {
                        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 (loginPage && isAnonymous) {
                        if (authConfig.NeedLogin || (!isAccess && authConfig.RejectStrategy === 'to_login')) {
                            redirectToLogin($page);
                            return [2 /*return*/, isAccess];
                        }
                    }
                    if (!isAccess) {
                        app.showToast({
                            title: '页面无访问权限',
                            icon: 'error',
                        });
                    }
                    return [2 /*return*/, isAccess];
            }
        });
    });
}
exports.checkAuth = checkAuth;
function redirectToLogin(currentPage) {
    // 去登录则清空权限缓存。
    _AUTH_CACHE_MAP = {};
    var app = global_api_1.app;
    var loginPage = findLoginPage(app);
    if (!currentPage) {
        currentPage = app.utils.getCurrentPage() || {};
    }
    if ((loginPage === null || loginPage === void 0 ? void 0 : loginPage.id) === currentPage.id) {
        return true;
    }
    if (loginPage) {
        app.redirectTo({
            pageId: loginPage.id,
            params: {
                sourcePageId: currentPage.id,
                sourcePageParams: currentPage.params,
            },
        });
    }
    else {
        app.showToast({
            title: '用户未登录',
            icon: 'error',
        });
    }
}
exports.redirectToLogin = redirectToLogin;
//# sourceMappingURL=common.js.map