import { Model, routerRedux } from 'dva';
import { message } from 'antd';
import { Journal, CommunityBasic } from '@/types/common';
import { getCommunityList, getCommunityBasic } from './service';

export interface HomeCommunityModelState {
  refreshingList: boolean;
  loadingList: boolean;
  loadingFinished: boolean;
  errorList: boolean;
  data: Journal[] | null;

  refreshingBasic: boolean;
  errorBasic: boolean;
  info: CommunityBasic | null;

  pageIndex: number;
}

const CommunityModel: Model = {
  namespace: 'homeCommunity',

  state: {
    refreshingList: false,
    loadingList: false,
    loadingFinished: false,
    errorList: false,
    data: null,

    refreshingBasic: false,
    errorBasic: false,
    info: null,

    pageIndex: 1,
  } as HomeCommunityModelState,

  effects: {
    *loadList({ payload: refresh }, { put, call, select }) {
      const {
        refreshingList,
        loadingList,
        pageIndex,
        data,
      } = yield select((state: any) => state.homeCommunity);
      if (refreshingList || loadingList) return;

      yield put({
        type: 'onUpdateState',
        refreshingList: refresh,
        loadingList: !refresh,
        errorList: false,
      });
      try {
        const pageSize = 10;
        const page = refresh ? 1 : pageIndex + 1;
        const list = yield call(getCommunityList, page, pageSize);
        yield put({
          type: 'onUpdateState',
          data: refresh ? list : [...data, ...list],
          refreshingList: false,
          loadingList: false,
          pageIndex: page,
          errorList: false,
          loadingFinished: list.length !== pageSize,
        });
      } catch (e) {
        message.error(e.message);
        yield put({
          type: 'onUpdateState',
          refreshingList: false,
          loadingList: false,
          errorList: true,
        });
      }
    },

    *loadBasic(_, { put, call, select }) {
      const { refreshingBasic } = yield select((state: any) => state.homeCommunity);
      if (refreshingBasic) return;

      yield put({
        type: 'onUpdateState',
        refreshingBasic: true,
        errorBasic: false,
      });
      try {
        const info = yield call(getCommunityBasic);
        yield put({
          type: 'onUpdateState',
          info,
          refreshingBasic: false,
          errorBasic: false,
        });
      } catch (e) {
        yield put({
          type: 'onUpdateState',
          refreshingBasic: false,
          errorBasic: true,
        });
      }
    },
  },

  reducers: {
    onUpdateState(state, payload) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default CommunityModel;
