import { routerRedux } from 'dva/router';
import * as payableService from '../../../services/cooperate/finance/payable';
import { formUtils, stringUtils } from "../../../utils";

export default {

  namespace: 'payable',

  state: {
    list: [],
    total: 0,
    mode: 'create',
    accountBtn: true ,
    invBtn: true,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/cooperate/finance/payable') {
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, select, put }) {
      let { accountBtn, invBtn } = yield select(({ payable }) => payable);
      const perms = yield select(({ app }) => app.perms);
      // 角色控制按钮权限
      if (perms) {
        for (const p of perms) {
          if (p.menuId === 'cp_fn_pa_account') {
            accountBtn = false;
          } else if (p.menuId === 'cp_fn_pa_inv') {
            invBtn = false;
          }
        }
      }

      const data = yield call(payableService.query, { ...formUtils.standardiseFormData(payload) });
      let rows = [];
      if (data.data) {
        rows = data.data.rows
      }
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            list: rows,
            total: data.data.total,
            accountBtn,
            invBtn
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));

      } else {
        throw data;
      }
    },
    * getSingle({ payload }, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode,
        },
      });
      yield put(routerRedux.push(`/cooperate/finance/payable/${payload.id}?mode=view`));
    },
    * goToAccount({ payload }, { put }) {
      const checkId = payload.selectedRows[0].checkId;
      yield put(routerRedux.push(`/cooperate/finance/soa/view?id=${checkId}`));
    },
    * goToInv({ payload }, { put }) {
      const invId = payload.selectedRows[0].invId;
      yield put(routerRedux.push(`/cooperate/finance/s-invoice/${invId}?mode=view`));
    },
    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          mode: 'create',
          accountBtn: true ,
          invBtn: true,
        },
      });
    },
  },

  reducers: {

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

  },
};
