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

export default {
  namespace: 'ListHouse',
  state: {
    sourceData: [],
    metas: [],
    houseID: '',
    searchValue: '',
  },
  reducers: {
    setHouseID(state, { payload }) {
      return {
        ...state,
        houseID: payload,
      };
    },
    setSearchValue(state, { payload }) {
      return {
        ...state,
        searchValue: 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 }) {
      const { clear, pFWDiZhi } = payload;
      if (clear === '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, params: { pFWDiZhi } });
      console.info('result');
      console.info(result);
      const meta = yield call(getMeta, coordinate);
      console.info('meta');
      console.info(meta);
      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] } });
    },
  },
};
