import { Model, routerRedux } from "dva";
import { message } from 'antd';
import { Estate, PageState } from '@/types/common';
import { getEstateDetail } from './service';
import { isDev } from '@/utils/utils';

export enum PageTab {
  Record = '0',
  Detail = '1',
}

export interface EstateModelState {
  tab: PageTab.Record;
  estate?: Estate;
  pageState: PageState;
}

const initState: EstateModelState = {
  tab: PageTab.Record,
  estate: undefined,
  pageState: PageState.Pending,
};

const model: Model = {
  namespace: 'estate',

  state: initState,

  effects: {
    *changeTab({ payload: tab }, { put }) {
      yield put({ type: 'onUpdateState', payload: { tab } });
    },

    *load({ payload }, { put, call }) {
      if (!payload) {
        yield put(routerRedux.goBack());
        return;
      }

      yield put({
        type: 'onUpdateState',
        payload: { pageState: PageState.Pending },
      });
      try {
        const estate = yield call(getEstateDetail, payload.id);
        if (payload.id === estate.id || isDev) { // TODO: Remember to remove this
          yield put({
            type: 'onUpdateState',
            payload: {
              pageState: PageState.Success,
              estate,
              tab: PageTab.Record,
            },
          });
        }
      } catch (e) {
        message.error(e.message);
        yield put({
          type: 'onUpdateState',
          payload: { pageState: PageState.Failure },
        });
      }
    },

    *clear(_, { put }) {
      yield put({ type: 'onUpdateState', payload: initState });
      if (!isDev) {
        yield put({ type: 'ext/onUpdateState', payload: { estateExt: undefined } });
      }
    },
  },

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

export default model;
