import { apiUpdageBusinessMsgStatus } from '@/services/messageReminder';

const MessageReminderModel = {
  namespace: 'messageReminder',
  state: {
    unReadCount: 0, // 未读总数
    unReadData: [], // 未读数据
  },
  effects: {
    *setUnReadData({ payload, options }, { put, call }) {
      yield setTimeout(() => {
        put({
          type: 'setUnReadData',
          payload,
          options,
        });
      });
    },
    *setMarkRead({ payload, options = {} }, { put, call }) {
      const { setLoading } = options;
      if (setLoading) {
        setLoading(true);
      }
      const res = yield call(apiUpdageBusinessMsgStatus, payload);
      // console.log(res)
      if (setLoading) {
        setLoading(false);
      }
      if (res.code !== '0000') {
        return;
      }
      if (
        Object.hasOwnProperty.call(options, 'callback') &&
        typeof options.callback === 'function'
      ) {
        options.callback(res);
      }
      yield put({
        type: 'updateUnReadData',
        payload,
        options,
      });
    },
  },
  reducers: {
    setUnReadData(state, { payload, options = {} }) {
      const currentData = [...payload, ...state.unReadData];
      let unReadCount = state.unReadCount + 1;
      if (options.unReadCount || options.unReadCount === 0) {
        // eslint-disable-next-line prefer-destructuring
        unReadCount = options.unReadCount;
      }

      return { ...state, unReadData: currentData, unReadCount };
    },
    updateUnReadData(state, { payload, options = {} }) {
      // 删除已读的数据
      const currentData = state.unReadData.filter(message => !payload.idsList.includes(message.id));
      // 重置当前未读数量
      const unReadCount = currentData.length; // state.unReadCount - (options.readCount || payload.idsList.length || 1)
      return { ...state, unReadCount, unReadData: currentData };
    },
  },
};
export default MessageReminderModel;
