import * as suppInvoiceService from '../../../services/cooperate/finance/suppInvoice';
import { routerRedux } from 'dva/router';
import { stringUtils } from '../../../utils';

export default {

  namespace: 'suppInvoiceForm',

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

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

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

      const data = yield call(suppInvoiceService.query, payload);
      data.data.rows && data.data.rows.map(i => {
        i.invAmt = parseFloat(i.invAmt).toFixed(2);
        i.taxAmt = parseFloat(i.taxAmt).toFixed(2);
        i.netAmt = parseFloat(i.netAmt).toFixed(2);
      });
      // console.log("=======data", data.data.rows)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            list: data.data.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/offi-invoice/${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 };
    },


  },
}
