import { routerRedux } from 'dva/router';
import { notification } from 'antd';
import { stringify } from 'querystring';
import { fakeAccountLogin, getFakeCaptcha } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import localStorage from '@/utils/localStorage';
import sessionStorage from '@/utils/sessionStorage';

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      if (response.code === 2000) {
        localStorage.set('token', response.data.accessToken);
        localStorage.set('refreshtoken', response.data.refreshToken);
        localStorage.set('atExpire', response.data.atExpire);
        payload.username && sessionStorage.set('account', payload.username);
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
        yield put(routerRedux.replace('/'));
      } else {
        notification.error({ message: response.msg || $t('login.failed') });
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
    *logout(_, { put }) {
      const { redirect } = getPageQuery(); // redirect

      if (window.location.pathname !== '/user/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          }),
        );
        localStorage.clear();
        window.location.reload();
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
