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 infoShow from '@common/images/info-show.png';
import infoMove from '@common/images/info-move.png';
import {ConfirmModal, Message,ComplexModal,Footer,Loading} 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 { 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 tableIcon from '@common/images/table.png';
import { CONFIRM_TYPE } from "@store/types/typeConfig";
import $ from "jquery";

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
        }
        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);
    }
    onPrint() {
      let dom = $("#AssistResult");
      dom.jqprint({
        debug: false,
        importCSS: true,
        printContainer: true,
        operaSupport: false,
      });
    }
    upDiagnostic(index) {
        const { upDiagnostic } = this.props;
        upDiagnostic && upDiagnostic(index)
    }
    downDiagnostic(index) {
        const { downDiagnostic } = this.props;
        downDiagnostic && downDiagnostic(index)
    }
    deleteItem() {
        const { delItem } = this.state;
        const { delDiagnostic, delReact,delFollowUp } = this.props;
        delDiagnostic && delDiagnostic(delItem);
        delReact && delReact(delItem);
        delFollowUp && delFollowUp(delItem);
        this.setState({
            visible: false,
        })
        Notify.success('删除成功')
    }
    cancel() {
        this.setState({
            visible: false
        })
    }
    close() {
        this.setState({
            visible: false
        })
    }
    handleDeleteItem(item) {
        this.setState({
            visible: true,
            delItem: item,
        })
    }
    showTreat(item, index) {
        // item.treatIndex = index
        const  { showTreat, getTreatResult } = this.props;
        getTreatResult && getTreatResult(item);
        // showTreat && showTreat();//添加loading，移到async-actions中
        this.setState({
            treatTitle: item.name
        })
    } 
    handleClickDiag(item,noTips,noDetails,noNotify) {
        const { getTips } = this.props;
        // getTips && getTips(item);
        getTips && getTips({id:item.conceptId, type:7, name: item.name, position: 1},noTips,noDetails,noNotify);
    }
    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();
        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();
        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) {
      if (this.props.diagnosticStr != nextprops.diagnosticStr) {
        this.props.getBilling();
      }
    }
   
    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
      })
    }
    render(){
        const { list, treatment, showReferRecord, showHistoryCase ,chronicMagItem,loading,refreshScroller,windowWidth} = this.props;
        const {visible, treatTitle, showAssess, isAssessConfirm, assessId, disName, hasOndel, hasOnIndex,hasEnterItem,hasEnterImg} = this.state;
        const chronicList = JSON.parse(localStorage.getItem('chronic')||null);
        let isChronic = false;      //是否要显示管理评估
        const footer = <Footer print={true}
                               footText="确定"
                               handlePrint={this.onPrint}
                               handleConfirm={this.handleSaveAssess}/>;
        return(
                <div className={style['diaglist-wrap']}>
                    {list && (list.length > 0) && list.map((item, index) => {
                        const hasTreat = item.treat && ((item.treat.commonTreatment&&item.treat.commonTreatment.content) || (item.treat.surgeryTreatment&&item.treat.surgeryTreatment.content) || item.treat.treatment.length>0 ||(item.adverseReactions&&item.adverseReactions.length > 0)
                           || (item.drugHistory && item.drugHistory['慢病用药内容'] &&  item.drugHistory['慢病用药内容'].length > 0) || (item.drugHistory &&item.drugHistory['普通病用药内容'] &&  item.drugHistory['普通病用药内容'].length > 0) ||item.follow)
                        isChronic = chronicMagItem&&item.type==2&&chronicList&&chronicList.findIndex((it)=>it.conceptId==item.conceptId)!=-1;
                        return (<div draggable={true} 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>}
                                    {list.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   className={style['diag-name-box']} style={{maxWidth: windowWidth > 1024 ?windowWidth-900 +'px':'130px'}} onClick={this.handleClickDiag.bind(this,item,false,true,false)}>
                                        {item.name}
                                      </span>
                                      <img className={`${style['info-img']}`}
                                          title='点击i图标可查看详细说明'
                                          style ={hasEnterItem===index  ? {display: "inline-block"} : {display: "none"}}
                                          src={hasEnterImg ? infoMove : infoShow} 
                                          onMouseEnter={this.handleMouseEnterImg.bind(this)}
                                          onMouseLeave = {this.handleMouseLeaveImg.bind(this)}
                                          onClick={this.handleClickDiag.bind(this,item,false,false,false)}
                                      />
                                    </span> 
                                    {item.type === 1 ? <span className={style['diag-first']}>初诊</span> :<span className={style['diag-second']}> 复诊</span>}
                                    <span className={style['treat']}
                                          // style ={hasTreat ? '' : { color: 'gray', cursor: 'text'}}
                                          onClick={() =>{this.showTreat(item, index)}}>
                                          治疗方案
                                    </span>
                                    {isChronic?<span className={style['assess']}
                                          onClick={this.showAssessFn.bind(this,item)}>
                                        管理评估
                                    </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)}}/>
                        </div>)
                    })}
                     {treatment&&<Treat title={treatTitle} refreshScroller={refreshScroller}></Treat>}
                     {showAssess?<ComplexModal onclose={this.showAssessFn.bind(this)} footer={footer}
                                               title='管理和评估'
                                               icon={manageIcon}
                                               top={'3%'}
                                               bottom={'3%'}
                                               width={820}>
                       <AssessResult closeAssess={this.showAssessFn.bind(this)}
                                     disId={assessId}
                                     disName={disName}
                                     chronicMagItemName={list[0].name}
                                     isAssessConfirm={isAssessConfirm}
                                     ></AssessResult>
                      </ComplexModal>:''}
                    <ConfirmModal visible={visible} 
                                  okText='删除' 
                                  cancelText='取消' 
                                  confirm={this.deleteItem}  
                                  cancel={this.cancel}
                                  close={this.close}
                                  >
                                  <div className={style['del-msg']}>是否删除该诊断？</div> 
                    </ConfirmModal>
                    <ConfirmModal visible={showReferRecord} 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>
                    <Loading show={loading}/>
                </div>
               
        )
    }
}

export default DiagnosticList;