import * as planService from '../../services/plan/requirement';

export default {
  namespace: 'plan',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
    filterParams: {},
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/plan-mgmt/requirement-mgmt') {
          // TODO
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, select, put }) {
      const filterParams = yield select(({ plan }) => plan.filterParams);

      if (payload && payload.cccCode && typeof payload.cccCode !== 'string') {
        if (payload.cccCode.length > 0) {
          payload.cccCode.map((code, index) => {
            const key = 'c' + (index + 1) + 'Code';
            payload[key] = code;
          });
        } else {
          Object.keys(payload).map((key) => {
            if (key.indexOf('Code') === 2) {
              payload[key] = '';
            }
          });
        }
      }

      // console.log(filterParams, payload);
      const data = yield call(planService.query, { ...filterParams, ...payload });
      if (data.success) {
        if (data.data.rows) {
          data.data.rows.map(item => {
            item.category = `${item.c1Name}>${item.c2Name}>${item.c3Name}`;
          })
        }

        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            filterParams: { ...filterParams, ...payload },
          },
        });
      } else {
        throw data;
      }
    },
    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          mode: 'create',
          filterParams: {},
        },
      });
    },
  },

  reducers: {
    querySuccess(state, action) {
      const { list, total, filterParams } = action.payload;
      return {
        ...state,
        list,
        total,
        filterParams,
      };
    },
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
