import React,{Component} from 'react';
import style from './index.less';
import {ItemBox,Textarea,Notify,TailInlineTag} from '@commonComp';
import SearchDrop from '@components/SearchDrop';
import CommonSymptom from '@components/CommonSymptom';
import chooseType from '@containers/eleType.js';
import config from "@config/index";
import {isIE,getPageCoordinate,windowEventHandler,filterDataArr,getAllDataList,getAllDataStringList,ifOtherClear} from "@utils/tools.js";
import store from '@store';
import {getFeature} from '@store/async-actions/fetchModules';

class MainSuit extends Component{
  constructor(props){
    super(props);
    this.state = {
      boxLeft:null,
      boxTop:null,
      symptom:false,
      timer:null,
      inpText:'',
      clearTimer:null,
      overFlag:false,
    };
    this.handleFocus = this.handleFocus.bind(this);
    this.handleSelect = this.handleSelect.bind(this);
    this.handleSearchSelect = this.handleSearchSelect.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  getInlineTag(){
    const {datas,showArr,handleTailClick,saveText,mainIds,allModules} = this.props;
    const boxMark = '1';
    let list = datas&&datas.map((item,i)=>{
      if(item.flag && item.flag==3){
        return <TailInlineTag {...item} showText={item.relationModuleName} handleTailClick={(obj)=>{handleTailClick(obj,saveText,allModules)}}></TailInlineTag>
      }else {
        return chooseType({item,boxMark,i,hideTag:false,showArr,saveText,mainIds});
      }

    })
    return list;
  }


  handleFocus(e){
    //e.stopPropagation();
    const {getCommonSymptoms,datas,clearDiagnose} = this.props;
    let innerText = e.target.innerText || e.target.innerHTML;//兼容火狐43
    clearDiagnose&&clearDiagnose();//清除复诊数据
    if(!isIE()){//IE会触发onfocus和onblur事件
      if(!innerText.trim()){//有内容就走搜索接口
        getCommonSymptoms && getCommonSymptoms();
        this.setState({
          symptom:true,
          inpText:innerText
        })    
      }else{
        this.setState({
          symptom:false,
          inpText:innerText
        }) 
      }
    }else{
      window.event.cancelBubble = true;
      // IE 默认会有一个<br>
      // if(datas.length==0 && !innerText.trim()){
      if(datas.length==0 && innerText == '<br>'){
        getCommonSymptoms && getCommonSymptoms();
        this.setState({
          symptom:true
        })  
      }
    }
    
  }

  handleSelect(item){//选中的常见症状
    if(item.select.length>0){
      const {clearCommS,insertMain,getData} = this.props;
      // 获取主诉模板
      // getData && getData();
      // 让模板出现
      this.setState({
          symptom: false,
        }) 
      //选中后清空下拉结果
      insertMain && insertMain(item);
      clearCommS && clearCommS();
    }else{//没有选中点确定-关闭
      this.setState({
        symptom: false
      })
    } 
  }


  handleSearchSelect(item){
    const {clearSearch,insertSearch,datas,span,saveText} = this.props;
    let mainText = filterDataArr(saveText);//主诉字数
    const itemL = item.name.length;
    let lengths = mainText.length + itemL;
    if(lengths>config.limited){
      Notify.info(config.limitText);
      clearSearch && clearSearch();
      return
    }
    if(datas.length==0){//没有使用模板时点击搜索结构要展开模板
      // FF26 清空输入的值 bug2283
      const mainBox = document.getElementById('mainSuit');
      mainBox.innerHTML = "";
      insertSearch &&insertSearch({item,span});
      this.setState({
        search: false,
        inpText:''
      })
    }else{
      insertSearch &&insertSearch({item,span});
      this.setState({
        search: false,
      })
    }    
     // 清空搜索结果
     clearSearch && clearSearch();
  }


  handleClick(e){
    // e.stopPropagation(); //冒泡到最顶层关闭其他下拉
    //搜索框位置
    const ele = document.activeElement;
    const height = ele.offsetHeight;
    let boxTop = (+(ele.offsetTop)+height);
    let boxLeft = ele.offsetLeft;
    this.setState({
      boxLeft:boxLeft,
      boxTop:boxTop
    });
  }

  handleChange(e){
    const ev = e || window.event;
    const data = ev.target.innerText || ev.target.innerHTML;
    const {getSearchData,searchData,datas,pushMessage,reTotalHide,saveText,clearSearch,CommonSymptoms,getCommonSymptoms} = this.props;
    const {overFlag,inpText} = this.state;
    reTotalHide && reTotalHide();//重置homePage中的控制项
    const that = this;
    if(data&&data.length > config.limited){
      Notify.info(config.limitText);
      if(overFlag){
        ev.target.innerText?(ev.target.innerText = inpText) : (ev.target.innerHTML = inpText);
        ev.target.blur();
        return
      }
      ev.target.blur();
      // ev.target.innerText?(ev.target.innerText = data.substr(0,config.limited)):(ev.target.innerHTML = data.substr(0,config.limited));  //输入法内输入多个字再按enter的情况
      //console.log(333,data,ev)
      // ev.target.blur();
      this.setState({
        inpText:data.substr(0,config.limited),
        overFlag:true,
        symptom:false
      })
      return false;
    }
    this.setState({
      inpText:data,
      overFlag:false
    })
    if(datas && datas.length > 0){//使用模板
      return false;
    }
    // 有输入内容或搜索结果时关闭，否则显示
    // if(data && data.trim()||searchData.length>0){
    if(data && data.trim()){
      clearTimeout(this.state.timer);
      const timer = setTimeout(function(){
        pushMessage && pushMessage(data);
        //调搜索接口 使用模板走EditableSpan里的搜索方法
        // FF26 会多一个<br>
        getSearchData && getSearchData({inpStr:data.replace('<br>',''),boxMark:1,itemType:0});
      },config.delayTime);
      this.setState({
        symptom:false,
        timer
      })
    }else{
      clearTimeout(this.state.timer);
      // 内容为空-清空搜索数据-显示常见
      clearSearch();
      // 慢病流程下常见会被清空，所以要重新获取
      if(CommonSymptoms.length == 0){
        getCommonSymptoms && getCommonSymptoms();
      }
      this.setState({
        symptom:true
      })
    }

    // IE11聚焦时也会触发change事件，导致常见症状下拉出不来
    if(isIE() && data == '<br>'){
      this.setState({
        symptom:true
      })
    }
    /*clearTimeout(this.state.timer);
    const timer = setTimeout(function(){
      pushMessage && pushMessage(data);
      //调搜索接口 使用模板走EditableSpan里的搜索方法
      getSearchData && getSearchData({inpStr:data,boxMark:1,itemType:0});
    },config.delayTime);
    this.setState({
      timer
    });*/

  }
  //除主诉外 其他是否为空
  ifClear(){
    let baseList = store.getState();
    let jsonData = getAllDataList(baseList);
    let jsonStr = getAllDataStringList(baseList);
    let flg = ifOtherClear(jsonData,jsonStr,baseList);
    return flg;
  }

  handleBlur(e){//隐藏常见症状下拉、存自由输入的值
    const {freeText,saveText,datas,clearSearch,getSymptomFeature,currentData,saveChronic} = this.props;
    const that = this;
    let data = this.state.inpText;
    const inner = e.target.innerText || e.target.innerHTML ;
    //分词-现病史没有模板的时候才去获取
    if(inner.trim() && currentData&&currentData.length==0){
      getFeature(inner.replace('<br>','')).then((res)=>{
        if(res.data.code==0){
          const result = res.data.data;
          // 慢病
          if(result && result[0].chronicLabel==1){
            let flg = this.ifClear();
            if(!flg){
              saveChronic && saveChronic(result[0]);
            }
          }else{
            getSymptomFeature && getSymptomFeature(result);
          }
        }
      })
    }
    if(!isIE()){
      // inner?(e.target.innerText=""):(e.target.innerHTML="")
      e.target.innerText?(e.target.innerText=""):(e.target.innerHTML="");
      freeText && freeText(data.trim().replace('<br>',''));
    }else{
      if(datas.length==0){
        const ev = e || window.event;
        const data = ev.target.innerText || ev.target.innerHTML;
        // freeText && freeText(data.trim());
        freeText && freeText(data);
      }
    }
    // 延时关闭常见症状下拉、清空搜索结果，不延时会影响选中
     /* const clearTimer = setTimeout(function(){
        clearSearch && clearSearch();
        clearTimeout(clearTimer);
      },config.delayTime-200); */
  }
  /*componentWillReceiveProps(nextProps){   //主诉高度变化不会出现滚动内容看不见的情况，因为已经是最顶部，所以可以不必更新滚动条
      const contHeightDiff =  nextProps.data&&this.props.data&&nextProps.data.length!==this.props.data.length;
      const dataDiff = !!nextProps.data!==!!this.props.data;
      if(contHeightDiff||dataDiff){
        this.context.scrollArea.refresh();
      }
  }*/
  render(){
    const {saveChronic,readMode,type,CommonSymptoms,searchData,fetchPushInfos,isRead,totalHide,handleInput,fuzhen,saveText,editClear,datas,commSymHide} = this.props;
    const {symptom,boxLeft,boxTop} = this.state;
    const symptomFlag = CommonSymptoms.length>0 ? true : false;
    const searchFlag = searchData.length>0 ? true : false;
    const boxTop1 = datas.length>0?boxTop:45;
    const boxLeft1 = datas.length>0?boxLeft:85;
    const mode = readMode===null||readMode===-1?type:readMode;
    if(+mode===1){      //文本模式
      return <Textarea title='主诉' boxMark='1' saveChronic={saveChronic} isRead={isRead} value={saveText[0]} handlePush={fetchPushInfos} handleInput={handleInput} />;
    }
    return  <div className={style['main-suit']}>
      <ItemBox
      fuzhen={fuzhen} 
      title='主诉' 
      editable={editClear||datas.length==0?true:false} 
      boxLineHeight="24px"
      handleFocus={this.handleFocus}
      handleChange={this.handleChange}
      handleClick={this.handleClick} 
      handleBlur={this.handleBlur}
      data={datas}
      saveText={saveText}
      boxId="mainSuit">
        {''}{datas.length>0?<div style={{display:'inline-block'}}>{this.getInlineTag()}</div>:(saveText[0]?saveText[0]:'')}
      </ItemBox>
      {/*没有推送结果就不显示*/}
      {symptomFlag && !searchFlag ? <CommonSymptom data={CommonSymptoms} show={!totalHide&&symptom} onSelect={this.handleSelect} /> : ( searchFlag ? <SearchDrop data={searchData} show={!commSymHide} onSelect={this.handleSearchSelect} left={boxLeft1} top={boxTop1} mainEmpty={datas.length==0?true:false}/>:"")}
    </div>
  }
}

/*MainSuit.contextTypes = {
  scrollArea: React.PropTypes.object
};*/
export default MainSuit;