import { setSessionToken } from '@/access';
import { loginByOauth2Req } from '@/services/auth';
import { to } from '@/utils/promise';
import { history, useModel, useSearchParams } from '@umijs/max';
import { message } from 'antd';
import { useCallback, useEffect } from 'react';
import { flushSync } from 'react-dom';
import styles from './index.less';

function Authorize() {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [searchParams] = useSearchParams();
  const code = searchParams.get('code');
  const redirect = searchParams.get('redirect');

  const fetchUserInfo = useCallback(async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  }, [initialState, setInitialState]);

  // 登录
  const loginByOauth2 = useCallback(async () => {
    const params = {
      code,
    };
    const [res] = await to(loginByOauth2Req(params));
    if (res && res.data) {
      const { access_token, expires_in } = res.data;
      setSessionToken(access_token, access_token, expires_in);
      message.success('登录成功！');
      await fetchUserInfo();
      history.push(redirect || '/');
    }
  }, [fetchUserInfo, redirect, code]);

  useEffect(() => {
    loginByOauth2();
  }, [loginByOauth2]);

  return <div className={styles.container}></div>;
}

export default Authorize;
