import { actionTypes } from 'constants/action-types';

export enum MenuActionState {
  NONE = 'none',
  NODE_UP = 'nodeUp',
  NODE_DOWN = 'nodeDown',
  CANVAS_CHANGE = 'canvasChange'
}

export function updateMenuState(state = MenuActionState.NONE) {
  // 切换图层状态
  return async (dispatch) => {
    dispatch({
      type: actionTypes.NODE_SET_STATE,
      payload: { state }
    });
  };
}

export function updateLayerNode(nodes) {
  return async (dispatch) => {
    await dispatch({
      type: actionTypes.NODE_SET_SELECT_LIST_NODES,
      payload: nodes
    });
  };
}

export function updateLayerEdge(edges) {
  return async (dispatch) => {
    await dispatch({
      type: actionTypes.NODE_SET_SELECT_LIST_EDGES,
      payload: edges
    });
  };
}

export function updateLayerNodeEages({ nodes = [], edges = [] }) {
  // 高亮图层节点信息
  return async (dispatch) => {
    await dispatch(updateLayerNode(nodes));
    dispatch(updateLayerEdge(edges));
  };
}

export function setCurrentNode(ids: string | string[]) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.NODE_SET_CURRENT,
      payload: { ids: Array.isArray(ids) ? ids : [ids] }
    });
  };
}

export function clearCurrentNode() {
  return async (dispatch) => {
    await dispatch({
      type: actionTypes.NODE_CLEAR_SELECT_NODE
    });
  };
}

export function nodeManagementPositioning() {
  return async (dispatch, getState) => {
    const { createApp } = getState();
    const { layersSelected, id } = createApp;
    if (Array.isArray(layersSelected) && layersSelected.length === 1) {
      dispatch(setCurrentNode(layersSelected.map((id) => id + '')));
      return id + '';
    }
  };
}

const initialState: {
  nodeState: MenuActionState;
  selectNodes: string[];
  currents: string[];
  selectEdges: string[];
} = {
  nodeState: MenuActionState.NONE,
  selectNodes: [],
  selectEdges: [],
  currents: []
};

export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.NODE_SET_STATE: {
      return {
        ...state,
        nodeState: payload.state
      };
    }
    case actionTypes.NODE_SET_SELECT_LIST_EDGES: {
      return {
        ...state,
        selectEdges: payload
      };
    }
    case actionTypes.NODE_SET_SELECT_LIST_NODES: {
      return {
        ...state,
        selectNodes: payload
      };
    }
    case actionTypes.NODE_CLEAR_SELECT_NODE: {
      return {
        ...state,
        currents: []
      };
    }
    case actionTypes.NODE_SET_CURRENT: {
      return {
        ...state,
        currents: payload.ids
      };
    }

    default:
      return state;
  }
}
