import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { SidePane, Tabs, Icon } from 'amos-framework';
import BizIcon from './../../common/icon/BizIcon';
import ExplainMouse from './ExplainMouse';
import ExplainKeyboard from './ExplainKeyboard';

const { TabList, Tab, TabPanel } = Tabs;

const delay = 1000;
const times = 10;

class Explain extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeControl: [],
      visible: props.visible || false
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.visible !== nextProps.visible){
      if (nextProps.visible){
        this.open();
        this.autoClosed();
      } else {
        this.closed(true);
      }
    }
  }

  componentWillUnmount() {
    if (this.autoCloseId){
      clearTimeout(this.autoCloseId);
    }
  }

  autoClosed = () => {
    this.autoCloseId = setTimeout(() => {
      this.closed();
    }, times * delay);
  }

  open = () => {
    this.setState({
      visible: true
    });
  }

  closed = (notSync = false) => {
    if (this.autoCloseId){
      clearTimeout(this.autoCloseId);
    }
    this.setState({
      visible: false
    }, () => {
      // 需要同步至父组件
      if (!notSync){
        this.props.onExplainClose && this.props.onExplainClose();
      }
    });
  }

  renderTab(icon, text){
    return (
      <div className="explain-tab">
        <BizIcon icon={icon} />
        <span className="explain-tab-text">{text}</span>
      </div>
    );
  }

  render() {
    const { visible } = this.state;
    if (!visible){
      return null;
    }

    return (
      <SidePane className="operate-explain" top={false} left={false}>
        <div className="operate-explain-header">
          <span className="header-title">控件</span>
          <span className="header-close" onClick={() => this.closed(false)}>
            <Icon icon="cross" />
          </span>
        </div>
        <Tabs closeAnimate>
          <TabList>
            <Tab>{this.renderTab('shubiao', '鼠标')}</Tab>
            <Tab>{this.renderTab('jianpan', '键盘')}</Tab>
          </TabList>
          <TabPanel><ExplainMouse /></TabPanel>
          <TabPanel><ExplainKeyboard /></TabPanel>
        </Tabs>
      </SidePane>
    );
  }
}

Explain.propTypes = {
  visible: PropTypes.bool,
  onExplainClose: PropTypes.func
};

export default Explain;
