import React, { Component } from "react";
import style from "./index.less";
import classNames from 'classnames';
import {handleEnter} from '@utils/tools.js';
/***
 * 标签组件
 * author:zn@2018-11-08
 * 接收参数：
 * prefix：前缀文字
 * value:输入的值
 * placeholder
 * suffix：后缀文字
 * canEditable: 切换父元素框（主诉同级框）的可编辑属性，
 *              PS：父元素框可编辑时子元素onBlur无法触发，因为此时focus的元素为父元素框
 *
 ***/
class InlineTag extends Component {
  constructor(props){
    super(props);
    this.$box = React.createRef();
    this.$span = React.createRef();
    this.state = {
      editable:false,
      value:props.value
    };
    this.changeToEdit = this.changeToEdit.bind(this);
    this.changeToClick = this.changeToClick.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
    this.handleInput = this.handleInput.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleFixClick = this.handleFixClick.bind(this);
  }
  changeToEdit(e){
    const {handledbClick,id} = this.props;
    this.setState({
      editable:true
    });
    //埋点记录
    handledbClick&&handledbClick({id});
  }
  changeToClick(event){
    event.returnValue = true;
    const {canEditable} = this.props;
    canEditable&&canEditable();
    this.setState({
      editable:false
    });
  }
  handleInput(e){       //输入时保存临时值，在修改灰显为黑色时判断用
    const text = e.target.innerText || e.target.innerHTML;
    this.setState({
      value:text
    });
   // e.target.innerText = text;
  }
  handleBlur(e){         //鼠标离开是保存值到store中
    const {value} = this.state;
    const {handleInput,ikey,prefix,suffix} = this.props;
    this.$span.current.innerText?(this.$span.current.innerText=''):(this.$span.current.innerHTML='');      //修改生成文字变成输入的2倍bug
    handleInput&&handleInput({text:value,ikey,prefix,suffix});
  }
  handleFocus(e){
    e.stopPropagation();
    const text = e.target.innerText || e.target.innerHTML;
    const {placeholder} = this.props;
    if(text==placeholder){
      e.target.innerText?(e.target.innerText = ''):(e.target.innerHTML='');
    }
  }
  getStyle(){
    const {value} = this.state;
    const {hideTag} = this.props;
    if(hideTag){
      if(value){
        return classNames(style['selected-no-tag']);
      }
      return style['no-tag'];
    }
    if(!value){
      return classNames(style['gray']);
    }
    return style['selected-tag'];
  }
  moveEnd(obj) {
    if(window.getSelection){//ie11 10 9 ff safari
      obj.focus(); //解决ff不获取焦点无法定位问题
      var range = window.getSelection();//创建range
      range.selectAllChildren(obj);//range 选择obj下所有子内容
      range.collapseToEnd();//光标移至最后
    }
    else if (document.selection) {//ie10 9 8 7 6 5
      var range = document.selection.createRange();//创建选择对象
      range.moveToElementText(obj);//range定位到obj
      range.collapse(false);//光标移至最后
      range.select();
    }
  }
  handleFixClick(){
    this.moveEnd(this.$span.current);
  }
  componentDidMount(){
    //设置最小宽度避免输入后宽度跳动
    const spanWidth = window.getComputedStyle(this.$span.current).width;
    this.$span.current.style.minWidth=spanWidth;
  }
  render(){
    const {placeholder,value,prefix,suffix} = this.props;
    const inp = this.state.value;
    return <div className={this.getStyle()}
                 onDoubleClick={this.changeToEdit}
                  onClick={this.handleFixClick}
                 onkeydown={handleEnter}
                 onBlur={this.changeToClick} ref={this.$box} contentEditable={this.state.editable}>
                {prefix}
                <span className={style['free-in']}
                      contentEditable={true}
                      onBlur={this.handleBlur}
                      onInput={this.handleInput}
                      onFocus={this.handleFocus}
                      onClick={e=>e.stopPropagation()}
                      onkeydown={handleEnter}
                      ref={this.$span}>{value||(inp?'':placeholder)}</span>
                {suffix}
            </div>;
    }
}

export default InlineTag;
