import { NavigationActions } from 'react-navigation';
import { login, userInfo } from '../services/login';
import { errors } from '../utils/error';
import { setToken, setUser } from '../utils/auth';


export default {
  namespace: 'login',
  state: {},
  reducers: {
  },
  effects: {
    *login({ payload }, { call, put }) { // 这里的put 代表 跟dispatch一样的功能，只是在effects中叫做put
      const payloads = { ...payload, type: 'userName', authType: 'password' };
      console.info(payloads);
      const result = yield call(login, payloads);
      const { tokenId, authResponse, remainedAuthRequirements } = result;
      if (authResponse.status !== 'authed' && authResponse.status !== 'skipped') {
        throw errors.wrongPassword();
      }
      console.log(authResponse);
      const { requirements } = remainedAuthRequirements;
      if (requirements.length > 0) {
        throw errors.unsupportedAuthType(requirements);
      }
      console.log(requirements);
      yield call(setToken, tokenId);// 这里的yield ,跟C#中的await一样
      const uInfo = yield call(userInfo);
      console.log(uInfo);
      yield call(setUser, uInfo.id, uInfo.name); // 保存用户名密码
      yield put(NavigationActions.navigate({
        routeName: 'Main',
      }));
    },
  },
  subscriptions: {},
};
