import React,{Component} from 'react';
import style from './index.less';
import {Button,InlineTag,ItemBox,DropDown,DropList,Textarea,Notify,ConfirmModal} from '@commonComp';
import TailInlineTag from '@commonComp/TailInlineTag';
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 { initItemList } from '@store/async-actions/historyTemplates';
import tableIcon from '@common/images/table.png';
import iconRadioDefault from '@common/images/icon-radio-default.png'
import iconRadioActive from '@common/images/icon-radio-active.png'
import { pushAllDataList,inspectAndAssist } from '@utils/tools';
import $ from 'jquery';
import store from '@store';

class MainSuit extends Component{
  constructor(props){
    super(props);
    this.state = {
      boxEditable:true,
      show:false,
      showModule:false,
      inputData:"",
      boxLeft:null,
      boxTop:null,
      selecSearch:"",
      symptom:false,
      search:false,
      timer:null,
      blurTimer:null,
      inpText:'',
      clearTimer:null,
      overFlag:false,
      tmpScroll:0,
      tmpTop:0,
      activeHistory: -1,
      showHistoryCase: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);
    this.referRecord = this.referRecord.bind(this);
    this.noReferRecord = this.noReferRecord.bind(this);
    this.referCase = this.referCase.bind(this);
    this.closeHistoryCaseModal = this.closeHistoryCaseModal.bind(this);
    this.handleQuoteClick = this.handleQuoteClick.bind(this);
  }
  componentWillReceiveProps(nextProps){
    this.setState({boxLeft:nextProps.boxLeft})
  }
  toggleEditable(){
    this.setState({
      boxEditable:!this.state.boxEditable
    })
  }


  getInlineTag(){
    const {datas,showArr,handleTailClick,selecteds,saveText,addModuleName,mainIds,allModules} = this.props;
    const boxMark = '1';
    let list = datas&&datas.map((item,i)=>{
      if(item.flag && item.flag==3){
        /*return <TailInlineTag {...item} showText={addModuleName} handleTailClick={(obj)=>{handleTailClick(obj,saveText)}}></TailInlineTag>*/
        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
        })  
      }
    }
    
  }


  /*handleShow(e,show){
    e.stopPropagation();
    if(e.target.tagName=="INPUT"){
      return ;
    }
  }*/

  handleSelect(item){//选中的常见症状
    if(item.select.length>0){
      const {clearCommS,insertMain,getData} = this.props;
      // 获取主诉模板
      getData && getData();
      // 让模板出现
      this.setState({
          showModule:true,
          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
    }
    // clearTimeout(this.state.timer);
    if(datas.length==0){//没有使用模板时点击搜索结构要展开模板
      insertSearch &&insertSearch({item,span});
      this.setState({
        search: false,
        showModule:true,
        inpText:''
      })
    }else{
      insertSearch &&insertSearch({item,span});
      this.setState({
        search: false,
      })
    }
    
     // 清空搜索结果
     clearSearch && clearSearch();
  }


  handleClick(e){//让搜索框跟随鼠标点击移动
    // e.stopPropagation(); //冒泡到最顶层关闭其他下拉
    //若使用e.target，因为是onClick事件中，值可能是itembox的而不是span因此会有bug
    const {getSearchLocation} = this.props;
    let leftL=0;      //用焦点元素的左边距替换鼠标点击的左边距，高度还是鼠标点击的位置
    let num = this.props.datas.length == 0?0:60
    if(isIE()){
      leftL = getPageCoordinate(e).boxLeft
    }else{
      const ele = document.activeElement;
      leftL = ele.offsetLeft+num
    }
    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])
  }

  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
    });

  }

  handleBlur(e){//隐藏常见症状下拉、存自由输入的值
    const {freeText,saveText,datas,clearSearch,getSymptomFeature,currentData,saveChronic} = this.props;
    const that = this;
    let data = this.state.inpText;
    if(!isIE()){
      if(currentData&&currentData.length==0){//现病史没有模板的时候才去获取
        getSymptomFeature && getSymptomFeature(e.target.innerText);
      } 
      e.target.innerText?(e.target.innerText=""):(e.target.innerHTML="")
      freeText && freeText(data.trim());
      // 慢病模板获取：精确匹配"糖尿病复诊"，储存慢病字段
      // 页面有模板数据 就不在请求
      let baseList = store.getState();
      let jsonData = getAllDataList(baseList);
      let jsonStr = getAllDataStringList(baseList);
      let flg = ifOtherClear(jsonData,jsonStr,baseList);//除主诉外 其他是否为空
      if(data.trim()=='糖尿病复诊' && !flg){
        saveChronic && saveChronic({name:'糖尿病',id: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);
        // that.setState({
        //   symptom:false
        // })
      },config.delayTime-200); 
  }

  // 慢病
  referRecord() {//是否引用历史病例弹窗--是
    const { chronicDesease,closeHisBox } = this.props
    closeHisBox&&closeHisBox();//关闭
    this.setState({
      showHistoryCase:true
    })
    store.dispatch(initItemList(chronicDesease));
  }
  noReferRecord() {//否
    const {closeHisBox,autoFillMoudles} = this.props;
    closeHisBox&&closeHisBox();
    // 不引用病例 -直接分发模板进行填充
    autoFillMoudles && autoFillMoudles()
    inspectAndAssist()//化验辅检模板
  }
  referCase() {
        const { items ,pureSaveChronic} = this.props
        this.setState({
          showHistoryCase:false
        })
        if (this.state.activeHistory === -1) {
            return
        }
        // let baseList = store.getState(); 
        let baseObj = items[this.state.activeHistory];
        pushAllDataList(baseObj.sign,'push',baseObj,'history')       //引用
        pureSaveChronic && pureSaveChronic({name:'糖尿病',id:21773}); //储存慢病疾病
        this.props.getBilling();
        this.setState({
            activeHistory: -1
        })
    }
  closeHistoryCaseModal() {//关闭病例列表
    const {autoFillMoudles} = this.props;
      this.setState({
        activeHistory: -1,
        showHistoryCase:false
      })
     // 不引用病例直接分发模板进行填充 
     autoFillMoudles&&autoFillMoudles();
  }
  handleQuoteClick(item, index) {
      console.log('asadsd', item)
      this.setState({
          activeHistory: index
      })
  }
  getHistoryCase() {
        const { items } = this.props
        return (<div className={style['history-info']}>
            {items.map((item, index) => {
                return<div onClick={this.handleQuoteClick.bind(this, item, index)} style={this.state.activeHistory === index ? {color: '#abcdef'} : ''}>
                    <img src={this.state.activeHistory === index ? iconRadioActive : iconRadioDefault}/>{item.diagnose}
                </div>
            })}
        </div>)
    }


  render(){
    const {type,CommonSymptoms,searchData,fetchPushInfos,isRead,totalHide,handleInput,fuzhen,saveText,editClear,datas,commSymHide,boxLeft,boxTop,showHisBox} = this.props;
    const {showModule,show,symptom,search,showHistoryCase} = 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;
    if(+type===1){      //文本模式
      return <Textarea title='主诉' boxMark='1' isRead={isRead} value={saveText[0]} handlePush={fetchPushInfos} handleInput={handleInput} />;
    }
    return  <div className={`${'mainsuit-box'} ${style['main-suit']}`} id="mainsuitBox">
      <ItemBox
      fuzhen={fuzhen} 
      title='主诉' 
      editable={editClear||datas.length==0?true:false} 
      boxLineHeight="24px"
      handleFocus={this.handleFocus} 
      onchange={(e)=>{this.handleChange(e)}} 
      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}/>:"")}
      <ConfirmModal visible={showHisBox} okText='是' cancelText='否' confirm={this.referRecord}  cancel={this.noReferRecord} close={this.noReferRecord}>
          <div className={style['confirm-info']}>是否引用往期病历</div> 
      </ConfirmModal>
      <ConfirmModal visible={showHistoryCase} noFooter='true' title='请选择历史病历' close={this.closeHistoryCaseModal} titleBg="#DFEAFE" icon={tableIcon} height={300}>
        {this.getHistoryCase()}
        <div className={style['confirm-history']}><span className={style['confirm-history-btn']} onClick={this.referCase}>确定</span></div>
    </ConfirmModal>
    </div>
  }
}

export default MainSuit;