import { __awaiter } from "tslib";
import { app } from '../../app/global-api';
// import { saveUrlParams } from './cookies';
// 用于三方登录跳转回的页面地址生成：默认为当前页面
function getProviderRedirectURI(providerId) {
    return location.href;
    // return location.origin + location.pathname;
}
export function providerLogin(router, providerId, scope) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            // if (providerId === PORTAL_WECOM_METHOD.id) {
            //   debugger;
            //   try {
            //     await checkWeChatPermission(router.getUrlParams('env_id'));
            //     await portalWecomLogin();
            //   } catch (e) {
            //     app.showToast({
            //       title: e.message,
            //       icon: 'error',
            //     });
            //   }
            //   return;
            // }
            const cloudbase = yield app.cloud.getCloudInstance();
            const auth = cloudbase.authInstance || cloudbase.auth;
            const state = `prd-${providerId}-${Math.random().toString(36).slice(2)}`;
            // 保存当前页面参数，用于授权回跳使用
            // saveUrlParams(state, router);
            const res = yield auth.genProviderRedirectUri({
                provider_id: providerId,
                provider_redirect_uri: getProviderRedirectURI(providerId),
                state,
                scope,
            });
            location.replace(res.uri);
        }
        catch (err) {
            app.showToast({
                title: err.message,
                icon: 'error',
            });
        }
    });
}
export function signInWidthProviderCode(state, code) {
    return __awaiter(this, void 0, void 0, function* () {
        const providerId = state.replace(/prd-(.+)-.+/, '$1');
        const cloudbase = yield app.cloud.getCloudInstance();
        const auth = cloudbase.authInstance || cloudbase.auth;
        const res = yield auth.grantProviderToken({
            provider_id: providerId,
            provider_code: code,
            // provider_redirect_uri: getProviderRedirectURI(providerId),
        });
        return yield auth.signInWithProvider({
            provider_id: providerId,
            provider_token: res.provider_token,
        });
    });
}
