import React, { Component } from 'react';
import style from './index.less';
import del_icon from './img/delete.png'
import del_on from './img/delete-on.png'
import diagUp from './img/diagUp.png'
import diagDown from './img/diagDown.png'
import manageIcon from '@common/images/manage.png';
import singleB from './img/singleB.png';
import singleL from './img/singleL.png';
import {ConfirmModal, Message,ComplexModal,Footer,Loading, Add} from '@commonComp';
import Notify from '@commonComp/Notify';
import Treat from '@containers/Treat'
import store from '@store';
import { initItemList ,setInitHistory,getHistempDetail} from '@store/async-actions/historyTemplates';
import { getPageCoordinate,setPosition,pushAllDataList,inspectAndAssist ,deepClone,setFontColorSize} from '@utils/tools';
import { dragBox } from '@utils/drag';
import iconRadioDefault from '@common/images/icon-radio-default.png'
import iconRadioActive from '@common/images/icon-radio-active.png'
import AssessResult from '@containers/AssessResult';
import {getAssessData} from '@store/async-actions/fetchModules';
import DetailsModal from '@components/PushItems/DetailsModal';
import DiagResultSearch from '@containers/DiagResultSearch';
import tableIcon from '@common/images/table.png';
import { CONFIRM_TYPE } from "@store/types/typeConfig";
import config from '@config/index';
import $ from "jquery";
import {getMRAnalyse} from '@store/async-actions/pushMessage';

class DiagnosticList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            delItem: {},
            treatTitle: '',
            activeHistory: -1,
            sign:-1,
            showAssess:false,
            assessId:'',
            disName:'',
            isAssessConfirm:false,
            hasOndel: false,
            hasOnIndex: -1,
            activeItem:{},
            hasEnterItem: -1,
            hasEnterImg: false,
            timer:null,
            pageTop:''
        }
        this.deleteItem = this.deleteItem.bind(this);
        this.cancel = this.cancel.bind(this);
        this.close = this.close.bind(this);
        this.showTreat = this.showTreat.bind(this);
        this.handleClickDiag = this.handleClickDiag.bind(this);
        this.referRecord = this.referRecord.bind(this);
        this.noReferRecord = this.noReferRecord.bind(this);
        this.getHistoryCase = this.getHistoryCase.bind(this);
        this.closeHistoryCaseModal = this.closeHistoryCaseModal.bind(this);
        this.referCase = this.referCase.bind(this);
        this.handleSaveAssess = this.handleSaveAssess.bind(this);       //评估弹窗确定
        this.onPrint = this.onPrint.bind(this);
        this.hideTips=this.hideTips.bind(this);
        this.handleTcmShowSearch = this.handleTcmShowSearch.bind(this);
        this.handleSymShowSearch = this.handleSymShowSearch.bind(this);
        this.showTcmSearch=this.showTcmSearch.bind(this);
        this.showSymSearch=this.showSymSearch.bind(this);
    }
    onPrint() {
      let dom = $("#AssistResult");
      dom.jqprint({
        debug: false,
        importCSS: true,
        printContainer: true,
        operaSupport: false,
      });
    }
    upDiagnostic(index) {
        const { upDiagnostic,isTcm } = this.props;
        upDiagnostic && upDiagnostic(index,isTcm)
    }
    downDiagnostic(index) {
        const { downDiagnostic,isTcm } = this.props;
        downDiagnostic && downDiagnostic(index,isTcm)
    }
    deleteItem() {
        const { delItem,idxNum } = this.state;
        const { delDiagnostic, delReact,delFollowUp,isTcm } = this.props;
        delDiagnostic && delDiagnostic(delItem,idxNum,isTcm);
        delReact && delReact(delItem);      //删除对应不良反应
        delFollowUp && delFollowUp(delItem);    //删除对应回访记录
        this.setState({
            visible: false,
        })
        Notify.success('删除成功')
    }
    handleBlur(e,delItem,idxNum){
      const { delDiagnostic,isTcm } = this.props;
      let name = e.target.value
      if(name.trim() == ''){
        delDiagnostic && delDiagnostic(delItem,idxNum,isTcm);
      }
    }
    handleTcmShowSearch(e) {
        this.props.showTcm ? this.hideTcmSearch() : this.showTcmSearch()
        this.setState({pageTop: getPageCoordinate(e).boxTop})
        if (this.props.showTcm) {
            this.props.setHighter(48)
        } else {
            //this.props.getBilling({mode: 10});
            setPosition(e, "#searchOption", this.props.setHighter)
        }
    }
    handleSymShowSearch(e) {
        this.showSymSearch(this.props.showSym ? false : true)
        this.setState({pageTop: getPageCoordinate(e).boxTop})
        if (this.props.showSym) {
            this.props.setHighter(48)
        } else {
            this.props.getBilling({isTcm:true});
            setPosition(e, "#searchOption", this.props.setHighter)
        }
    }
    showTcmSearch(flag) {
        const {showTcmSearch} = this.props;
        showTcmSearch && showTcmSearch(flag)
    }
    showSymSearch(flag) {
        const {showSymSearch} = this.props;
        showSymSearch && showSymSearch(flag)
    }
    cancel() {
        this.setState({
            visible: false
        })
    }
    close() {
        this.setState({
            visible: false
        })
    }
    handleDeleteItem(item,idx) {
        this.setState({
            visible: true,
            delItem: item,
            idxNum:idx
        })
    }
    showTreat(item, idx) {
        const  { getTreatResult,getBilling,isTcm } = this.props;
        getTreatResult && getTreatResult(item,idx,isTcm);
        getBilling({isTcm});
    } 
    handleClickDiag(item) {
        const { getTips } = this.props;
        // getTips && getTips(item);
        getTips && getTips({id:item.conceptId, type:7, name: item.name, position: 0});
    }
    hideTips() {
      const { hideTipsDetailsModal } = this.props;
      hideTipsDetailsModal && hideTipsDetailsModal()
    }
    referRecord() {
        const { hideReferRecord, showHistoryCaseModal ,chronicMagItem,hisTemplates,autoFillModules,typeConfig} = this.props;
        hideReferRecord && hideReferRecord();
        // showHistoryCaseModal && showHistoryCaseModal()
        // store.dispatch(initItemList(chronicMagItem))
        initItemList(chronicMagItem).then((res)=>{
            const result = res.data;
            if(result.code==0 && result.data){
              store.dispatch(setInitHistory(result.data));
              showHistoryCaseModal && showHistoryCaseModal();
            }else{
              Notify.info("暂无历史病历，已默认展示慢病相关内容");
              const timer = setTimeout(function(){
                autoFillModules && autoFillModules();
                clearTimeout(timer);
              },1000) //需求要求延时
            }
        })
    }
    noReferRecord() {
        const { hideReferRecord ,autoFillModules,refreshScroller} = this.props;
        hideReferRecord && hideReferRecord();
        autoFillModules&&autoFillModules();
       
        store.dispatch(getMRAnalyse());
        setTimeout(function(){
          refreshScroller()&&refreshScroller().scrollTop();
        },100)
    }
    referCase() {//确定
        const { hideHistoryCaseModal, items ,autoFillModules,typeConfig} = this.props;
        const {sign,activeItem} = this.state;
        hideHistoryCaseModal && hideHistoryCaseModal()
        if (this.state.activeHistory === -1) {//没有选择历史病例直接点确定
            Notify.info("未选择历史病历，已默认展示慢病相关内容");
              const timer = setTimeout(function(){
                autoFillModules && autoFillModules();
                clearTimeout(timer);
              },1000)
            return
        }
        // let baseList = store.getState();
        // let baseObj = items[this.state.activeHistory];
        // pushAllDataList(baseObj.sign,'push',baseObj,'history')       //引用
        store.dispatch(getHistempDetail(activeItem));
        this.props.getBilling({mode:10});
        this.setState({
            activeHistory: -1,
            sign:-1,
            activeItem:{}
        })
    }
    closeHistoryCaseModal() {
        const { hideHistoryCaseModal ,autoFillModules,typeConfig} = this.props
        this.setState({
            activeHistory: -1,
            sign:-1,
            activeItem:{}
        })
        hideHistoryCaseModal && hideHistoryCaseModal()
        autoFillModules&&autoFillModules();
    }
    handleQuoteClick(item, index) {
        // const { handleQuoteClick } = this.props
        // handleQuoteClick && handleQuoteClick(item)
        this.setState({
            activeHistory: index,
            sign:item.sign,
            activeItem:item
        })
    }
    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: '#3B9ED0'} : ''}>
                    <img src={this.state.activeHistory === index ? iconRadioActive : iconRadioDefault}/>{item.diagnose} {item.inquiryDate}
                </div>
            })}
        </div>)
    }
    showAssessFn(item){
      const {setAssess} = this.props;
      const that = this;
        if(item&&item.conceptId){         //显示评估弹窗
          getAssessData(item.conceptId,item.name).then((res)=>{
            if(res.data.code=='0'){
              const data = res.data.data;
              if(!data||data.length==0){
                Notify.info('暂无数据');
              }else{
                setAssess&&setAssess(data,item.name);
                that.setState({
                  showAssess:true,
                  isAssessConfirm:false,
                  assessId:item.conceptId,
                  disName:item.name
                });
              }
            }else{
              Notify.error(res.data.msg);
            }
          }).catch(error=>{
            console.log(error);
          });
        }else{          //关闭评估弹窗
            this.setState({
              showAssess:false,
              isAssessConfirm:false,
            });
            dragBox('dragModalWrap','dragModalTitle','del')
        }
    }
    handleSaveAssess(){
      this.setState({
        isAssessConfirm:true
      });
      const that=this;
      setTimeout(()=>{
        that.setState({
          showAssess:false
        });
      });
      dragBox('dragModalWrap','dragModalTitle','del')
    }
    componentWillReceiveProps(nextprops) {
      let flg = store.getState().print.mrInfo.mrId&&store.getState().print.mrInfo.mrId.indexOf('reStart')>-1
      if (this.props.diagnosticStr.split(',').length != nextprops.diagnosticStr.split(',').length&&!flg) {
        this.props.getBilling({mode:10});
      }
    }
   
    handleEnterDel(index) {
      this.setState({
        hasOnIndex: index,
        hasOndel: true
      })
    }
    handleLeaveDel() {
      this.setState({
        hasOnIndex: -1,
        hasOndel: false
      })
    }
    handleMouseEnterDrug(index) {
      this.setState({
          hasEnterItem: index, 
      })
    }
    handleMouseLeaveDrug() {
      this.setState({
          hasEnterItem: -1, 
      })
    }
    handleMouseEnterImg() {
      this.setState({
        hasEnterImg: true
      })
    }
    handleMouseLeaveImg() {
      this.setState({
        hasEnterImg: false
      })
    }
    handleFocus(flag){
      const {getBilling} = this.props;
      getBilling&&getBilling({isTcm:flag});
    }
    handleInput(e,index,isTcm){
      const {editDiagName,getBilling} = this.props;
      let name = (e.target.value).trim()
      editDiagName(index,name,isTcm)
      //右侧推送--延时推送
      const stimer = this.state.timer;
      clearTimeout(stimer);
      let timer = setTimeout(function(){
        getBilling&&getBilling({isTcm:!!isTcm});
        clearTimeout(stimer);
      },config.delayPushTime);
      this.setState({timer})
    }
    render(){
        const { list,tcmList, treatment,pushMessage, loading,refreshScroller,windowHeight,setHighter,isTcm} = this.props;
        const {showTipsDetails,tipsDetails,showAllName}=pushMessage;
        const {visible, treatTitle,  hasOndel, hasOnIndex,delItem} = this.state;
        const diagList = isTcm?tcmList:list;
        if(isTcm){      //中医，添加中医诊断后才显示中医症候添加按钮
            return(
                <div className={style['diaglist-wrap']}>
                    {diagList && (diagList.length > 0) && diagList.map((item, index) => {
                        const {tcmDiag,tcmSyndrome} = item;
                        return (<div draggable={false} className={`${style['diag-box']} ${setFontColorSize(2,3)} clearfix`} id="diagListBox" key={index} >
                            {index === 0 ? '' : <span className={style['diag-up']} onClick={() => {this.upDiagnostic(index)}}><img className={style["diag-up"]} src={diagUp}/></span>}
                            {diagList.length === 1 ? '' : index !== 0 ? '' : <span onClick={() => {this.downDiagnostic(index)}} className={style['diag-down']}><img className={style["diag-down"]} src={diagDown}/></span>}
                            <span className={style['diag-number']} style={{fontWeight:index === 0 ?'bold':'normal'}}>{index === 0 ? '1' : index+1}</span>

                                {tcmDiag?<span className={style['diag-name']}>
                                      <span title={tcmDiag} className={style['diag-name-box']} style={{'max-width': '300px'}}>
                                        <input type="text" value={tcmDiag} disabled={true}/>
                                      </span>

                                    </span>:<Add showText="添加中医诊断结果" isTcm={isTcm} handleClick={this.handleTcmShowSearch} id="addTcmDiag" height="50px" />}
                            {tcmSyndrome?<span className={style['diag-name']}>
                                      <span title={tcmSyndrome} className={style['diag-name-box']} style={{'max-width': '300px'}}>
                                        <input type="text" value={tcmSyndrome} disabled={true}/>
                                      </span>

                                    </span>:(tcmDiag?<Add showText="添加中医证候" isTcm={isTcm} handleClick={this.handleSymShowSearch} id="addSymDiag" height="50px" />:'')}
                                {tcmDiag&&tcmSyndrome?'':<DiagResultSearch
                                        refreshScroller={refreshScroller}
                                        setHighter={setHighter}
                                        windowHeight={windowHeight}
                                        pageTop={this.state.pageTop}
                                        isTcm={isTcm}
                                        height={150}>
                                    </DiagResultSearch>}
                                {tcmDiag&&tcmSyndrome?<span className={style['treat']}
                                  onClick={() =>{this.showTreat(item, index)}}>
                                          <img src={item.hasTreat?singleB:singleL} alt=""/>
                                          治疗方案
                                    </span>:''}
                            <img className={style['diag-del']} src={hasOnIndex == index ? hasOndel ? del_on : del_icon : del_icon} onMouseEnter={this.handleEnterDel.bind(this,index)} onMouseLeave={this.handleLeaveDel.bind(this)} onClick={()=>{this.handleDeleteItem(item,index)}}/>
                        </div>)
                    })}
                    {treatment&&<Treat title={treatTitle} refreshScroller={refreshScroller}></Treat>}
                    {showTipsDetails &&<DetailsModal
                        showTipsDetails = {showTipsDetails}
                        hideTips = {this.hideTips}
                        showAllName = {showAllName}
                        tipsDetails = {tipsDetails}/>}
                    <ConfirmModal visible={visible}
                                  okText='删除'
                                  cancelText='取消'
                                  confirm={this.deleteItem}
                                  cancel={this.cancel}
                                  close={this.close}
                    >
                        <div className={style['del-msg']}>是否删除中医诊断{delItem.tcmDiag}？</div>
                    </ConfirmModal>
                    <Loading show={loading}/>
                </div>

            )
        }
        return(
                <div className={style['diaglist-wrap']}>
                    {diagList && (diagList.length > 0) && diagList.map((item, index) => {console.log(diagList,item)

                        return (<div draggable={false} className={`${style['diag-box']} ${setFontColorSize(2,3)} clearfix`} id="diagListBox" key={item.conceptId} >
                                    {index === 0 ? '' : <span className={style['diag-up']} onClick={() => {this.upDiagnostic(index)}}><img className={style["diag-up"]} src={diagUp}/></span>}
                                    {diagList.length === 1 ? '' : index !== 0 ? '' : <span onClick={() => {this.downDiagnostic(index)}} className={style['diag-down']}><img className={style["diag-down"]} src={diagDown}/></span>}
                                    <span className={style['diag-number']} style={{fontWeight:index === 0 ?'bold':'normal'}}>{index === 0 ? '1' : index+1}</span>
                                    <span className={style['diag-name']} 
                                       onMouseEnter={this.handleMouseEnterDrug.bind(this,index)}
                                       onMouseLeave = {this.handleMouseLeaveDrug.bind(this)}
                                    >
                                      <span title={item.name} className={style['diag-name-box']} style={{'max-width': '300px'}}>
                                        <input type="text" value={item.name} onFocus={(e)=>{this.handleFocus()}} onBlur={(e)=>{this.handleBlur(e,item,index)}} onInput={(e)=>this.handleInput(e,index)}/>
                                      </span>

                                    </span>
                                    <span className={style['treat']}
                                          onClick={() =>{this.showTreat(item, index)}}>
                                          <img src={item.hasTreat?singleB:singleL} alt=""/>
                                          治疗方案
                                    </span>
                                    <img className={style['diag-del']} src={hasOnIndex == index ? hasOndel ? del_on : del_icon : del_icon} onMouseEnter={this.handleEnterDel.bind(this,index)} onMouseLeave={this.handleLeaveDel.bind(this)} onClick={()=>{this.handleDeleteItem(item,index)}}/>
                        </div>)
                    })}
                     {treatment&&<Treat title={treatTitle} refreshScroller={refreshScroller}></Treat>}
                    {showTipsDetails &&<DetailsModal
                        showTipsDetails = {showTipsDetails}
                        hideTips = {this.hideTips}
                        showAllName = {showAllName}
                        tipsDetails = {tipsDetails}/>}
                    <ConfirmModal visible={visible} 
                                  okText='删除' 
                                  cancelText='取消' 
                                  confirm={this.deleteItem}  
                                  cancel={this.cancel}
                                  close={this.close}
                                  >
                                  <div className={style['del-msg']}>是否删除西医诊断{delItem.name}？</div>
                    </ConfirmModal>
                    <Loading show={loading}/>
                </div>
               
        )
    }
}

export default DiagnosticList;