import { request } from 'utils/fetch';
import { api } from '@/constants/config.js';
import { actionTypes } from 'constants/action-types';
import { getScreen } from './screen';
import { getFilters } from './filter';

export function getData({ screenId, panelId, stateId }) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.PANEL_DETAIL_GET_START,
    });

    const filterResult = await dispatch(getFilters(screenId));

    if (!filterResult) {
      dispatch({
        type: actionTypes.PANEL_DETAIL_GET_FAILURE,
      });
      return;
    }

    // const result: Resulf | null = await http.get(api.panelGet, { id: panelId }); // HACK切换到了v5
    const result = await request(api.panelGet, { id: panelId });

    if (result) {
      const screenResult = await dispatch(getScreen(stateId));

      if (screenResult) {
        dispatch({
          type: actionTypes.PANEL_DETAIL_GET_SUCCESS,
          payload: {
            panelId: panelId,
            stateId: stateId,
            name: result.name,
            config: result.config,
          },
        });
      } else {
        dispatch({
          type: actionTypes.PANEL_DETAIL_GET_FAILURE,
        });
      }
    } else {
      dispatch({
        type: actionTypes.PANEL_DETAIL_GET_FAILURE,
      });
    }
  };
}

const initialState = {
  loading: true,
  panelId: null,
  stateId: null,
  name: '',
  config: {},
};

export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.PANEL_DETAIL_GET_START: {
      return { ...state, loading: true };
    }

    case actionTypes.PANEL_DETAIL_GET_SUCCESS: {
      return { ...state, ...payload, loading: false };
    }

    case actionTypes.PANEL_DETAIL_GET_FAILURE: {
      return { ...state, loading: false };
    }
    default:
      return state;
  }
}
