import http from 'utils/fetch';
import { api } from 'constants/config';
import { actionTypes } from 'constants/action-types';
import { AppState } from './app.types';
import message from 'components/message';

export function getApps() {
  return async (dispatch) => {
    const result = await http.get(api.appList);

    if (result) {
      dispatch({
        type: actionTypes.APP_GET_LIST_SUCCESS,
        payload: result
      });
    }
  };
}

export function getApp(id) {
  return async (dispatch) => {
    const result = await http.get(api.appGet, { id });

    if (result) {
      dispatch({
        type: actionTypes.APP_GET_SUCCESS,
        payload: result
      });
    }
  };
}

export function publishScreenToApp({ screenId, appId, publish }) {
  return async (dispatch, getState) => {
    const { screens, screensById } = getState();
    const result = await http.post(
      api.appPublish,
      { screenId, appId, publish },
      {
        error: (err) => {
          err?.message && message.error(err.message.replace('该租户', '当前产品版本'));
        }
      }
    );
    if (result) {
      // 更新列表页数据
      if (screens.list.length) {
        const screen = screens.list.find((d) => d.screenId === screenId);
        let apps = screen.apps;
        apps = publish ? apps.concat(appId) : apps.filter((d) => d !== appId);

        dispatch({
          type: actionTypes.SCREEN_LIST_UPDATE_SUCCESS,
          payload: {
            id: screenId,
            apps
          }
        });
      }

      // 更新编辑页数据
      if (screensById[screenId]) {
        const screen = screensById[screenId];
        let apps = screen.apps;
        apps = publish ? apps.concat(appId) : apps.filter((d) => d !== appId);

        dispatch({
          type: actionTypes.SCREEN_UPDATE_SUCCESS,
          payload: {
            id: screenId,
            apps
          }
        });
      }
    }
    return result;
  };
}

const initialState: AppState = {
  list: []
};

export default function reducer(state = initialState, { type, payload }): AppState {
  switch (type) {
    case actionTypes.APP_GET_LIST_SUCCESS: {
      return { ...state, list: payload };
    }
    default:
      return state;
  }
}
