import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { PubSub } from 'ray-eventpool';
import Icon from 'amos-icon';
import { TOPO_SWITCH_CONFIG_TOPIC } from './../modelConf/stageConst';
import TopoConfigHeadPanel from './TopoConfigHeadPanel';
import TopoConfigBodyPanel from './TopoConfigBodyPanel';
import TopoConfigDefaultPanel from './TopoConfigDefaultPanel';

/**
 *
 *
 * @class TopoConfigPanel
 * @extends {Component}
 */
class TopoConfigPanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: 1,
      expandIconWidth: '300px'
    };
  }
  componentWillMount() {}

  componentDidMount() {
    this.switchConfig = PubSub.subscribe(TOPO_SWITCH_CONFIG_TOPIC.switchConfig, (e, { selectedKey }) => {
      this.setState({ selectedKey });
    });
  }

  componentWillReceiveProps(nextProps) {
    let { expandIconRight } = this.props;
    if (expandIconRight !== nextProps.expandIconRight) {
      this.setState({ expandIconWidth: nextProps.expandIconRight });
    }
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.switchConfig);
  }

  getTopoPanelByType = () => {
    let { isNodeSelected } = this.props;
    let { selectedKey } = this.state;
    let content = [];
    if (isNodeSelected) {
      content.push(<TopoConfigBodyPanel selectedKey={selectedKey} getImgPath={this.getImgPath} {...this.props} />);
    } else {
      content.push(<TopoConfigDefaultPanel getImgPath={this.getImgPath} {...this.props} />);
    }
    return content;
  };

  getImgPath = (index, collapseKey) => {
    let styleName;
    if (collapseKey.includes(index)) {
      styleName = 'rotate-negative-ninety';
    } else {
      styleName = 'rotate-ninety';
    }
    return <img src={require('./../../../../assets/iot/deviceManage/arrow.png')} alt="" className={styleName} />;
  };

  clickPanel = () => {
    let { expandIconWidth } = this.state;
    let { changePanelWidth } = this.props;
    if (expandIconWidth === '0') {
      expandIconWidth = '300px';
      changePanelWidth(true);
    } else {
      expandIconWidth = '0';
      changePanelWidth(false);
    }
    this.setState({ expandIconWidth });
  };

  render() {
    let { expandIconWidth } = this.state;
    return (
      <div className="topo-config-panel-root">
        <div className="device-config-choose-btn" style={{ right: expandIconWidth }} onClick={this.clickPanel}>
          <Icon icon={expandIconWidth === '0' ? 'right' : 'left'} />
        </div>
        <TopoConfigHeadPanel {...this.props} />
        {this.getTopoPanelByType()}
      </div>
    );
  }
}

TopoConfigPanel.propTypes = {
  isNodeSelected: PropTypes.bool,
  changePanelWidth: PropTypes.func,
  expandIconRight: PropTypes.string
};

TopoConfigPanel.defaultProps = {
  isNodeSelected: false
};

export default TopoConfigPanel;
