/**
 * imui.Tab
 * @author jero
 * @date 2016-07-12
 *
 * @todo prefix class
 */
import React, { cloneElement } from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import TabNav from './TabNav';
// @require '../style/index.scss'

export default class Tab extends React.Component {
  static propTypes = {
    prefixCls: PropTypes.string,
    /**
     * 标识第几个 tab 选中
     */
    active: PropTypes.string,
    /**
     * 点击选项时回调
     */
    onTabClick: PropTypes.func,
    /**
     * 选中后回调
     */
    onActive: PropTypes.func,
    /**
     * 选中前事件，回调参数有两个，分别为即将选中的序号和当前选中的序号，返回值为 false 时，阻止选中
     */
    onBeforeActive: PropTypes.func,
    /**
     * 选中样式
     */
    tabType: PropTypes.oneOf(['bottom', 'border', 'top', 'fit']),
    /**
     * 整体样式
     */
    tabScene: PropTypes.oneOf(['center', 'bookmark', 'banner']),
    /**
     * 在切换到其它tab后被隐藏的tab的dom是否需要被销毁还是通过css隐藏
     */
    shouldDestroy: PropTypes.bool,
    style: PropTypes.object,
    className: PropTypes.string,
  };

  static defaultProps = {
    prefixCls: 'im-tab',
    active: '0',
    tabType: 'bottom', // bottom | border | top
    tabScene: '',
    shouldDestroy: true,
    onTabClick() {
    },
    onActive() {
    },
    onBeforeActive() {
    },
  };

  state = {
    active: this.props.active,
  };

  componentWillReceiveProps(nextProps) {
    this.setState({
      active: nextProps.active,
    });
  }

  getActivePanel = () => {
    const { children, shouldDestroy } = this.props;
    const { active } = this.state;
    let newChild = [];

    React.Children.forEach(children, (child, index) => {
      const isActive = +active === index;
      if (shouldDestroy) {
        if (isActive) {
          newChild = child;
        }
      } else {
        // 这是一个很不优雅的实现，由于要保证不产生不兼容的关闭，只能在原基础上这样改了
        newChild.push(cloneElement(child,
          {
            key: index,
            className: classnames({ 'im-tab-panel-hidden': !isActive }),
          }));
      }
    });

    return newChild;
  };

  onActive = (current, prev) => {
    this.setState({
      active: current,
    });
    this.props.onActive(current, prev);
  };

  render() {
    const { children, tabType, tabScene, onTabClick, onBeforeActive, className, style } = this.props;
    const { active } = this.state;
    const activePanel = this.getActivePanel();

    const panels = [];
    children.forEach((child) => {
      if (child instanceof Array) {
        panels.push(...child);
      } else {
        panels.push(child);
      }
    });

    return (
      <div className={classnames('im-tab', className)} style={style}>
        <TabNav
          onTabClick={onTabClick}
          onActive={this.onActive}
          onBeforeActive={onBeforeActive}
          panels={panels}
          active={active}
          tabType={tabType}
          tabScene={tabScene}
        />
        <div className="im-tab-bd">
          {activePanel}
        </div>
      </div>
    );
  }
}
