import React, { Component } from 'react';
import { Form, Button } from 'antd';
import './index.less';

class ActionBar extends Component {
  onClick(key) {
    if (this.props.onAction) this.props.onAction(key);
  }

  getItem(item) {
    const { selectedKeys = [], checkedKeys = [], onlySelect, readOnly } = this.props;
    if (readOnly && !item.readOnly) return '';
    let { disabled } = item;
    if (item.selectNum) disabled = item.selectNum !== selectedKeys.length;
    if (item.checkNum) disabled = item.checkNum !== checkedKeys.length;
    if (item.needCheck) disabled = item.needCheck > checkedKeys.length;
    if (item.needSelect) disabled = item.needSelect > selectedKeys.length;
    if (item.needOnlySelect) disabled = !(onlySelect || onlySelect === 0);
    if (item.render) {
      return item.render(item, disabled);
    }
    return (
      <Button type={item.type} disabled={disabled} onClick={() => this.onClick(item.key)}>
        {item.name}
      </Button>
    );
  }

  render() {
    const { itemList = [], readOnly } = this.props;
    let noRead = false;
    if (readOnly) {
      noRead = true;
      for (let i = 0; i < itemList.length; i += 1) {
        if (itemList[i].readOnly) {
          noRead = false;
          break;
        }
      }
    }
    return (
      <div hidden={noRead} className="action-layout">
        <Form layout="inline">
          {itemList.map((item, index) => {
            return (
              <Form.Item className={item.hidden ? 'hidden' : ''} key={index}>
                {this.getItem(item)}
              </Form.Item>
            );
          })}
        </Form>
      </div>
    );
  }
}

export default ActionBar;
