import { app } from '../../app/global-api';
// import { saveUrlParams } from './cookies';

// 用于三方登录跳转回的页面地址生成：默认为当前页面
function getProviderRedirectURI(providerId: string): string {
  return location.href;
  // return location.origin + location.pathname;
}

export async function providerLogin(router, providerId: string, scope?: string) {
  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 = await app.cloud.getCloudInstance();
    const auth = cloudbase.authInstance || cloudbase.auth;

    const state = `prd-${providerId}-${Math.random().toString(36).slice(2)}`;
    // 保存当前页面参数，用于授权回跳使用
    // saveUrlParams(state, router);
    const res = await 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 async function signInWidthProviderCode(state, code) {
  const providerId = state.replace(/prd-(.+)-.+/, '$1');
  const cloudbase = await app.cloud.getCloudInstance();

  const auth = cloudbase.authInstance || cloudbase.auth;

  const res = await auth.grantProviderToken({
    provider_id: providerId,
    provider_code: code,
    // provider_redirect_uri: getProviderRedirectURI(providerId),
  });
  return await auth.signInWithProvider({
    provider_id: providerId,
    provider_token: res.provider_token,
  });
}
