import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Popover } from 'amos-framework';
import imgStatic from './../../../consts/imgStatic';

/**
 * 楼层操作
 *
 * @class LayerOperater
 * @extends {Component}
 */
class LayerOperater extends Component {

  constructor(props) {
    super(props);
    this.state = {
      open: false,
      layerActives: props.defaultSelects || []
    };
  }

  onLayerItemClick = (item) => {
    const alreadyActive = this.isActiveLayer(item.key);
    const newKeys = this.getLayerActive(item.key, alreadyActive);
    this.setState({
      layerActives: newKeys
    });
    this.props.onLayerItemClick && this.props.onLayerItemClick(item, alreadyActive);
  }

  onVisibleChange = (open) => {
    this.setState({
      open
    });
  }

  getLayerActive = (key, alreadyActive) => {
    const { layerActives } = this.state;
    return alreadyActive ? layerActives.filter(ac => ac !== key) : [...layerActives, key];
  }

  isActiveLayer = (key) => {
    const { layerActives } = this.state;
    return layerActives && layerActives.includes(key);
  }

  renderContent = () => {
    const { layers } = this.props;
    return (
      <ul>
        {
          layers.map(l => {
            const cls = this.isActiveLayer(l.key) ? 'layer-item control-active' : 'layer-item';
            return <li key={l.key} className={cls} onClick={() => this.onLayerItemClick(l)}>{l.displayName}</li>;
          })
        }
      </ul>
    );
  }

  render() {
    const { open } = this.state;
    return (
      <Popover
        className="layer-popver"
        triggerMode="click"
        align="top"
        direction="right"
        open={open}
        content={this.renderContent()}
      >
        <div className="control-innate-item">
          <img src={imgStatic.contorls.layerController} alt="" />
        </div>
      </Popover>
    );
  }
}

LayerOperater.propTypes = {
  layers: PropTypes.array,
  onLayerItemClick: PropTypes.func,
  defaultSelects: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.string),
    PropTypes.string
  ])
};

export default LayerOperater;
