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';

// eslint-disable-next-line react/prop-types
const ControlTrigger = ({ onClick, icon, dotTipNum, label, cls, showLabel, changeLabelState, position } = {}) => {
  // console.log('nummmmmmmmmmmmm===',dotTipNum);
  return (
    <li className={cls} onClick={onClick} onMouseOver={(e) => changeLabelState(e, 'over')} onMouseOut={(e) => changeLabelState(e, 'out')} onMouseMove={(e) => changeLabelState(e, 'move')}>
      {/* <BizIcon icon={icon} /> */}
      <img src={`/src/assets/indexChart/${icon}.png`} style={{marginTop: '2px', width: '26px', height: '26px'}} />
      <div className="marker-icon-title" style={{ visibility: showLabel ? 'inherit' : 'hidden', top: position.top, left: position.left }}>
        <div className="title-text" >{label}</div>
      </div>
      <div className='dotTip' style={{ display: icon === 'dangerMsg' && dotTipNum > 0 ? 'block' : 'none' }}></div>
    </li>
  );
};

/**
 * 控制区项
 *
 * @class ControlItem
 * @extends {Component}
 */
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
    });
  }

  /**
   * 子项点击事件
   *
   * @memberof ControlItem
   */
  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);
  }

  /**
   * 控制区点击事件
   *
   * @memberof ControlItem
   */
  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];
  }

  /**
   * 初始化选中的每一项
   *
   * @memberof ControlItem
   */
  getInitSubSelectKeys = () => {
    const { subs = [] } = this.props;
    return subs.map(s => s.key);
  }

  /**
   * 是否选中
   *
   * @memberof ControlItem
   */
  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
        }
      });
    }
  }

  /**
   * 内容渲染
   *
   * @memberof ControlItem
   */
  renderSubContent = () => {
    const { subs = [], type } = this.props;
    if (type === 'patrol') {
      return (
        <ul>
          {
            subs.map(l => {
              let key = `risk_${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 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} dotTipNum={this.props.dotTipNum} 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} dotTipNum={this.props.dotTipNum} 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;
