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 = {
      boxEditable:true,
      boxLeft:null,
      boxTop:null,
      symptom:false,
      timer:null,
      inpText:'',
      clearTimer:null,
      overFlag:false,
    };
    this.toggleEditable = this.toggleEditable.bind(this);
    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);
  }
  toggleEditable(){
    this.setState({
      boxEditable:!this.state.boxEditable
    })
  }


  getInlineTag(){
    const {datas,showArr,handleTailClick,selecteds,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,selecteds,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{
      if(datas.length==0 && !innerText.trim()){
        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){//没有使用模板时点击搜索结构要展开模板
      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} = 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.innerText?(ev.target.innerText = data.substr(0,config.limited)):(ev.target.innerHTML = data.substr(0,config.limited));  //输入法内输入多个字再按enter的情况
      ev.target.blur();
      
      this.setState({
        inpText:data.substr(0,config.limited),
        overFlag:true
      })
      return false;
    }
    this.setState({
      inpText:data,
      overFlag:false
    })
    if(datas && datas.length > 0){//使用模板
      return false;
    }
    // 有输入内容或搜索结果时关闭，否则显示
    if(data && data.trim()||searchData.length>0){
      this.setState({
        symptom:false
      })
    }else{
      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;
    //分词-现病史没有模板的时候才去获取
    if(inner.trim() && currentData&&currentData.length==0){
      getFeature(inner).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="")
      freeText && freeText(data.trim());
      // 慢病模板获取：精确匹配"糖尿病复诊"，储存慢病字段
      /*let flg = this.ifClear();
      if((data.trim()=='糖尿病复诊'||data.trim()=='糖尿病(复诊)'||data.trim()=='糖尿病（复诊）') && !flg){
        saveChronic && saveChronic({name:'糖尿病',conceptId:21773});
      }*/
    }else{
      if(datas.length==0){
        const ev = e || window.event;
        const data = ev.target.innerText;
        // 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} 
      onchange={this.handleChange} 
      handleClick={this.handleClick} 
      handleBlur={this.handleBlur}
      data={datas}
      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;