import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { SidePane } from 'amos-framework';
import BizControlPane from './BizControlPane';
import InnateControlPane from './InnateControlPane';
import { viewController, bizControls } from './../conf';


/**
 * 侧边控制区
 *
 * @class SideControl
 * @extends {Component}
 */
class SideControl extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeControl: []
    };
  }

  /**
   * control 点击，第二次点击则取消
   */
  onBizItemClick = (item, e) => {
    const alreadyActive = this.isActive(item.key);
    const newKeys = this.getActiveControl(item.key, alreadyActive);
    this.setState({
      activeControl: newKeys
    });
    this.props.onItemClick && this.props.onItemClick(item, alreadyActive);
  };

  getActiveControl = (key, alreadyActive) => {
    const { multiple } = this.props;
    const { activeControl } = this.state;
    let newKeys = [];
    if (multiple) {
      newKeys = alreadyActive ? activeControl.filter(ac => ac !== key) : [...activeControl, key];
    } else {
      newKeys = alreadyActive ? [] : [key];
    }
    return newKeys;
  };

  isActive = key => {
    const { activeControl } = this.state;
    return activeControl && activeControl.includes(key);
  };

  render() {
    const { layerConfig } = this.props;
    return (
      <SidePane className="side-control-pane">
        <BizControlPane controls={bizControls} isActive={this.isActive} onItemClick={this.onBizItemClick} />
        <InnateControlPane controls={viewController} layerConfig={layerConfig} />
      </SidePane>
    );
  }
}

SideControl.propTypes = {
  layerConfig: PropTypes.object,
  multiple: PropTypes.bool,
  onItemClick: PropTypes.func,
  write: PropTypes.func,
  toStr: PropTypes.func
};

export default SideControl;
