import * as api from '../services/api';

export default {
  namespace: 'approval',
  state: {
    approvalTypeList: [],
    total: 0,
    current: 1
  },

  effects: {
    *getApprovalTypeList(action, sagaEffects) {
      const { call, put } = sagaEffects;
      const approvalTypeList = yield call(
        api.getApprovalTypeList,
        action.payload
      );
      yield put({
        type: 'approvalTypeList',
        payload: approvalTypeList.data.data,
        total: approvalTypeList.data.total,
        current: approvalTypeList.data.pageNumber
      });
    },

    *changeApprovalTempStatus(action, sagaEffects) {
      const { call, put } = sagaEffects;
      const status = yield call(api.changeApprovalTempStatus, action.payload);
      if (status.retType) {
        yield put({ type: 'approvalTempStatus', payload: action.payload });
      }
    }
  },

  reducers: {
    approvalTypeList(state, action) {
      return {
        ...state,
        approvalTypeList: action.payload,
        total: action.total,
        current: action.current
      };
    },

    approvalTempStatus(state, action) {
      let newApprovalTypeList = [];
      newApprovalTypeList = newApprovalTypeList.concat(state.approvalTypeList);
      newApprovalTypeList.forEach(v => {
        if (v.approveTempId === action.payload.approveTempId) {
          v.isActive = action.payload.isActive;
        }
      });

      return {
        ...state,
        approvalTypeList: newApprovalTypeList
      };
    }
  }
};
