import React from 'react';
import style from './index.less';
import chronicPic from "../../common/images/chronic.png";
import level1 from "../../common/images/级别1.png";
import tableIcon from '@common/images/table.png';
import allTableIcon from '@common/images/all-table.png';
import checkIcon from '@common/images/check.png';
import up from '@common/images/slide-up.png';
import down from '@common/images/slide-down.png';
import {ComplexModal,ConfirmModal,MiniToast, Radio,CheckBtn,Footer,Notify} from '@commonComp';
import infoShow from '@common/images/info-show.png';
import infoMove from '@common/images/info-move.png';
import ScaleTable from '@containers/ScaleTable';
import {deepClone} from '@utils/tools';
import $ from 'jquery';
import config from '@config/index';

/***
慢病右侧推送模块规则:
慢病--显示慢病名称以及管理和评估
普通病--不显示管理和评估和量表按钮
明细--量表-计算公式-核心指标
controlType:0-radio  1-checkbox  2-text  3-dropdownlist
**/

class ChronicInfo extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      show:true,
      showInfo:false,
      showOption:false,
      showAssess:false,      //评估弹窗
      infoId:null,  //静态知识
      formulaId:null, //计算公式
      optionId:null,  //可能结果,
      isAssessConfirm:false,    //是否点击评估弹窗确定按钮
      radioVal:{},  //可能结果选择内容
      possible:{},  //可能结果
      formulaParam: {}, //量表计算公式计算入参
      isCalculated:false,     //是否刚计算过，关闭时值与结果对应
      calcuValues:deepClone(props.calcuValues),       //计算公式填的值
      hasEnterImg: false, //是否移入info
      currentIndex: -1, //当前index
      comfirnFlag:false,
      flag:true,
      ff:false,
      timer:null,
	  scaleParam:{},    //加入病例需要的参数
    };
    this.$result = React.createRef();
    this.$content = React.createRef();
    this.showInfo = this.showInfo.bind(this);
    this.closeInfo = this.closeInfo.bind(this);
    this.showOption = this.showOption.bind(this);
    this.closeOption = this.closeOption.bind(this);
    this.showTable = this.showTable.bind(this);//显示量表弹窗
    this.closeTable = this.closeTable.bind(this);//关闭量表弹窗
    this.showFormula = this.showFormula.bind(this); //打开计算公式
    this.handleAddAssessItem = this.handleAddAssessItem.bind(this);   //加入病例记录
    this.onPrint = this.onPrint.bind(this);
    this.handleForRadio = this.handleForRadio.bind(this);
    this.handleSaveCalcu = this.handleSaveCalcu.bind(this);     //保存评估修改的计算和可能结果
    this.slideToggle = this.slideToggle.bind(this);
    this.resetComfirnFlag = this.resetComfirnFlag.bind(this);
    this.slideToggle = this.slideToggle.bind(this);
    this.comfirnTable = this.comfirnTable.bind(this);
	  this.unscroeClose = this.unscroeClose.bind(this);
  }

  onPrint() {
    const {showHide} = this.props;
    let dom = showHide&&showHide.showTable?$("#printcontent"):$("#AssistResult");
    dom.jqprint({
      debug: false,
      importCSS: true,
      printContainer: true,
      operaSupport: false,
    });
  }
  showInfo(item){
    // 静态知识显示在提示信息里（4-18）
    const {getInfomation} = this.props;
    const param = {
      id:item.id,
      name: item.name,
      // id:40738, //目前只有“肾功能不全”有数据
      type:22,
      position: 1
    }
    getInfomation&&getInfomation(param);
  }
  closeInfo(){//关闭静态知识
    this.setState({
      infoId:null
    })
  }
  showOption(id){
    this.setState({
      optionId:id,
      formulaId:null //关闭计算公式
    });
    const {patDom} = this.props;
    const ht = $(patDom.current).height();
    setTimeout(function(){
      $(patDom.current).scrollTop(ht+200);
    })
  }
  closeOption(){
    // 关闭-有可能结果则保持与结果一致，没有就保持最新选择的内容
    let {possible,radioVal} = this.state;
    if(JSON.stringify(possible)=='{}'){
      this.setState({
        optionId:null
      })
    }else{
      this.setState({
        radioVal:Object.assign({},radioVal,possible),
        optionId:null,
      });
    }
  }
  showTable(it,v,i,j){
    const {scaleInfo} = this.props;
    // 密西根糖尿病周围神经病评分（MDNS）, id:40744
    const item = {
      conceptId:it.conceptId,
      name:it.name
    };
    // 判断：store里已经有该量表就无需重新调接口
    if(scaleInfo&&scaleInfo[it.conceptId]){
      this.props.hideList({name:'showTable',value:true},it);
    }else{
      this.props.getScaleInfo(item);
    }

    this.setState({
      formulaId:null, //关闭计算公式和可能结果弹窗
      optionId:null,
      scaleParam:{
        v,i,j
      }
    })
  }
  // 量表明细-关闭,isClose是否是点击关闭按钮
  closeTable(isClose){
    const {scaleParam} = this.state;
    const {showHide} = this.props;
    if(!showHide.isPop){
      //量表结果，判断需要计算并且dom中有值才能加入病例记录
      const res = this.$result.current&&this.$result.current.innerText;
      if(!isClose&&(this.$result.current&&!res)){
        Notify.info("请先计算量表结果！");
        return ;
      }
      !isClose&&this.handleAddAssessItem(scaleParam.v,scaleParam.i,scaleParam.j);
      this.setState({
        scaleParam:{}
      });
    }
    this.props.hideList({name:'showTable',value:false});
  }
  // 非计分量表确定-延时关闭->量表存值
  unscroeClose(){
    let {timer} = this.state;
    this.setState({
      ff:true
    })
    clearTimeout(timer)
    let _timer = setTimeout(()=>{
      this.closeTable();
    },200) 
    this.setState({
      timer:_timer
    })
  }
  // 量表明细-确定
  comfirnTable(){
    const {flag} = this.state;
    this.setState({
      comfirnFlag:true,
      flag:!flag //触发更新
    })
  }
  resetComfirnFlag(){
    this.setState({
      comfirnFlag:false,
      ff:false
    })
  }
 
  showFormula(id){//计算公式
    this.setState({
      formulaId:id,
      optionId:null  //关闭可能结果
    });
    const {patDom} = this.props;
    const ht = $(patDom.current).height();
    setTimeout(function(){
      $(patDom.current).scrollTop(ht+200);
    })
  }
  closeFormula(it){
    const {formulaId,isCalculated} =this.state;
    if(!isCalculated){
      //没有计算结果时，保存输入的值
      const {calcuResult,calcuValues} = this.props;
      const cres = calcuResult&&calcuResult[formulaId]||it.content.result;
      const result = cres&&cres[1]&&cres[1].text;
      if(result){
        this.setState({
          calcuValues:deepClone(calcuValues)
        });
      }
    }
    this.setState({
      formulaId:null,
    });
  }
  handleAddAssessItem(v,pIndex,i){
    const {addAssessItem,showHide,addScaleItems,scaleInfo} = this.props;
    if(!v){
      addScaleItems(scaleInfo[showHide.conceptId],showHide.conceptId);
      return ;
    }
    addAssessItem(v,pIndex,i);
  }
  addFormula(it,v,pIndex,i){
    const {chronicMagItem} = this.props;
    this.closeFormula(it);
    chronicMagItem&&this.handleAddAssessItem(v,pIndex,i);
  }
  handleReg(e){   //只能输入数字和特殊符号
    //const hasDot = e.target.value.indexOf('.')!=-1;
    // const key = e.key;
    // if(key!='Backspace'&&((/[^\d|.\/%*~]/.test(key)))){
    //   e.preventDefault();
    // }
  }
  handleInputformula(id,calcuContent,i,e) {
    const {calcuValues} = this.state;
    let obj = deepClone(calcuValues);
    let values = (obj&&obj[id])||deepClone(calcuContent);
    const txt = e.target.value;
    values[i].value = txt.replace(/[\u4e00-\u9fa5]|[^\d|.\/%*~]/g,'');       //处理中文输入法的情况
    obj[id] = values;
    if(/[\u4e00-\u9fa5]|[^\d|.\/%*~]/g.test(txt)){
      e.target.value = txt.replace(/[\u4e00-\u9fa5]|[^\d|.\/%*~]/g,'');
    }
    this.setState({
      isCalculated:false,
      calcuValues:obj
    });
  }
  handleForRadio(id,calcuContent,i,fidx){//计算公式
    const { calcuValues } = this.state;
    let obj = deepClone(calcuValues);
    let values = (obj&&obj[id])||deepClone(calcuContent);
    let details = values[i].details;
    for(let x=0;x<details.length;x++){
      if(x!=fidx){
        details[x].state=0;
      }else{
        details[x].state=1;
      }
    }
    obj[id] = values;
    this.setState({
      isCalculated:false,
      calcuValues:obj
    });
  }
  handleRadio(item,parent){//可能结果
    let {radioVal} = this.props;
    this.setState({
      radioVal:Object.assign({},radioVal,{[parent.conceptId]:item.detailName})
    })
  }
  confirmOption(parent,pIndex,i){//可能结果确定
    const {radioVal,possible} = this.state;
    const {savePossibleResult,chronicMagItem} = this.props;
    this.setState({
      possible:Object.assign({},possible,radioVal),
      radioVal:Object.assign({},possible,radioVal),//不设置radioVal只有最近一次选中的值
      optionId:null,
    });
    savePossibleResult&&savePossibleResult({possible:Object.assign({},possible,radioVal),radioVal:Object.assign({},possible,radioVal)})
    chronicMagItem&&this.handleAddAssessItem(parent,pIndex,i);

  }
  handleSaveCalcu(obj){
    this.setState({
      possible:Object.assign({},obj.possible),
      radioVal:Object.assign({},obj.radioVal),//不设置radioVal只有最近一次选中的值
    })
  }
  calcuFormula(id,it) { //计算公式计算
    const { calcuFormula } = this.props;
    let item = deepClone(it);
    const values = this.state.calcuValues;
    const calcuValues = Object.keys(values).length&&values[id]?values[id]:item.content.details;
    let allHasInfo = true;
    for (let i = 0; i < calcuValues.length; i++) {
      if(calcuValues[i].controlType == 2) {  //输入框类型的有没有填值
        if(!calcuValues[i].value) {
          allHasInfo = false;
        }
      } else if(calcuValues[i].controlType == 0) {
        let hasSelect = false;
        for( let z = 0; z <calcuValues[i].details.length; z++) {
          if(calcuValues[i].details[z].state == 1) {
            hasSelect= true;
          }
        }
        if(!hasSelect) {
          allHasInfo = false;
        }
      }
    }
    item.content.details = calcuValues;
    if(allHasInfo) { //所有都有值，则计算
      let param = {
        type: 2,
        data: item,
        disId: id
      };
      calcuFormula(param);
      this.setState({
        isCalculated:true
      });
    } else {  //不是所有值都填过了
      Notify.info('请填写计算公式内容')
    }
  }
  handleMouseEnterDrug(index) {
    this.setState({
        currentIndex: index,
    })
  }
  handleMouseLeaveDrug() {
    this.setState({
        currentIndex: -1,
    })
  }
  handleMouseEnterImg() {
    this.setState({
      hasEnterImg: true
    })
  }
  handleMouseLeaveImg() {
    this.setState({
      hasEnterImg: false
    })
  }
  
  getDetail(){
    const {data,formulaResult,calcuResult,chronicMagItem} = this.props;
    const {formulaId,optionId,possible,radioVal,calcuValues,currentIndex,hasEnterImg} = this.state;
    let list = data&&data.map((v,i)=>{
                    return <div className={style["list"]}>
                      {v.name?<p>
                                <span>患者可能有</span>
                                <span
                                  className={style['dis-name']}
                                  onMouseEnter={this.handleMouseEnterDrug.bind(this, i)}
                                  onMouseLeave = {this.handleMouseLeaveDrug.bind(this)}
                                >
                                  {v.name}
                                  {<img className={style['info-img']}
                                    style ={currentIndex === i  ? {display: "inline-block"} : {display: "none"}}
                                    src={currentIndex === i ?(hasEnterImg ? infoMove : infoShow ): infoShow}
                                    onMouseEnter={this.handleMouseEnterImg.bind(this)}
                                    onMouseLeave = {this.handleMouseLeaveImg.bind(this)}
                                    onClick={this.showInfo.bind(this,v)}/>}

                                </span>
                                {/* <img src={infoShow} className={style["infoPic"]} onClick={this.showInfo.bind(this,v.id)}/> */}

                                ：
                              </p>:''}
                      {v.details&&v.details.map((it,j)=>{
                        if(it.type==1){
                          return <p>
                                <span className={style["listName"]}>
                                  <i onClick={this.showTable.bind(this,it.content,v,i,j)}>{'【'+it.content.name+'】'}</i>
                                  {formulaResult&&formulaResult[it.content.conceptId]?<i>{'结果：'}{formulaResult[it.content.conceptId].calcalculate&&formulaResult[it.content.conceptId].calcalculate.result.value +' '+ formulaResult[it.content.conceptId].calcalculate.result.text}</i>:''}
                                </span>
                              </p>
                        }else if(it.type==2){
                          const cres = calcuResult&&calcuResult[v.conceptId]||it.content.result;
                          const result = cres&&cres[1]&&cres[1].text;
                          const details = calcuValues&&calcuValues[v.conceptId]||it.content.details;
                          return <div className={style["marTop"]}>
                            <span className={style["limit"]}>
                              计算公式结果：
                              <i className={style["blue"]} onClick={this.showFormula.bind(this,v.conceptId)}>{result?result:'请选择'}</i>
                              <img src={level1} />
                            </span>
                            {formulaId&&formulaId==v.conceptId&&<MiniToast title={it.content.name}
                                icon={allTableIcon}
                                confirmText={chronicMagItem?'加入病历记录':'确定'}
                                show={formulaId&&formulaId==v.conceptId?true:false}
                                close={this.closeFormula.bind(this,it)}
                                confirm={this.addFormula.bind(this,it,v,i,j)}
                                footer={result?true:false}>
                                <table>
                                {details.map((item,idd)=>{
                                    if(item.controlType==0){//单选
                                      return <tr>
                                        <td>
                                          <span>{'请选择'+item.name+'：'}</span>
                                        </td>
                                        <td>
                                          {Array.isArray(item.details)&&item.details.map((ii,ind)=>{
                                            return <div className={style["chooseItem"]}>
                                                    <Radio label={ii.detailName}
                                                             isSelect={ii.state == 1}
                                                             handleClick={item.isShow == '0' ? '' : this.handleForRadio.bind(this,v.conceptId,details,idd,ind)}>
                                                      </Radio>
                                                  </div>
                                          })}
                                        </td>  
                                      </tr>
                                    }else if(item.controlType==2){//输入框
                                      return <tr>
                                        <td>
                                          <span>{'请输入'+item.name+'：'}</span>
                                        </td>
                                        <td>
                                          <input type="text" placeholder="请输入" readonly={item.isShow == '0'} value={item.value} onKeyDown={this.handleReg.bind(this)} onInput={this.handleInputformula.bind(this,v.conceptId,details,idd)}/>
                                        </td>
                                        <td>
                                          <span>{item.uint}</span>
                                        </td>

                                      </tr>
                                    }
                                })}
                                </table>
                                <div className={style["forMulBtn"]} onClick={this.calcuFormula.bind(this,v.conceptId,it)}>计算</div>
                                <table>
                                  {cres && Array.isArray(cres) &&cres.map((itemResult, resultIndex) => {
                                    return <tr>
                                        <td>
                                            <span>{itemResult.name+'：'}</span>
                                        </td>
                                        <td>
                                            <span>{itemResult.text}</span>
                                        </td>
                                    </tr>
                                  })}
                                </table>
                                
                            </MiniToast>}
                          </div>
                        }else if(it.type==3){
                          return <div className={style["marTop"]}>
                            <span className={style["limit"]}>
                              可能结果：
                              <i onClick={this.showOption.bind(this,v.conceptId)} className={style["blue"]}>{possible[v.conceptId]?possible[v.conceptId]:'请选择'}</i>
                              <img src={level1} />
                            </span>
                            <MiniToast title='结果选择'
                                icon={checkIcon}
                                confirmText={chronicMagItem?'加入病历记录':'确定'}
                                show={optionId&&optionId==v.conceptId?true:false}
                                close={this.closeOption}
                                confirm={this.confirmOption.bind(this,v,i,j)}
                                footer={radioVal[v.conceptId]?true:false}>
                                <div className={style["infoOption"]}>
                                  <span>{it.content.name?it.content.name+'：':''}</span>
                                  {it.content.details&&it.content.details.map((lis,ind)=>{
                                    return <div className={style["chooseItem"]}>
                                      <Radio label={lis.detailName}
                                               isSelect={radioVal[v.conceptId]==lis.detailName}
                                               handleClick={this.handleRadio.bind(this,lis,v)}>
                                        </Radio>
                                        {lis.state==1?<span className={style['recomand']}>（智能推荐）</span>:''}
                                    </div>
                                  })}
                                </div>
                            </MiniToast>
                          </div>
                        }
                      })}
                    </div>
                  })
    return list;
  }
  componentWillReceiveProps(next){
    if(JSON.stringify(next.calcuValues)!=JSON.stringify(this.props.calcuValues)){
      this.setState({
        calcuValues:next.calcuValues
      })
    }
    if (JSON.stringify(next.wholeResults.possible) != JSON.stringify(this.props.possible)) {
      this.setState({
        radioVal: next.wholeResults.radioVal,
        possible: next.wholeResults.possible
      })
    }
    if(next.slideUp!=this.props.slideUp){
      if(next.slideUp){
        $(this.$content.current).slideUp(config.slideTime);
      }else{
        $(this.$content.current).slideDown(config.slideTime);
      }
    }
  }
  slideToggle(){
    const {toggleSlide,slideUp} = this.props;
    toggleSlide&&toggleSlide(!slideUp);
  }
  render(){
    const {comfirnFlag,flag,ff} = this.state;
    const {chronicMagItem,chronicDesease,data,showHide,slideUp} = this.props;
    const scaleFooter = <Footer print={true}
                                footText={showHide.isPop||!chronicMagItem?"确定":"加入病历记录"}
                                handlePrint={this.onPrint}
                                handleConfirm={this.comfirnTable}/>;
    if(data&&data.length>0){
      return <div className={style["tips"]} style={{marginBottom:'15px'}}>
        <div className={`${style["tips-title"]} ${style["chronic"]}`} onClick={this.slideToggle}>
          <div className={style["tips-name"]}>
            <img src={chronicPic} />
            <h2>{chronicMagItem&&chronicMagItem.name||chronicDesease&&chronicDesease.name||'病情提示'}<span className={style["redTips"]}>(页面信息有更新可能影响评估结果)</span></h2>
          </div>
          <div className={style['toggle-btn']}>
            <img src={slideUp?down:up} alt="展开/收起"/>
          </div>
        </div>
        <div className={style["content"]} ref={this.$content}>
          {this.getDetail()}
        </div>
        {showHide&&showHide.showTable?<ComplexModal onclose={()=>this.closeTable(true)} footer={scaleFooter}
                                                    title={showHide.name}
                                                    icon={tableIcon}
                                                    top={20}
                                                    bottom={20}
                                                    width={820}>
          <ScaleTable title={showHide.name}
                      tableId={showHide.conceptId}
                      comfirnFlag={comfirnFlag}
                      flag={flag}
                      flagT={ff}
                      resetFlag={this.resetComfirnFlag}
                      unscroeClose={this.unscroeClose}
                      closeTable={this.closeTable}
                      resRef={this.$result}
          ></ScaleTable>
        </ComplexModal>:''}
      </div>
    }
    //量表弹窗-无指标推送时量表弹窗要单独加载
    if(showHide&&showHide.showTable){
      return <ComplexModal onclose={()=>this.closeTable(true)} footer={scaleFooter}
                           title={showHide.name}
                           icon={tableIcon}
                           top={20}
                           bottom={20}
                           width={820}>
        <ScaleTable title={showHide.name}
                    tableId={showHide.conceptId}
                    comfirnFlag={comfirnFlag}
                    flag={flag}
                    flagT={ff}
                    resetFlag={this.resetComfirnFlag}
                    unscroeClose={this.unscroeClose}
                    closeTable={this.closeTable}
                    resRef={this.$result}
        ></ScaleTable>
      </ComplexModal>;
    }



  }
}
export default ChronicInfo;