import React,{Component} from 'react';
import {handleEnter,windowEventHandler,filterDataArr,getLabelIndex,setFontColorSize} from '@utils/tools.js';
import {DropList,Notify} from '@commonComp';
import config from '@config/index';
import style from "./index.less";
import classNames from 'classnames';
import $ from "jquery";

/****
 * 单选下拉，选项带输入
 * author:zn@2019-3.18
 * 接收参数：
 * placeholder:灰显文字
 * data:下拉内容数据
 * handleSelect:选中事件
 *
 * ***/

class RadioInpDrop extends Component{
  constructor(props){
    super(props);
    this.state={
      texts:props.vals||{0:props.value||props.placeholder},
    };
    this.$cont = React.createRef();
    this.isIE = navigator.appName=="Microsoft Internet Explorer" && navigator.appVersion.split(";")[1].replace(/[ ]/g,"")=="MSIE8.0";
    this.handleSelect = this.handleSelect.bind(this);
    this.handleShow = this.handleShow.bind(this);
    this.parseInputDom = this.parseInputDom.bind(this);
    this.handleInnerBlur = this.handleInnerBlur.bind(this);
  }
  getClass(){
    const {value,hideTag,show,isImports,isExtBlue,mouseSelect} = this.props;
    const orgBorder = isImports&&!value?style['orange-border']:'';    //查体，是否橙色框高亮
    const ext = isExtBlue?style['ext']:'';      //查体，是否是体征
    const selectedArea = mouseSelect?style['selected-area']:'';
    if(show){
      $(this.$cont.current).addClass(style['borderd']);
    }else{
      $(this.$cont.current).removeClass(style['borderd']);
    }
    if(value){
      if(hideTag){
        return classNames(style['no-tag'],ext,setFontColorSize(),selectedArea);
      }
      return classNames(style['selected-tag'],setFontColorSize(),selectedArea);
    }else{
      if(hideTag){
        return classNames(style['no-tag'],ext,setFontColorSize(2),selectedArea);
      }
      return classNames(style['tag'],orgBorder,ext,setFontColorSize(2,6),selectedArea);
    }
  }
  handleSelect(item){
    const {handleSelect,ikey,value,placeholder,mainSaveText} = this.props;
    let vals = {}, inx = 0;
    if(!item){
      handleSelect&&handleSelect({ikey});  //清空
      this.setState({
        texts:{0:placeholder}
      });
      return ;
    }
    const arr = item.name.split(config.radioOptionPer);
    arr.map((it,i)=>{
      inx = (i+1)*2-2;
      vals[inx] = it;
      if(i!=arr.length-1){
        vals[+inx+1]={value:'',index:+inx+1}
      };
    });
    this.setState({
      texts:vals
    });
    handleSelect&&handleSelect({ikey,id:item.id,values:vals,mainSaveText,value});
  }
  handleShow(e){
    e.stopPropagation();
    const {handleShow,ikey,id,patId} = this.props;
    document.activeElement.blur()//chrome41有效，但是失去焦点的span仍能编辑
    handleShow && handleShow({ikey,id:patId||id});

    windowEventHandler('scroll',()=>{      //弹窗跟随滚动条滚动或者关闭弹窗
      let scrollYs = $("#addScrollEvent")[0].scrollTop;
      this.setState({
        boxTop:this.state.tmpTop - scrollYs + this.state.tmpScroll
      })
    },$("#addScrollEvent")[0])
  }
  handleInnerBlur(i,val){
    const {ikey,boxMark,handleSaveInp,mainSaveText} = this.props;
    let vals = this.state.texts;
    vals[i].value=val;
    this.setState({
      texts:vals,
    });
    handleSaveInp({values:vals,ikey,boxMark,mainSaveText});
  }
  handleMouseUp(){
    const {select_start,i,setSelectArea,boxMark}= this.props;
    if(select_start!==undefined){
      setSelectArea({i,boxMark,dir:'end'});
    }
  }
  handleMouseDown(){
    const {i,setSelectArea,boxMark}= this.props;
    setSelectArea({i,boxMark,dir:'start'});
  }
  parseInputDom(){
    const {mainSaveText,ikey,boxMark} = this.props;
    const {texts} = this.state;
    const inx = ikey.split("-")[1];
    let temp='',list=[];
    for(let i in texts){
      temp = texts[i];
      if(typeof temp=='object'){
        list.push(<InputComp handleBlur={this.handleInnerBlur}
                             mainSaveText={mainSaveText}
                             index={i}
                             inx = {inx}
                             texts={texts}
                             boxMark={boxMark}
                             value={temp.value}
                             ></InputComp>);
      }else{
        list.push(<span className="inheritStyle">&nbsp;{temp}</span>);
      }
    }
    return list;
  }
  render(){
    const {data,show,vals,placeholder} = this.props;
    return <div className={style['container']} ref = {this.$cont}>
      <div className={this.getClass()}
           onClick={(e)=>this.handleShow(e)}
           onMouseUp={this.handleMouseUp.bind(this)}
           onMouseDown={this.handleMouseDown.bind(this)}
           onKeyDown={handleEnter}>
        {vals?this.parseInputDom():<span className='inheritStyle'>{placeholder}</span>}
      </div>
      <DropList onSelect={this.handleSelect} data={data} show={show}/>
    </div>
  }
}

//单选项中的输入框
class InputComp extends Component{
  constructor(props){
    super(props);
    this.$inp = React.createRef();
    this.handleBlur = this.handleBlur.bind(this);
    this.handleInp = this.handleInp.bind(this);
  }
  handleBlur(e){
    e.stopPropagation();
    if(this.over){
      return;
    }
    // FF26 只有innerHTML
    const text = e.target.innerText || e.target.innerHTML;
    const {handleBlur,index} = this.props;
    e.target.innerHTML = '';
    // FF26 会把&nbsp; 也获取到
    handleBlur(index,text.replace('&nbsp;',''));
  }
  getTextVal(obj=[],index){
    let str = '';
    Object.keys(obj).map((it)=>{
      if(typeof obj[it]==='string'){
        str += obj[it];
      }else{
        if(it!==index){       //当前输入框文字不记录，避免重复计算
          str += obj[it].value;
        }
      }
    });
    return str;
  }
  handleInp(e){
    const val = e.target.innerText||e.target.innerHTML;
    const {mainSaveText,value,index,texts,inx,boxMark} = this.props;
    if(boxMark==='1'){
      const textVal = this.getTextVal(texts,index);    //已存的单选含自由输入生成的文字
      const tempArr = [...mainSaveText];
      tempArr.splice(inx,1);
      const otherVal = tempArr.join("");      //主诉其他的已填文字
      //console.log(textVal,otherVal,val)
      //超出主诉限制提示并不可继续输入
      if((textVal+otherVal+val).length>config.limited){
        e.target.innerHTML=value||'';
        this.over=true;
        //e.target.blur();
        Notify.info(config.limitText);
        return;
      }
      this.over=false;
    }
    this.over=false;
  }
  componentWillReceiveProps(next){
    //超过限制时，再点开下拉被删除的输入文字又出现bug修改
    const inp = this.$inp.current;
    const value = next.value;
    inp.innerHTML = '';
    setTimeout(function(){
      inp.innerHTML = value;
    });
  }
  render(){
    const {value} = this.props;
    return <span contentEditable={true}
                 ref={this.$inp}
                 className={`${style['inner-inp']}`}
                 onClick={(e)=>{e.stopPropagation()}}
                 onFocus={(e)=>{e.stopPropagation()}}
                 onInput={this.handleInp}
                 onBlur={this.handleBlur}>&nbsp;</span>
  }
}

export default RadioInpDrop;