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

export default {

  namespace: 'suppInvoiceDetails',

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

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(() => {
        const match = pathToRegexp('/cooperate/finance/offi-invoice/: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(suppInvoiceService.getSingle, payload.id);
      data.data.invAmt = numberUtils.round_half_up_format(data.data.invAmt,2);
      data.data.taxAmt = numberUtils.round_half_up_format(data.data.taxAmt,2);
      data.data.netAmt = numberUtils.round_half_up_format(data.data.netAmt,2);
      if (data.success) {
        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,
      };
    },
  },

};
