import { Toast } from 'antd-mobile';
import { NavigationActions } from 'react-navigation';
import { getData, getMeta } from '../../utils/DataTemplate';
import { datasourceApi } from '../../services/datasource';

export default {
  namespace: 'HouseDetail',
  state: {
    singularData: {},
    enableEdit: false,
    metas: [],
  },
  reducers: {
    setList(state, { payload }) {
      return { ...state, singularData: payload.singularData };
    },
    setMeta(state, { payload }) {
      return {
        ...state,
        metas: payload,
      };
    },
    setEnable(state, { payload: enableEdit }) {
      return { ...state, enableEdit };
    },
  },
  effects: {
    *jumpPage({ payload: id }, { put }) {
      yield put(NavigationActions.navigate({
        routeName: 'HouseDetailEditInfo',
        params: { id },
      }));
    },
    *getHouseDetail({ payload }, { call, put }) {
      const coordinate = {
        containerType: 'module',
        containerName: 'query-DSRFWInfo',
        datasourceName: 'QueryfwDetails',
      };
      const result = yield call(getData, coordinate, { pst: 0, psz: 10, params: { pID: payload } });
      const singularData = result[0];
      yield put({ type: 'setList', payload: { singularData: { ...singularData } } });
      const metas = yield call(getMeta, coordinate);
      yield put({ type: 'setMeta', payload: metas });
    },
    *updateHouseDetail({ payload }, { call, put }) {
      const coordinate = {
        containerType: 'module',
        containerName: 'query-DSRFWInfo',
        datasourceName: 'QueryfwDetails',
      };
      const api = datasourceApi(coordinate);
      console.info({ key: payload.id, params: payload.singularData });
      const result = yield call(api.update, coordinate, { key: payload.id, params: payload.singularData });
      console.info(result);
      Toast.success('修改成功!', 0.5);
      yield put(NavigationActions.navigate({
        routeName: 'HouseList',
      }));
    },
  },
};
