import { __assign, __awaiter, __generator, __read, __rest, __spreadArray } from "tslib";
import { widgetKeys } from './widgets';
import { app as _app } from '../app/global-api';
import { auth } from '@cloudbase/weda-client';
var loginScope = auth.loginScope, getAccessToken = auth.getAccessToken;
/**
 * All data bindings are generated as functions: (forItems) => any
 * @param {*} dataBinds
 * @param {*} forItems
 */
export 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;
}
/**
 * 对函数进行批量绑定
 * @param {*} funcObj
 * @param {*} context
 */
export 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;
    }, {});
}
export function kebabCase(str) {
    return str.replace(/[A-Z]/g, function (match) {
        return "-".concat(match.toLowerCase());
    });
}
export 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;
}
export 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;
};
export function isPlainObject(src) {
    return Object.prototype.toString.call(src) === '[object Object]';
}
/**
 * 用于处理自定义组件props传参结构，对系统变量进行保留
 */
export function resolveComponentProps(props, isPlainProps) {
    var _a, _b;
    var _c = (_app || {}).__internal__, __internal__ = _c === void 0 ? {} : _c;
    var resolveStaticResourceUrl = (__internal__ || {}).resolveStaticResourceUrl;
    var staticResourceAttribute = props.staticResourceAttribute;
    (_a = staticResourceAttribute === null || staticResourceAttribute === void 0 ? void 0 : staticResourceAttribute.map) === null || _a === void 0 ? void 0 : _a.call(staticResourceAttribute, function (property) {
        var _a;
        if ((_a = props.data) === null || _a === void 0 ? void 0 : _a[property]) {
            props.data[property] = resolveStaticResourceUrl(props.data[property]);
        }
    });
    if (!isPlainProps) {
        return __assign({}, props);
    }
    var _d = props.data, data = _d === void 0 ? {} : _d, _e = props.events, events = _e === void 0 ? [] : _e, restProps = __rest(props, ["data", "events"]);
    var customProps = __assign({}, data);
    var builtinProps = __spreadArray(__spreadArray([
        // react 保留字
        'ref',
        'key',
        'dangerouslySetInnerHTML',
        'className',
        'htmlFor',
        'style',
        'contentEditable',
        // lowcode 保留字
        'events',
        'children',
        '_parentId',
        '_visible',
        '_listeners'
    ], __read(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 = __rest(customProps, ["_selectableBlockEvents"]);
    var _selectableBlockEmit = _selectableBlockEvents.emit;
    var selectableBlockEvents = ((_b = _selectableBlockEvents === null || _selectableBlockEvents === void 0 ? void 0 : _selectableBlockEvents.events) === null || _b === void 0 ? void 0 : _b.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 __assign(__assign(__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); };
            },
        }) });
}
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;
}, {});
export function isSlot(comp) {
    return !comp['module'] && !comp.component;
}
/**
 * 判断是否为作用域插槽
 * 1、根据组件dataForm是否有属性包含 x-slot-scope 属性
 * 2、保持历史穷举法不变
 */
export 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 && map[slot]);
}
export function findLoginPage(app) {
    if (app === void 0) { app = _app; }
    var _a = app.__internal__.getConfig().pages, pages = _a === void 0 ? [] : _a;
    return pages.find(function (item) { return item.type === 'login'; });
}
var _AUTH_CONFIG_CACHE = null;
export function getAuthConfig(app) {
    if (app === void 0) { app = _app; }
    return __awaiter(this, void 0, void 0, function () {
        var res, settingData_1, e_1;
        return __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*/];
            }
        });
    });
}
var _AUTH_CACHE_MAP = {};
function getAccessPermission(app, appId, pageId) {
    return __awaiter(this, void 0, void 0, function () {
        var cacheKey, isAccess, res, e_2;
        return __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];
            }
        });
    });
}
export function checkAnonymous() {
    return __awaiter(this, void 0, void 0, function () {
        var isAnonymous, _a, scope, accessToken, e_3;
        return __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 = __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];
            }
        });
    });
}
/**
 * 检查页面权限
 **/
export function checkAuth(app, appId, $page) {
    return __awaiter(this, void 0, void 0, function () {
        var loginConfigVersion, requestList, _a, isAccess, authConfig, isAnonymous;
        return __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 = __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];
            }
        });
    });
}
export function redirectToLogin(currentPage) {
    return __awaiter(this, void 0, void 0, function () {
        var app, _a, staticResourceDomain, envId, id, clientId, loginConfigVersion, url;
        return __generator(this, function (_b) {
            // 去登录则清空权限缓存。
            _AUTH_CACHE_MAP = {};
            app = _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*/];
        });
    });
}
//# sourceMappingURL=common.js.map