import React from 'react';
import PageLoading from '@/lib/PageLoading';
// @ts-ignore
import jwt from 'jsonwebtoken';
import { Session } from '@/utils';
import { history, Location } from 'umi';
import { refreshUserInfo } from './sign-in';
import { useModel } from '@@/plugin-model/useModel';

interface oauthProps {
  location: Location;
}

const OauthInIn: React.FC<oauthProps> = (props) => {
  const { refresh } = useModel('@@initialState');
  const {
    location: { query },
  } = props;
  const { back_url, _k } = query as { back_url: string; _k: string };
  if (!_k) {
    history.push('/403');
  }

  let user = {};
  const decoded = jwt.decode(_k);
  if (decoded) {
    const { authorities } = decoded;
    user = {
      ...decoded,
      roles: authorities,
      access_token: _k,
      refresh_token: 'null',
    };
    Session.init(user);
    refreshUserInfo(() => {
      refresh && refresh();
      setTimeout(() => {
        if (_.isEmpty(back_url)) {
          history.push({
            pathname: '/',
            query,
          });
        } else {
          history.push({
            pathname: back_url,
            query,
          });
        }
      }, 100);
    });
  }

  return <PageLoading />;
};

export default OauthInIn;
