import { getCaptcha, login } from '../../services/common/login';
import { networkUtils } from '../../utils';

export default {
  namespace: 'login',
  state: {
    loginLoading: false,
    captcha: '',
  },
  effects: {
    * initCaptcha({ payload }, { put, call }) {
      const csrfToken = yield call(networkUtils.csrf);
      if (csrfToken) {
        yield put({
          type: 'getCaptcha',
        });
      }
    },

    * getCaptcha({ payload }, { put, call }) {
      const data = yield call(getCaptcha);
      yield put({
        type: 'updateCaptcha',
        payload: { captcha: `data:image/jpeg;base64,${data.data}` },
      });
    },
    // *fetchPrincipal({}, {put, call}) {
    //   const data = yield call(getPrincipal)
    //   console.log(data)
    //   yield put({
    //     type: 'getCaptcha',
    //     payload: {}
    //   })
    // },
    * login({ payload }, { put, call }) {
      yield put({ type: 'showLoginLoading' });
      const data = yield call(login, payload);
      yield put({ type: 'hideLoginLoading' });
      if (data.success) {
        const { ent_code, login_no, rememberMe } = payload;
        if (rememberMe) {
          localStorage.setItem('login_user', JSON.stringify({ ent_code, login_no, rememberMe }));
        } else {
          localStorage.removeItem('login_user');
        }

        if (data.data === 'NG_INITIAL_PWD') {
          window.location.href = '/changePW';
        } else {
          window.location.href = '/dashboard';
        }

      } else { // 失败则刷新验证码
        yield put({
          type: 'getCaptcha', payload: {},
        });
        throw data;
      }
    },
  },
  reducers: {
    updateCaptcha(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    showLoginLoading(state) {
      return {
        ...state,
        loginLoading: true,
      };
    },
    hideLoginLoading(state) {
      return {
        ...state,
        loginLoading: false,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/login') {
          dispatch({
            type: 'initCaptcha',
          });
        }
      });
    },
  },
};
