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

export default {
  namespace: 'QSInfo',
  state: {
    sourceData: [],
    metas: [],
    QSID: '',
    searchValue: '',
  },
  reducers: {
    setQSID(state, { payload }) {
      return {
        ...state,
        QSID: 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 };
    },
    setSearchValue(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        searchValue: payload,
      };
    },
  },
  effects: {
    *jumpPage({ payload: id }, { put }) {
      yield put({ type: 'setQSID', payload: id });
      yield put(NavigationActions.navigate({
        routeName: 'quanshuInfoDetail',
        params: { id },
      }));
    },
    *getQSList({ payload }, { take, put, call, select }) {
      const { clear, pQuanShuBianMa } = payload;
      // console.info(payload);
      if (clear === 'clear') {
        yield put({ type: 'clearList', payload: {} });
      }
      const { sourceData } = yield select(state => state.QSInfo);
      const size = sourceData.length;
      const coordinate = {
        containerType: 'module',
        containerName: 'query-DSRFWQuanShu',
        datasourceName: 'QueryfwqsTable',
      };
      const result = yield call(getData, coordinate, { pst: size, psz: 10, params: { pQuanShuBianMa } });
      const meta = yield call(getMeta, coordinate);
      yield put({ type: 'setMetas', payload: meta });
      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] } });
    },
  },
};
