import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import * as todoService from '@services/common/todo';
import * as anncService from '@services/message/public';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'dashboard',
  state: {
    todoList: [],
    anncList: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/dashboard') {
          dispatch({ type: 'query' });
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const { menu, user } = yield select(({ app }) => app);

      const todoData = yield call(todoService.queryCardTodo, payload); // 待办统计
      const anncData = yield call(anncService.query, { sortBy: 'publishTime', sortDirection: 'DESC' }); // 公告信息

      if (todoData.success && todoData.data) {
        const todoList = yield call(todoService.resolveTodo, { data: todoData.data, menu, user: user.user });
        yield put({
          type: 'updateState',
          payload: {
            todoList,
          },
        });
      } else {
        throw todoData;
      }

      if (anncData.success && anncData.data) {
        yield put({
          type: 'updateState',
          payload: {
            anncList: anncData.data.rows,
          },
        });
      } else {
        throw anncData;
      }
    },

    * todo({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const { menu } = yield select(({ app }) => app);
      // const { record } = payload;
      const link = yield call(todoService.goto, { menu, ...payload });
      yield put(routerRedux.push(link));
    },
  },

  reducers: {
    updateState(state: object, { payload }: ReduxAction) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
