import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Popover } from 'amos-framework';
import { utils } from 'amos-tool';
import BizIcon from '../../common/icon/BizIcon';
import imgStatic from './../../../consts/imgStatic';

const ControlTrigger = ({ onClick, icon, label, cls, showLabel, changeLabelState, position } = {}) => {
  return (
    <li className={cls} onClick={onClick} onMouseOver={(e) => changeLabelState(e, 'over')} onMouseOut={(e) => changeLabelState(e, 'out')} onMouseMove={(e) => changeLabelState(e, 'move')}>
      <BizIcon icon={icon} />
      {/*<p>{label}</p>*/}
      <div className="marker-icon-title" style={{ visibility: showLabel ? 'inherit' : 'hidden', top: position.top, left: position.left, zIndex: 100000 }}>
        <div className="title-text" >{label}</div>
      </div>
    </li>
  );
};

class ControlItem extends Component {

  constructor(props) {
    super(props);
    this.state = {
      open: false,
      subItemActives: this.getInitSubSelectKeys(),
      showLabel: false, // 是否显示提示
      position: { top: '', left: '' } // 提示相对鼠标坐标位置
    };
  }

  componentWillReceiveProps(nextProps) {
    const { active } = nextProps;
    this.setState({
      open: active
    });
  }

  onSubItemClick = (item) => {
    const { type } = this.props;
    const alreadyActive = this.isActiveSubItem(item.key);
    const newKeys = this.getSubItemActive(item.key, alreadyActive);
    this.setState({
      subItemActives: newKeys
    });
    this.props.onSubItemClick && this.props.onSubItemClick({ ...item, type }, alreadyActive);
  }

  onControlItemClick = (item) => {
    const { active, onClick } = this.props;
    this.setState({
      open: !active,
      // 重置选中为默认
      subItemActives: this.getInitSubSelectKeys()
    });
    onClick(item);
  }

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

  getInitSubSelectKeys = () => {
    const { subs = [] } = this.props;
    return subs.map(s => s.key);
  }

  isActiveSubItem = (key) => {
    const { subItemActives } = this.state;
    return subItemActives && subItemActives.includes(key);
  }

  shouldOpenPop = () => {
    return this.props.active;
  }

  changeLabelState(e, type) {
    if (type === 'over') {// mouse over
      this.setState({ showLabel: true });
    } else if (type === 'out'){// mouse out
      this.setState({ showLabel: false });
    } else {// mouse move
      const x = 15;
      const y = 10;
      let top = e.nativeEvent.layerY + y + 'px';
      let left = e.nativeEvent.layerX + x + 'px';
      this.setState({
        position: {
          top,
          left
        }
      });
    }
  }

  renderSubContent = () => {
    const { subs = [], type } = this.props;
    if (type === 'risk' || type === 'danger' || type === 'taskWork') {
      return (
        <ul>
          {
            subs.map(l => {
              let key = `${type}_${l.key.split('_')[1]}`;
              const cls = classNames({
                'sub-control-item': true,
                [`point-${key}`]: true,
                'control-active': this.isActiveSubItem(l.key)
              });
              return (
                <li key={l.key} className={cls} onClick={() => this.onSubItemClick(l)}>
                  <span className="sub-control-item-dot" />
                  <span>{l.label}</span>
                </li>
              );
            })
          }
        </ul>
      );
    }
    return (
      <ul>
        {
          subs.map(l => {
            const cls = classNames({
              'sub-control-item': true,
              [`point-${l.key}`]: true,
              'control-active': this.isActiveSubItem(l.key)
            });
            return (
              <li key={l.key} className={cls} onClick={() => this.onSubItemClick(l)}>
                <span className="sub-control-item-dot" />
                <span>{l.label}</span>
              </li>
            );
          })
        }
      </ul>
    );
  }

  render() {
    const { open, showLabel, position } = this.state;
    const { onClick, icon, label, active, subs } = this.props;
//    const imgPath = imgStatic.contorls[icon];
    const cls = classNames('control-item', {
      'control-active': active
    });
    if (!utils.isEmpty(subs)) {
      return (
        <Popover
          className="control-item-popver"
          triggerMode="click"
          align="top"
          direction="right"
          open={open}
          content={this.renderSubContent()}
          shouldOpen={this.shouldOpenPop}
          destroyContent
        >
          <div>
            <ControlTrigger cls={cls} icon={icon} label={label} onClick={(item) => this.onControlItemClick(item)} position={position} showLabel={showLabel} changeLabelState={(e, type) => this.changeLabelState(e, type)} />
          </div>
        </Popover>
      );
    }
    return (
      <div>
        <ControlTrigger cls={cls} icon={icon} label={label} onClick={onClick} position={position} showLabel={showLabel} changeLabelState={(e, type) => this.changeLabelState(e, type)} />
      </div>
    );
  }
}

ControlItem.propTypes = {
  // 具体的 control item 类型
  type: PropTypes.string,
  onClick: PropTypes.func,
  icon: PropTypes.string,
  label: PropTypes.string,
  active: PropTypes.bool,
  subs: PropTypes.array,
  onSubItemClick: PropTypes.func
};

export default ControlItem;
