import React, { useCallback, useMemo, useRef, useEffect } from 'react';
import IconFont from '../../../../themeComponents/IconFont';
import { computedMenuPosition } from './utils';
import './index.less';

const MENU_WIDTH = 110;
const MENU_HEIGHT = 30;
export default function RectMenu({ x, y, menus, containerDom, onMenuClick }) {
  const { width, height } = useMemo(() => containerDom.getBoundingClientRect(), [containerDom]);
  const size = useMemo(() => ({ w: MENU_WIDTH, h: MENU_HEIGHT * menus.length }), [menus.length]);
  const position = useMemo(() => computedMenuPosition({ width, height, size, position: [x, y] }), [height, size, width, x, y]);
  const domRef = useRef(null);

  const handleCancelB = useCallback(e => e.stopPropagation(), []);

  //防止click事件冒泡到查看器
  useEffect(() => {
    const dom = domRef.current;
    if (dom) {
      dom.addEventListener('mousedown', handleCancelB, false);
      dom.addEventListener('mousemove', handleCancelB, false);
      dom.addEventListener('mouseup', handleCancelB, false);
    }
    return () => {
      if (dom) {
        dom.removeEventListener('mousedown', handleCancelB, false);
        dom.removeEventListener('mousemove', handleCancelB, false);
        dom.removeEventListener('mouseup', handleCancelB, false);
      }
    };
  }, [handleCancelB]);

  const onClickMenu = useCallback(
    (e, item) => {
      e.stopPropagation();
      onMenuClick && onMenuClick(item);
    },
    [onMenuClick]
  );

  return (
    <div className="select-rect-menu-layout" style={{ left: position.x, top: position.y }} ref={domRef}>
      {menus.map(v => (
        <div className="menu-action-item" key={v.pathname} onClick={e => onClickMenu(e, v)}>
          <IconFont type={v.icon} />
          {v.title}
        </div>
      ))}
    </div>
  );
}
