import React, { Component } from 'react';
import { Tabs, Radio } from 'antd';
import './index.less';

class TabLayout extends Component {
  constructor(props) {
    super(props);
    const key = props.itemList && props.itemList.length > 0 ? props.itemList[0].key : '';
    const defaultActiveKey = props.defaultActiveKey || key;
    this.state = { defaultActiveKey };
    if (defaultActiveKey !== props.defaultActiveKey) this.onClick(defaultActiveKey);
  }

  onClick(tab) {
    if (this.props.onChange) this.props.onChange(tab);
  }

  getItem(item) {
    const { button = false } = this.props;
    return button ? (
      <Radio.Button key={item.key} value={item.key}>
        {item.name}
      </Radio.Button>
    ) : (
      <Tabs.TabPane tab={item.name} key={item.key} />
    );
  }

  render() {
    const { button = false, itemList = [] } = this.props;
    const { defaultActiveKey } = this.state;
    return (
      <div className="tab-layout">
        {button ? (
          <Radio.Group
            defaultValue={defaultActiveKey}
            onChange={e => {
              this.onClick(e.target.value);
            }}
            buttonStyle="solid"
          >
            {itemList.map(item => {
              return this.getItem(item);
            })}
          </Radio.Group>
        ) : (
          <Tabs defaultActiveKey={defaultActiveKey} onChange={key => this.onClick(key)}>
            {itemList.map(item => {
              return this.getItem(item);
            })}
          </Tabs>
        )}
      </div>
    );
  }
}

export default TabLayout;
