import React, { useState, useEffect } from 'react';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';

interface IProps {
  contextStatus: any;
  contextMenuNode: any;
  canBeginRun: any;
  handleRun: () => void;
  handleClose: () => void;
  handleRunBeginNode: () => void;
  handleRunEndNode: () => void;
  handleOpenTable: () => void;
  handleOpenLog: () => void;
}

const ContextMenu: React.FC<IProps> = props => {
  const {
    contextStatus,
    contextMenuNode,
    handleClose,
    handleRun,
    handleRunBeginNode,
    handleRunEndNode,
    handleOpenTable,
    handleOpenLog,
    canBeginRun
  } = props;

  const [contextMenu, setContextMenu] = useState<{
    mouseX: number;
    mouseY: number;
  } | null>(null);

  useEffect(() => {
    setContextMenu(contextStatus);
  }, [contextStatus]);

  return (
    <Menu
      open={contextMenu !== null}
      onClose={handleClose}
      anchorReference="anchorPosition"
      anchorPosition={
        contextMenu !== null
          ? {
              top: contextMenu.mouseY,
              left: contextMenu.mouseX
            }
          : undefined
      }
    >
      {canBeginRun && <MenuItem onClick={handleRun}>执行</MenuItem>}
      <MenuItem onClick={handleRunEndNode}>执行至此</MenuItem>
      {canBeginRun && (
        <MenuItem onClick={handleRunBeginNode}>从此处开始执行</MenuItem>
      )}
      {['success', 'failed'].includes(contextMenuNode?.data?.status) && (
        <MenuItem onClick={handleOpenLog}>查看执行日志</MenuItem>
      )}
      {contextMenuNode?.data?.status === 'success' && (
        <MenuItem onClick={handleOpenTable}>查看结果表</MenuItem>
      )}
    </Menu>
  );
};

export default ContextMenu;
