import React,{Component} from 'react';
import style from './index.less';
import closeIcon from '@common/images/close-icon.png';
import HisList from './HisList';
import PreviewBody from '@components/PreviewBody';
import config from '@config/index';
import {dragBox} from '@utils/drag';

/**
  急诊：全科历史病历
*/

class EmergencyHis extends Component{
  constructor(props){
    super(props);
    this.state = {
      index:0,
      timer:null,
      valChange:true,
      chooseItem:'',
      filtFlag:-1 , //筛选标识
      changeInd:false
    }
    this.searInp = React.createRef();
    this.handleClose = this.handleClose.bind(this);
    this.getMore = this.getMore.bind(this);
    this.handleFilter = this.handleFilter.bind(this);
    this.showDetail = this.showDetail.bind(this);
    this.handleDownload = this.handleDownload.bind(this);
    this.handleInput = this.handleInput.bind(this);
    this.handleAdd = this.handleAdd.bind(this);
  }

  componentDidMount(){
    dragBox('previewWrapper','previewStatic','add')
  }
  handleClose(){
    const {close} = this.props;
    close&&close();
    dragBox('previewWrapper','previewStatic','del')
  }

  getMore(){//点击更多
    const {params,getNextPage} = this.props;
    let current = params&&params.current + 1;
    let param = Object.assign({},params,{current:current});
    getNextPage&&getNextPage(param);
  }

  handleFilter(obj){//筛选
    const {filterData} = this.props;
    filterData&&filterData(obj);
    this.setState({
      filtFlag:obj.flag
    }) 
  }

  showDetail(index){//病历详情
    this.setState({
      index:index
    })
  }

  handleDownload(ids){//导出
    const { getDownload ,info} = this.props;
    getDownload&&getDownload({ids,info})
  }
  //搜索框输入
  handleInput(e){
    const { handleChangeValue } = this.props;
    clearTimeout(this.state.timer);
    let timer = setTimeout(()=>{
        clearTimeout(this.state.timer);
        if(e.target.value.trim() == ''){
          return  handleChangeValue('');
        }
        handleChangeValue(e.target.value);
    },config.delayTime);
    this.setState({
        timer,
        valChange:true,
        chooseItem:''
    });
  }
  //点击搜索结果
  handleListClick(item){
    const { handleChangeValue } = this.props;
    this.searInp.current.value = item.name;
    handleChangeValue('');
    this.setState({
      valChange:false,
      chooseItem:item.name
    });
  }
  getBtnStyle(){
    const {valChange} = this.state;
    if(!valChange){
      return `${style['add-btn']} ${style['comfirn-btn']}`
    }
    return style['add-btn'];
  }
  // 确认添加
  handleAdd(){
    const {chooseItem,index,filtFlag,changeInd} = this.state;
    const {addSecond,data} = this.props;
    if(chooseItem.trim()){
      // 在非默认筛选条件下添加二次诊断后重新调筛选接口
      if(filtFlag !== -1){
        if(filtFlag ==0){//无二次诊断添加后重置index
          this.setState({
            index:0,
            changeInd:!changeInd //重置list中的index标识
          })
        }
      }
      // 添加接口
      const item = {
        name:chooseItem,
        id:data[index].inquiryId
      }
      addSecond&&addSecond({item,flag:filtFlag});
      this.searInp.current.value = "";
      this.setState({
        valChange:true,
        chooseItem:''
      });
    }
  }

  componentWillUnmount(){
    // 组件销毁时 清除病历数据，因为每点开一次都会去请求
    const {clearHisRecord,handleChangeValue} = this.props;
    clearHisRecord&&clearHisRecord();
    handleChangeValue(''); //清除搜索结果
  }

  render(){
    const {show,data,total,preInfo,searchData} = this.props;
    // const {index,valChange,changeInd} = this.state;
    const {index,valChange,changeInd} = this.state;
    // const searchData = [];
    let baseObj = data[index];
    let dataJson,dataStr;
    if(baseObj){
        // dataJson = JSON.stringify(baseObj) == "{}" ? {} : JSON.parse(baseObj.dataJson);
        dataStr = JSON.stringify(baseObj) == "{}" ? [] : baseObj.detailList;
    }
    const getAllDataStringList = () =>{           //获取所有模块文本的数据
        let jsonDataString = {};
        jsonDataString.lis = {};
        jsonDataString.chief = dataStr[0].content || '';      //主诉
        jsonDataString.present = dataStr[1].content || '';     //现病史
        jsonDataString.other = dataStr[2].content || '';      //其他史
        jsonDataString.vital = dataStr[3].content || '';    //查体
        jsonDataString.lis = dataStr[4].content || '';      //检验导入填写
        jsonDataString.pacs = dataStr[5].content || '';     //检查
        jsonDataString.diag = dataStr[6].content || '';      //诊断
        jsonDataString.advice = dataStr[7].content || '';       //医嘱
        return jsonDataString;
    }
    if(show){
    return <div className={style['emer-box']} id="previewWrapper">      
            <div className={style['emer-content']}>
              <div id="previewStatic" className={`${style['closeModal']} drag-title`}><img src={closeIcon} className={style['img']} onClick={this.handleClose}/></div>
              <div className={style['emer-left']}>
                <HisList data={data} 
                        total={total} 
                        getMore={this.getMore} 
                        handleFilter={this.handleFilter}
                        detail={this.showDetail}
                        handleDownload={this.handleDownload}
                        changeInd={changeInd}/>
              </div>
              <div className={style['emer-right']}>
                {
                    baseObj == undefined || JSON.stringify(baseObj) == "{}" ? <p className={style['no-data']}>暂无数据</p> :
                    <PreviewBody
                        preInfo={preInfo}
                        dataJson={dataJson}
                        baseObj={baseObj}
                        dataStr={dataStr.length > 0?getAllDataStringList(dataStr):[]}
                        show={false}
                        flg={true}
                    ></PreviewBody>
                }
                <div className={style['emer-right-footer']}>
                  {baseObj&&baseObj.diagnoseSecond?<p className={style['diag-display']}>
                    <span>{baseObj.doctorNameSecond} {'在'}{baseObj.inquiryTimeSecond} 添加</span>
                    <span className={style['diag-cont']}>{baseObj.diagnoseSecond}{'（诊后添加）'}</span>
                  </p>:''}
                  <div className={style['add-diag']}>
                    <div>
                      <span>添加修正诊断：</span>
                      <input className={style['add-inp']} 
                            ref={this.searInp}
                            onInput={(e) => { 
                              this.handleInput(e)
                             }}
                            onPropertyChange={(e) => {  // 兼容ie
                                this.handleInput(e)
                            }}
                            disabled={data.length==0?true:false}/>
                      <span className={this.getBtnStyle()} onClick={!valChange?this.handleAdd:''}>确认添加</span>
                    </div>
                    <p className={style['add-tip']}>说明：修正诊断只会对导出数据有影响（只为AI建模使用）并不会对真实病历产生任何影响！</p>
                  </div>
                </div>
              </div>
                {searchData.length>0?<div className={style['search-list']}>
                      <ul>
                        {searchData.map((v,i)=>{
                          return <li key={v.questionId} onClick={this.handleListClick.bind(this,v)}>{v.name}{v.retrievalName?'('+v.retrievalName+')':''}</li>
                        })}
                      </ul>
                    </div>:''}
            </div>
          </div>
    }
    return ''
  }
}

export default EmergencyHis;