import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { utils } from 'amos-tool';
import { Scrollbars } from 'amos-framework';
import TabItem from './TabItem';
import TabContentItem from './TabContentItem';


class NavTab extends Component {

  static propTypes = {
    activeTab: PropTypes.string,
    tabAll: PropTypes.array,
    onTabChange: PropTypes.func,
    onItemClick: PropTypes.func,
    onFavorite: PropTypes.func
  };

  static defaultProps = {
    tabAll: [],
    onTabChange(){}
  };

  constructor(props) {
    super(props);
  }

  onTabChange = (itemKey, item) => {
    this.props.onTabChange(itemKey, item);
  }

  onFavorite = (isFav) => {

  }

  generateContentList = () => {
    const { activeTab, tabAll } = this.props;
    if (utils.isEmpty(tabAll)){
      return [];
    } else {
      const result = tabAll.filter(ta => ta.key === activeTab);
      if (utils.isEmpty(result)){
        return [];
      }
      return result[0].children;
    }
  }

  renderTabAll = (tabList) => {
    const { activeTab } = this.props;
    return tabList.map(tl => {
      const active = tl.key === activeTab;
      return (
        <TabItem
          key={tl.key}
          itemKey={tl.key}
          text={tl.text}
          count={(tl.children || []).length}
          active={active}
          onTabChange={(key) => this.onTabChange(key, tl)}
        />
      );
    });
  }

  renderTabContent = (contentList) => {
    const { onFavorite, onItemClick } = this.props;
    if (!contentList || contentList.length === 0) {
      return <div style={{ textAlign: 'center' }}>暂无应用</div>;
    }
    return contentList.map(cl => (
      <TabContentItem
        key={cl.key}
        item={cl}
        funcIcon={cl.funcIcon}
        title={cl.title}
        onItemClick={() => onItemClick(cl.key, cl)}
        onFavorite={(isFavorite) => onFavorite(isFavorite, cl)}
      />
    ));
  }

  render() {

    const { tabAll } = this.props;
    const contentList = this.generateContentList();

    return (
      <div className="amos-category-tab">
        <ul className="nav-tab-all">
          {this.renderTabAll(tabAll)}
        </ul>
        <div className="nav-tab-content">
          <Scrollbars>
            {this.renderTabContent(contentList)}
          </Scrollbars>
        </div>
      </div>
    );
  }
}

NavTab.propTypes = {

};

export default NavTab;
