import React,{Component} from 'react';
import style from './index.less';
import {Button,InlineTag,ItemBox,Notify,Textarea} from '@commonComp';
import TailInlineTag from '@commonComp/TailInlineTag';
import chooseType from '@containers/eleType.js';
import SearchDrop from '@components/SearchDrop';
import {filterDataArr,getPageCoordinate,windowEventHandler,isIE} from '@utils/tools'
import $ from 'jquery';

class CurrentIll extends Component{
  constructor(props){
    super(props);
    this.state = {
      boxEditable:true,
      showMoudle:false,
      forbidInput:false,
      mainFlag:true,
      mainData:[],
      boxMark:"2",
      boxLeft:0,
      boxTop:0,
      show:true,
      tmpScroll:0,
      tmpTop:0,
      setDataTimer:null
    }
    this.toggleEditable = this.toggleEditable.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.onchange = this.onchange.bind(this);
    this.handleSearchSelect = this.handleSearchSelect.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }
  
  componentWillReceiveProps(nextProps){
    this.setState({boxLeft:nextProps.boxLeft})
  }

  toggleEditable(){
    this.setState({
      boxEditable:!this.state.boxEditable
    })
  }

  handleFocus(e){
    // 判断主诉是否为空
    const {mainData,mainText,setData,moduleNum,mainIds,data,changeEditIll,editClear,symptomFeature,isChronic} = this.props;
    const that = this;
    const ev = e || window.event;
    const text = ev.target.innerText||ev.target.innerHTML;
    let {setDataTimer} = this.state; 
    let mainFinallyText = filterDataArr(mainText);
    if(!mainFinallyText){
      //弹窗提醒
      Notify.error("无法操作，请先输入主诉");
      this.setState({
        forbidInput:true
      })
    }else if(!text) {//现病史框里没有内容时才设置模板
      let num = moduleNum.num;//主诉使用了几个模板
      if(data.length==0 && !isChronic || !isChronic.name ){
        clearTimeout(setDataTimer);
        setDataTimer = setTimeout(function(){//延时，等待主诉失焦数据返回
            setData && setData({num,mainData,mainIds,symptomFeature:symptomFeature.featureData,isChronic});   
        },200)  
        this.setState({
          setDataTimer
        })
      }
      this.setState({
          showMoudle:true,
          forbidInput:false,
          boxEditable:false,
          setDataTimer
      })
      changeEditIll(false)
    }

  }

  onchange(e){//监听输入事件,主诉无数据不能输入
    const ev = e || window.event;
    ev.target.innerText?(ev.target.innerText = ""):(ev.target.innerHTML="");
  }

  handleClick(e){//让搜索框跟随鼠标点击移动
    // e.stopPropagation(); //冒泡到最顶层关闭其他下拉
    //若使用e.target，因为是onClick事件中，值可能是itembox的而不是span因此会有bug
    const {getSearchLocation} = this.props;
    let leftL=0;      //用焦点元素的左边距替换鼠标点击的左边距，高度还是鼠标点击的位置
    if(isIE()){
      leftL = getPageCoordinate(e).boxLeft
    }else{
      const ele = document.activeElement;
      if(ele.toString().indexOf('HTMLSpanElement') == -1){     //点击的不是span无法聚焦就不再设置位置
        return;
      }
      leftL = ele.offsetLeft+90
    }
    // console.log(getPageCoordinate(e).boxTop)
    getSearchLocation(getPageCoordinate(e).boxTop,leftL)
    this.setState({
      // boxLeft:getPageCoordinate(e).boxLeft,
      // boxLeft:leftL,
      // boxTop:getPageCoordinate(e).boxTop,
      tmpScroll: $("#addScrollEvent")[0].scrollTop,
      tmpTop:getPageCoordinate(e).boxTop
    });
    windowEventHandler('scroll',()=>{      //弹窗跟随滚动条滚动或者关闭弹窗
      let scrollYs = $("#addScrollEvent")[0].scrollTop;
      let boxTop = this.state.tmpTop - scrollYs + this.state.tmpScroll
      getSearchLocation(boxTop,this.state.boxLeft)
    },$("#addScrollEvent")[0])
  }

  handleSearchSelect(obj){
    const {questionId,name} = obj;
    const {fetchModules,focusIndex,span} = this.props;
    fetchModules&&fetchModules({id:questionId,index:focusIndex,name,span});
  }

  getInlineTag(){  
    const {data,showArr,selecteds,saveText,insertProcess,symptomIds,allModules} = this.props;
    const boxMark = '2';

    let list = data&&data.map((item,i)=>{
      if(item.flag && item.flag==3){
        return <TailInlineTag {...item} showText={item.relationModuleName} handleTailClick={(obj)=>{insertProcess(obj,allModules)}}></TailInlineTag>
      }else {
        return chooseType({item,boxMark,i,hideTag:false,showArr,selecteds,saveText,mainIds:symptomIds});
      }
    })
    return list;
  }
  handleBlur(e){
    const {freeText,data} = this.props;
    if(data&&data.length==0){//无模板纯手动输入时存值
      const ev = e || window.event;
      const innerData = ev.target.innerText || e.target.innerHTML;
      if(!isIE()){
        e.target.innerText?(e.target.innerText=""):(e.target.innerHTML="")
        freeText && freeText(innerData.trim());
      }else{
          freeText && freeText(innerData);
      }
    }
  }

  render(){
    const {fuzhen,isChronic,type,fetchPushInfos,handleInput,isRead,saveText,searchData,totalHide,showArr,focusIndex,editClear,data,boxLeft,boxTop} = this.props;
    const {showMoudle,forbidInput,boxMark,show} = this.state;
    const searchFlag = searchData.length > 0 ? true : false;

    if(+type===1){      //文本模式
      return <Textarea  title='现病史' boxMark='2'
                        isRead={isRead}
                        value={saveText[0]}
                        fuzhen={fuzhen}
                        isChronic={isChronic}
                        handlePush={fetchPushInfos}
                        handleInput={handleInput}/>;
    }
    return  <div className={style['current-ill']}>
      <ItemBox title='现病史' 
      editable={editClear||data.length==0?true:false} 
      handleFocus={this.handleFocus} 
      onchange={forbidInput?(e)=>{this.onchange(e)}:''} 
      handleClick={this.handleClick}
      handleBlur={this.handleBlur}>
        {data.length>0?this.getInlineTag():(saveText[0]?saveText[0]:'')}
      </ItemBox>
      {searchFlag ? <SearchDrop data={searchData} show={!totalHide} onSelect={this.handleSearchSelect} left={boxLeft} top={boxTop} />:""}
    </div>
  }
}

export default CurrentIll;