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

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