import react from "react";
import style from "./index.less";
import $ from 'jquery';
import classNames from 'classnames';
import {handleEnter,isIE,filterArr,deepClone,filterDataArr,setFontColorSize} from '@utils/tools.js';
import {Notify} from '@commonComp';
import SlideItem from "./SlideItem";
import config from '@config/index.js';
/**
  单列多选组件（tagtype=1,controlType=2）
  2019-2-20 By_liucf
  接收参数：
  placeholder：标签名
  value：标签选中的值
  show：是否展示下拉
  data：下拉数据
  type：1-主诉，2-现病史，3-其他史，4-查体
**/

class Multiple extends react.Component{
  constructor(props){
    super(props);
    const {seleData,seleId} = deepClone(props.selecteds||[]);
    this.state={
      editable:false,
      timer:null,
      labelVal:"",
      seleData:seleData||"",
      seleId:seleId||[],
    }
    this.$div = React.createRef();
    this.handleShow = this.handleShow.bind(this);
    this.changeToEdit = this.changeToEdit.bind(this);
    this.onChange = this.onChange.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
    this.handleConfirm = this.handleConfirm.bind(this);
  }

  getClass(){
    const {show,value,hideTag,isImports,isExtBlue} = this.props;
    const orgBorder = isImports&&!value?style['orange-border']:'';
    const ext = isExtBlue?style['ext']:'';
    const editBorder = this.state.editable?style['blue-border']:'';
    if(show){
      $(this.$div.current).addClass(style['borderd']);
    }else{
      $(this.$div.current).removeClass(style['borderd']);
    }
    if(value){
      if(hideTag){
          return classNames(style['hide-tag'],orgBorder,setFontColorSize(isExtBlue?2:''))
        }
      return classNames(style['selected-tag'],orgBorder,editBorder,setFontColorSize());
    }else{
      if(hideTag){
        return isExtBlue?classNames(setFontColorSize(2)):classNames(setFontColorSize(2),'prefixUnsetColor')
      }
      return classNames(style['tag'],orgBorder,ext,setFontColorSize(1));
    }
    // if(value){
      //   return hideTag?classNames(style['hide-tag'],orgBorder,setFontColorSize(isExtBlue?2:'')):classNames(style['selected-tag'],orgBorder,editBorder,setFontColorSize());
      // }
      // return hideTag?classNames(setFontColorSize()):classNames(style['tag'],orgBorder,ext,setFontColorSize());
  }

  getListClass(){
    let name = style['text-list'];
    let isHide = this.props.show?'':style['hide'];
    return classNames(style['list'],name,isHide);
  }

  handleShow(e){//单击
    e&&e.stopPropagation();
     this.setStateInit();
    const {ikey,handleShow,placeholder,flag,id,value,tagType,type} = this.props;
    const that = this;
    clearTimeout(this.state.timer);
    this.state.timer = setTimeout(function(){
      if (that.state.editable) {//如果处于编辑状态点击不显示下拉框
        return;
      }else{
        handleShow&&handleShow({ikey,placeholder,flag,id,value,tagType,type});
      }
    },300)

  }

  setStateInit(){//恢复初始选中状态
    const {seleData,seleId} = deepClone(this.props.selecteds||[]);
    this.setState({
      seleData:seleData||"",
      seleId:seleId||[],
    })
  }

  changeToEdit(e){//双击
    const {value,id,placeholder,handleDbclick,handleHide} = this.props;
    let text = e.target.innerText || e.target.innerHTML;
    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
    handleHide&&handleHide();       //展开情况下双击收起
    // clearTimeout(this.state.timer);//取消延时的单击事件
    e.stopPropagation();
    if(value&&value.trim()){//有选中值的标签才能双击编辑
      this.setState({
        labelVal:text,
        editable:true
      });
      /*setTimeout(()=>{
        e.target.focus();
      })*/
      handleDbclick && handleDbclick({value,id,placeholder});
    }
  }

  onChange(e){
    const {mainSaveText,ikey,type,handleLabelChange} = this.props;
    const {labelVal,editable} = this.state;
    let mainText = filterDataArr(mainSaveText);//主诉字数
    if(editable){//避免IE中点击标签也会触发
      let val = e.target.innerText || e.target.innerHTML;
      if(+type==1){// 主诉字数达到上限时不允许输入
        if(mainText.length >= config.limited){
          if(val.length > labelVal.length){
            e.target.innerText?(e.target.innerText = labelVal):(e.target.innerHTML = labelVal);
            Notify.info(config.limitText);
            return
          }else if(val.length == labelVal.length){
            this.setState({
              labelVal:val
            });
          }else{
            handleLabelChange && handleLabelChange({ikey,changeVal:val,type});
          }
        }
      }
    }
  }

  handleBlur(e){//修改存值
    e.stopPropagation();
    const {ikey,type,handleLabelChange} = this.props;
    const {editable} = this.state;
    const ev = e || window.event;
    if(editable){
      // 更改标签的value值
      let changeVal = ev.target.innerText || e.target.innerHTML;
      if(!isIE()){
        e.target.innerText?(e.target.innerText = ''):(e.target.innerHTML='');      //避免出现重复输入值
      }
      handleLabelChange && handleLabelChange({ikey,changeVal,type});
    }
    this.setState({
      editable:false
    });
  }

  handleConfirm(obj){
    const {handleConfirm,ikey,order,mainSaveText,value,handleHide,type} = this.props;
    const params = Object.assign({},obj,{ikey,order,mainSaveText,value,type});
    handleConfirm&&handleConfirm(params);
    handleHide&&handleHide();
  }

  componentDidMount(){
    if(isIE()){
      $(this.$div.current).onIe8Input(function(e){
        this.onChange(e)
      },this);
    }
  }
  render(){
    const {placeholder,value,show,data,hideTag} = this.props;
    const {editable,seleData,seleId} = this.state;
    return <div className={style["container"]}>
      <div className={this.getClass()}
      ref={this.$div}
      onClick={this.handleShow}
      onDoubleClick={hideTag?null:this.changeToEdit}
      onBlur={this.handleBlur}
      onInput={this.onChange}
      onKeyDown={handleEnter}
      contentEditable={editable}>{value||placeholder}</div>
      <div className={this.getListClass()} contentEditable="false">
        <SlideItem
          show={show}
          data={data} 
          seleData={seleData} 
          seleId={seleId} 
          handleConfirm={(obj)=>this.handleConfirm(obj)}
          ></SlideItem >
      </div>
    </div>
  }

}

export default Multiple;