text: import { history } from 'umi';
  import { stringify } from 'qs';
  import { fakeAccountLogin } from '@/services/api';
  import { setAuthority } from '@/utils/authority';
  import { getPageQuery } from '@/utils/utils';
  import { reloadAuthorized } from '@/utils/Authorized';
  
  export default {
    namespace: 'login',
  
    state: {
      status: undefined,
    },
  
    effects: {
      *login({ payload }, { call, put }) {
        const response = yield call(fakeAccountLogin, payload);
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
        // Login successfully
        if (response.token) {
          const { user, token } = response;
          localStorage.setItem('cello-token', token);
          yield put({
            type: 'changeLoginStatus',
            payload: {
              status: 'ok',
              currentAuthority: user.role || 'user',
              type: 'account',
            },
          });
          reloadAuthorized();
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params;
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              redirect = null;
            }
          }
          yield put(history.replace(redirect || '/'));
          // TODO: find better method to reload token for request, reload page to obtain the token from storage
          window.location.reload();
        }
      },
  
      *logout(_, { put }) {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currentAuthority: 'guest',
          },
        });
        reloadAuthorized();
        const { redirect } = getPageQuery();
        // redirect
        if (window.location.pathname !== '/user/login' && !redirect) {
          yield put(
            history.replace({
              pathname: '/user/login',
              search: stringify({
                redirect: window.location.href,
              }),
            })
          );
        }
      },
    },
  
    reducers: {
      changeLoginStatus(state, { payload }) {
        setAuthority(payload.currentAuthority);
        return {
          ...state,
          status: payload.status,
          type: payload.type,
        };
      },
    },
  };
  