import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import * as payableService from '../../../services/cooperate/finance/payable';
import { stringUtils } from '../../../utils';
import { numberUtils } from '@utils';

export default {

  namespace: 'payableD',

  state: {
    formData: {},
    mode: 'view',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(() => {
        const match = pathToRegexp('/cooperate/finance/payable/:id').exec(location.pathname);
        if (match) {
          dispatch({ type: 'updateState', payload: { mode: stringUtils.queryURL('mode') } });
          dispatch({ type: 'query', payload: { id: parseFloat(match[1]) } });

        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      const data = yield call(payableService.getSingle, payload.id);
      if (data.success) {
        data.data.amt = numberUtils.round_half_up_format(data.data.amt, 2);
        data.data.openAmt = numberUtils.round_half_up_format(data.data.openAmt, 2);
        data.data.payedAmt = numberUtils.round_half_up_format(data.data.payedAmt, 2);
        yield put({
          type: 'updateState',
          payload: {
            formData: data.data,
          },
        });
      } else {
        throw data;
      }
    },

    * cancel({ payload }, { put }) {
      yield put(routerRedux.goBack());
    },

    * clean({ payload }, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          mode: 'view',
        },
      });
    },
  },

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

};
