import React, { Component } from "react";
import style from "./index.less";
import classNames from 'classnames';
import Notify from '@commonComp/Notify';
import config from '@config/index';
import {setFontColorSize} from '@utils/tools';
/***
 * 标签组件
 * author:zn@2018-11-08
 * 接收参数：
 * prefix：前缀文字
 * value:输入的值
 * placeholder
 * suffix：后缀文字
 *
 ***/
class InlineTag extends Component {
  constructor(props){
    super(props);
    this.$span = React.createRef();
    this.state = {
      value:props.value||'',
      over:false
    };
    this.handleBlur = this.handleBlur.bind(this);
    this.handleInput = this.handleInput.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleFixClick = this.handleFixClick.bind(this);
  }
  handleInput(e){       //输入时保存临时值，在修改灰显为黑色时判断用
    e.stopPropagation();
    const {mainSaveText,ikey,prefix,suffix,value,boxMark} = this.props;
    const val = e.target.innerText||e.target.innerHTML.replace(/&nbsp;$|^&nbsp;/,'');//兼容firefox26
    const myval = prefix+val+suffix;
    const i = ikey.split("-")[1];
    const tempArr = [...mainSaveText];
    tempArr.splice(i,1);
    let lefts = tempArr.join("");
    if(boxMark==='1'&&(lefts+myval).length>config.limited) {      //主诉超过字数限制提示并禁止输入
      e.target.innerHTML = value||'';
      Notify.info(config.limitText);
      this.setState({
        over:true
      });
      return;
    }
    this.setState({
      value:val,
      over:false
    });
  }
  handleBlur(e){         //鼠标离开是保存值到store中
    e.stopPropagation(); //不阻止会触发外层div的失焦事件
    const val = e.target.innerText||e.target.innerHTML.replace(/&nbsp;$|^&nbsp;/,'');
    const {handleInput,ikey,prefix,suffix,placeholder,value,boxMark} = this.props;
    if(!val.trim()){
      this.setState({
        value:''
      });
      e.target.innerHTML = placeholder;
      return;
    }
    if(boxMark==='1'&&this.state.over){     //超过字数限制，显示输入前的值
      e.target.innerHTML = value||'';
      return;
    }
    //主诉未超过字数限制，保存值
    e.target.innerHTML = val.trim();
    handleInput&&handleInput({text:val.trim(),ikey,prefix,suffix});
  }
  handleFocus(e){
    e.stopPropagation();
    const text = e.target.innerText || e.target.innerHTML.replace(/&nbsp;$|^&nbsp;/,'');
    const {placeholder} = this.props;
    if(text.trim()==placeholder){
      e.target.innerHTML = '';
    }
  }
  getStyle(){
    const {hideTag,placeholder,isExtBlue} = this.props;
    const value = this.state.value;
    const ext = isExtBlue?style['ext']:'';//是否为体征
    if(hideTag){//是否是多标签组合
      if(value){
        return classNames(style['selected-no-tag'], setFontColorSize());
      }
      return classNames(style['no-tag'],ext, setFontColorSize(2),'prefixUnsetColor');
    }
    if(!value||value.trim()==placeholder){//灰色标签
      return classNames(style['gray'],ext, setFontColorSize(2));
    }
    return classNames(style['selected-tag'],ext, setFontColorSize());
  }
  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(){
    //设置最小宽度避免输入后宽度跳动
    this.$span.current.innerHTML=this.props.placeholder;
    const spanWidth = window.getComputedStyle(this.$span.current).width;
    this.$span.current.style.minWidth=spanWidth;
  }
  render(){
    const {prefix,suffix,isExtBlue} = this.props;
    return <div className={this.getStyle()}
                onClick={this.handleFixClick}>
                <span className="prefixUnset">{prefix}</span>
                <span className={`${style['free-in']}`}
                      contentEditable={true}
                      onBlur={this.handleBlur}
                      onInput={this.handleInput}
                      onFocus={this.handleFocus}
                      onClick={(e)=>{e.stopPropagation();}}
                      ref={this.$span}></span>
                <span className="prefixUnset">{suffix}</span>
            </div>;
    }
}

export default InlineTag;
