import * as reportService from "../../services/reports/comm";
import { routerRedux } from 'dva/router';
import { stringUtils } from '../../utils';

export default {
  namespace: "accReceivable",

  state: {
    list: [],
    total: 0,
    filterParams: {},
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === "/report/accreceivable") {
        }
      });
    },
  },

  effects: {
    *query({ payload }, { call, select, put }) {
      const data = yield call(reportService.accreceivable, payload);
      if (data.success) {
        yield put({
          type: "querySuccess",
          payload: {
            list: data.data.rows,
            total: data.data.total,
            filterParams: payload,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));
      } else {
        throw data;
      }
    },

    *clean({ payload }, { call, put }) {
      yield put({
        type: "updateState",
        payload: {
          list: [],
          total: 0,
          filterParams: {},
        },
      });
    },
  },

  reducers: {
    querySuccess(state, action) {
      const { list, total, filterParams } = action.payload;
      return {
        ...state,
        list,
        total,
        filterParams,
      };
    },

    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
