import React from 'react';
import PageLoading from '@/lib/PageLoading';
import { Session } from '@/utils';
import { history, Location, useModel } from 'umi';
import { refreshUserInfo } from './sign-in';
import API from '@/api';
import jwt from 'jsonwebtoken';
import _ from 'lodash'

interface oauthProps {
  location: Location;
}

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

  let user = {};
  let status = '';
  API.AccountService.fakeAccountLogin({
    username: userId,
    password: 'open',
    rememberMe: true,
  }).then(({ success, data }) => {
    if (!success || data.access_token === 'ERROR') {
      status = 'error';
    } else {
      status = 'ok';
      const { access_token, refresh_token, ...rest } = data;
      const decoded = jwt.decode(access_token);
      if (decoded) {
        const { authorities = [] } = decoded;
        user = {
          ...decoded,
          roles: authorities,
          access_token,
          refresh_token,
          ...rest,
        };
        Session.init(user);
      } else {
        status = 'error';
      }
    }

    if (status === 'ok') {
      refreshUserInfo(() => {
        setTimeout(() => {
          refresh && refresh();
          if (_.isEmpty(back_url)) {
            history.push({
              pathname: '/',
              query,
            });
          } else {
            history.push({
              pathname: back_url,
              query,
            });
          }
        }, 100);
      });
    }
  });
  return <PageLoading />;
};

export default OpenidIn;
