import { routerRedux } from 'dva/router';
import { stringify } from 'querystring';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';

import { fetch, apis } from '../utils/request';

const signin = fetch(apis.user.login)
const signoff = fetch(apis.user.logoff)

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(signin, { data: payload });
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully

      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 {
          window.location.href = redirect;
          return;
        }
      }

      yield put(routerRedux.replace(redirect || '/'));
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

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

      yield call(signoff);

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