import { NavigationActions } from 'react-navigation';
import { getData, getMeta } from '../../utils/DataTemplate';

export default {
  namespace: 'ListHouse',
  state: {
    sourceData: [],
    metas: [],
    houseID: '',
  },
  reducers: {
    setHouseID(state, { payload }) {
      return {
        ...state,
        houseID: payload,
      };
    },
    setList(state, { payload: { arrayData } }) {
      return { ...state, sourceData: [...state.sourceData, ...arrayData] };
    },
    // 下拉刷新用到的，清空列表的数据
    clearList(state) {
      return { ...state, sourceData: [] };
    },
    setMetas(state, { payload }) {
      return { ...state, metas: payload };
    },
  },
  effects: {
    *jumpPage({ payload: id }, { put }) {
      yield put({ type: 'setHouseID', payload: id });
      yield put(NavigationActions.navigate({
        routeName: 'HouseDetail',
      }));
    },
    *getHouseList({ payload }, { take, put, call, select }) {
      if (payload === 'clear') {
        yield put({ type: 'clearList', payload: {} });
      }
      const { sourceData } = yield select(state => state.ListHouse);
      const size = sourceData.length;
      const coordinate = {
        containerType: 'module',
        containerName: 'query-DSRFWInfo',
        datasourceName: 'QueryfwTable',
      };
      const result = yield call(getData, coordinate, { pst: size, psz: 10 });
      const meta = yield call(getMeta, coordinate);
      yield put({ type: 'setMetas', payload: meta });
      for (const row of result) {
        yield put({ type: 'addHouse', payload: row });
        yield take('addHouse/@@end');
      }
    },
    *addHouse({ payload }, { put }) {
      yield put({ type: 'setList', payload: { arrayData: [payload] } });
    },
  },
};
