import React, { Component } from 'react';
import { ContextMenu, MenuItem, SubMenu } from 'react-contextmenu';

class ContextMenuLayout extends Component {
  getItem(item, index) {
    const { onTriggerClick } = this.props;
    return (
      <MenuItem key={index} onClick={onTriggerClick} disabled={item.disabled} data={item}>
        {item.name}
      </MenuItem>
    );
  }

  getSubItem(item, index) {
    return (
      <SubMenu key={index} title={item.name}>
        {item.list.map((_item, _index) => {
          return this.getItem(_item, _index);
        })}
      </SubMenu>
    );
  }

  render() {
    const { id, itemTrigger = [], onTriggerShow, onTriggerHide } = this.props;
    if (itemTrigger.length === 0) {
      itemTrigger.push({ key: 'none', disabled: true, name: '无' });
    }
    return (
      <ContextMenu id={id} onShow={onTriggerShow} onHide={onTriggerHide}>
        {itemTrigger.map((item, index) => {
          if (item.type === 'divider') {
            return <MenuItem divider />;
          }
          if (item.list && item.list.length > 0) {
            return this.getSubItem(item, index);
          }
          return this.getItem(item, index);
        })}
      </ContextMenu>
    );
  }
}

export default ContextMenuLayout;
