import React from 'react';
import style from './index.less';
import infoPic from "../../common/images/info-pic.png";
import chronicPic from "../../common/images/chronic.png";
import level1 from "../../common/images/级别1.png";
import printIcon from '@common/images/team.png';
import manageIcon from '@common/images/manage.png';
import tableIcon from '@common/images/table.png';
import allTableIcon from '@common/images/all-table.png';
import add from '@common/images/add-result.png';
import added from '@common/images/first.png';
import checkIcon from '@common/images/check.png';
import {ComplexModal,ConfirmModal,MiniToast, Radio,CheckBtn} from '@commonComp';
import AssessResult from '@containers/AssessResult';
import ScaleTable from '@containers/ScaleTable';
import Notify from '@commonComp/Notify';
import {deepClone} from '@utils/tools';
import $ from 'jquery';

/***
慢病右侧推送模块规则:
慢病--显示慢病名称以及管理和评估
普通病--不显示管理和评估和量表按钮
明细--量表-计算公式-核心指标
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,    //是否点击评估弹窗确定按钮
      tableName:'' , //点击的量表名称
      tableId:null ,//点击的量表id
      parentId:null ,
      parentIndex:null,
      radioVal:{},  //可能结果选择内容
      possible:{},  //可能结果
      formulaParam: {}, //量表计算公式计算入参
      showRecommend:false,      //显示推荐结果弹窗
      isRecommendConfirm:false,   //推荐结果确定
      isFormulaConfirm:false,     //计算公式确定
    };

    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.showAssessFn = this.showAssessFn.bind(this); //开关评估弹窗
    this.close = this.close.bind(this); //关闭量表列表
    this.showFormula = this.showFormula.bind(this); //打开计算公式
    this.closeFormula = this.closeFormula.bind(this); //关闭计算公式
    this.handleAddAssessItem = this.handleAddAssessItem.bind(this);   //加入病例记录
    this.handleSaveAssess = this.handleSaveAssess.bind(this);       //评估弹窗确定
    this.onPrint = this.onPrint.bind(this); 
    this.handleForRadio = this.handleForRadio.bind(this);
    this.showRecommendFn = this.showRecommendFn.bind(this);
    this.handleSaveCalcu = this.handleSaveCalcu.bind(this);     //保存评估修改的计算和可能结果
  }

  onPrint() {
    const {showHide} = this.props;
    let dom = showHide&&showHide.showTable?$("#printcontent"):$("#AssistResult");
    dom.jqprint({
      debug: false,
      importCSS: true,
      printContainer: true,
      operaSupport: false,
    });
  }
  
  showTableList(id){//量表按钮
    const {getTableList} = this.props;
    if(id){
      getTableList(id);
    }
  }
  close(){//关闭量表列表
    const {hideList} = this.props;
    hideList&&hideList({name:'showList',value:false});
  }
  handleListClick(item){//量表列表单项点击
    this.showTable(item,null);
    this.close()
  }

  showInfo(id){
    // 静态知识显示在提示信息里（4-18）
    const {getInfomation} = this.props;
    const param = {
      id:id,
      // id:40738, //目前只有“肾功能不全”有数据
      type:22,
    }
    getInfomation&&getInfomation(param);
  }
  closeInfo(){//关闭静态知识
    this.setState({
      infoId:null
    })
  }
  showOption(id){
    this.setState({
      optionId:id,
      formulaId:null //关闭计算公式
    })
  }
  closeOption(){
    this.setState({
      optionId:null
    })
  }
  showTable(it,parentId,parentIndex){
    const {formulaResult,scaleInfo} = this.props;
    // 密西根糖尿病周围神经病评分（MDNS）, id:40744
    const item = {
      id:it.id,
      name:it.name
    };
    // 判断：store里已经有该量表就无需重新调接口
    if(scaleInfo&&scaleInfo[it.id]){
      this.props.hideList({name:'showTable',value:true});
    }else{
      this.props.getScaleInfo(item);
    }

    this.setState({
      tableName:it.name,
      tableId:it.id,
      parentId:parentId,
      parentIndex:parentIndex,
      formulaId:null, //关闭计算公式和可能结果弹窗
      optionId:null
    })
  }
  closeTable(){
    this.setState({
      tableName:'',
      tableId:null,
      parentId:null,
    })
    this.props.hideList({name:'showTable',value:false});
  }
  showAssessFn(){
    this.setState({
      showAssess:!this.state.showAssess,
      isAssessConfirm:false
    });
  }
  showRecommendFn(){
    this.setState({
      isRecommendConfirm:false,
      showRecommend:!this.state.showRecommend,
    });
  }
  showFormula(id){//计算公式
    this.setState({
      formulaId:id,
      optionId:null  //关闭可能结果
    })
  }
  closeFormula(){
    this.setState({
      formulaId:null
    })
  }
  handleAddAssessItem(v,pIndex,i){
    const {addAssessItem} = this.props;
    addAssessItem(v,pIndex,i);
  }
  handleSaveRecommend(){
    this.setState({
      isRecommendConfirm:true
    });
    const that=this;
    setTimeout(()=>{
      that.showRecommendFn();
    });
  }
  handleSaveAssess(){
    this.setState({
      isAssessConfirm:true
    });
    const that=this;
    setTimeout(()=>{
      that.showAssessFn();
    });
  }
  handleInputformula(v,i, j,idd,  e) {
    const { data, setChronicPush,calcuValues } = this.props;
    let data1 = JSON.parse(JSON.stringify(data));
    if(calcuValues&&calcuValues[data1[i].id]){
      data1[i].details[j].content=calcuValues&&calcuValues[data1[i].id];
    }
    const text = e.target.value;
    if (data1[i].details) {
      data1[i].details[j].content.details[idd].value = text
    }

    setChronicPush(data1,data1[i].id,data1[i].details[j].content)
  }
  handleForRadio(ii,v,i, j,idd, ind){//计算公式
    const { data, setChronicPush,calcuValues } = this.props;
    const data1 = JSON.parse(JSON.stringify(data));
    if(calcuValues&&calcuValues[data1[i].id]){
      data1[i].details[j].content=calcuValues&&calcuValues[data1[i].id];
    }
    if (data1[i].details) {
      for(let z = 0; z <  data1[i].details[j].content.details[idd].details.length; z++) {
        data1[i].details[j].content.details[idd].details[z].state = 0
      }
      data1[i].details[j].content.details[idd].details[ind].state = 1
    }
    setChronicPush(data1,data1[i].id,data1[i].details[j].content);
  }
  confirmFormula(){//计算公式确定
    this.setState({
      isFormulaConfirm:true,
      formulaId:null
    });
  }
  handleRadio(item,parent){//可能结果
    let {radioVal} = this.props;
    this.setState({
      radioVal:Object.assign({},radioVal,{[parent.id]:item.detailName})
    })
  }
  confirmOption(parent,pIndex){//可能结果确定
    const {radioVal,possible} = this.state;
    const {savePossibleResult} = 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)})
  }
  handleSaveCalcu(obj){
    this.setState({
      possible:Object.assign({},obj.possible),
      radioVal:Object.assign({},obj.radioVal),//不设置radioVal只有最近一次选中的值
    })
  }
  calcuFormula(item,j, v, i) { //计算公式计算
    const { calcuFormula, data ,chronicPushItems,calcuValues} = this.props;
    let pushObj = deepClone(chronicPushItems);
    if(calcuValues&&calcuValues[pushObj[i].id]){
      pushObj[i].details[j].content=calcuValues&&calcuValues[pushObj[i].id];
    }
    let it = pushObj[i].details[j];
    let allHasInfo = true;
    for (let i = 0; i < it.content.details.length; i++) {
      if(it.content.details[i].controlType == 2) {  //输入框类型的有没有填值
        if(!it.content.details[i].value) {
          allHasInfo = false
        }
      } else if(it.content.details[i].controlType == 1) {
        let hasSelect = false
        for( let z = 0; z <it.content.details[i].details.length; z++) {
          if(it.content.details[i].details[z].state == 1) {
            hasSelect= true
          }
        }
        if(!hasSelect) {
          allHasInfo = false
        }
      }

    }
    if(allHasInfo) { //所有都有值，则计算
      let param = {
        type: 2,
        data: it,
        disId: v.id,
        pIndex: j,
        ppIndex: i
      };
      calcuFormula({param,chronicPushItems:pushObj})
    } else {  //不是所有值都填过了
      Notify.info('请填写计算公式内容')
    }
  }
  getDetail(){
    const {data,indexs,formulaResult,calcuResult,calcuValues} = this.props;
    const {formulaId,optionId,possible,radioVal,isFormulaConfirm} = this.state;
    let list = data&&data.map((v,i)=>{
                    return <div className={style["list"]}>
                      {v.name?<p>
                                <span>{'患者可能有'+v.name}</span>
                                <img src={infoPic} 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.id,i)}>{'【'+it.content.name+'】'}</i>
                                  {formulaResult&&formulaResult[it.content.id]?<i>{'结果：'}{formulaResult[it.content.id].calcalculate&&formulaResult[it.content.id].calcalculate.result.value +' '+ formulaResult[it.content.id].calcalculate.result.text}</i>:''}
                                </span>
                                {indexs[i]&&indexs[i].includes(j)?<span className={style["addResult"]}>
                                  <img src={added} />
                                  已加入
                                </span>:<span className={style["listResult"]} onClick={()=>this.handleAddAssessItem(v,i,j)}>
                                  <img src={add} />
                                  加入病历记录
                                </span>
                                }
                              </p>
                        }else if(it.type==2){
                          const cres = calcuResult&&calcuResult[v.id]||it.content.result;
                          const result = cres&&cres[1]&&cres[1].text;
                          const details = calcuValues&&calcuValues[v.id]&&calcuValues[v.id].details||it.content.details;
                          return <div className={style["marTop"]}>
                            <span className={style["limit"]}>
                              计算公式结果：
                              <i className={style["blue"]} onClick={this.showFormula.bind(this,v.id)}>{result?result:'请选择'}</i>
                              <img src={level1} />
                            </span>
                            {indexs[i]&&indexs[i].includes(j)?<span className={style["addResult"]}>
                                  <img src={added} />
                                  已加入
                                </span>:<span className={style["listResult"]} onClick={()=>this.handleAddAssessItem(v,i,j)}>
                                  <img src={add} />
                                  加入病历记录
                                </span>
                            }
                            {formulaId&&formulaId==v.id&&<MiniToast title={it.content.name}
                                icon={allTableIcon}
                                show={formulaId&&formulaId==v.id?true:false}
                                close={this.closeFormula}
                                confirm={this.confirmFormula.bind(this,v,i)}
                                footer="true">
                                <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={this.handleForRadio.bind(this,ii,v,i, j,idd, ind)}>
                                                      </Radio>
                                                  </div>
                                          })}
                                        </td>  
                                      </tr>
                                    }else if(item.controlType==2){//输入框
                                      return <tr>
                                        <td>
                                          <span>{'请输入'+item.name+'：'}</span>
                                        </td>
                                        <td>
                                          <input type="text" placeholder="请输入"  value={item.value} onInput={this.handleInputformula.bind(this,v,i, j,idd)}/>
                                        </td>
                                        <td>
                                          <span>{item.uint}</span>
                                        </td>
                                        
                                      </tr>
                                    }
                                })}
                                </table>
                                <div className={style["forMulBtn"]} onClick={this.calcuFormula.bind(this,it,j, v, i)}>计算</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.id)} className={style["blue"]}>{possible[v.id]?possible[v.id]:'请选择'}</i>
                              <img src={level1} />
                            </span>
                            {indexs[i]&&indexs[i].includes(j)?<span className={style["addResult"]}>
                                  <img src={added} />
                                  已加入
                                </span>:<span className={style["listResult"]} onClick={()=>this.handleAddAssessItem(v,i,j)}>
                                  <img src={add} />
                                  加入病历记录
                                </span>
                            }
                            <MiniToast title='结果选择'
                                icon={checkIcon}
                                show={optionId&&optionId==v.id?true:false}
                                close={this.closeOption}
                                confirm={this.confirmOption.bind(this,v,i)}
                                footer="true">
                                <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.id]==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;
  }

  render(){
    const footer = <div className={style['footer']}>
      <span className={style['print']} onClick={this.onPrint}><img src={printIcon} alt=""/>打印</span>
      <span className={style['okBtn']} onClick={()=>this.handleSaveAssess()}>确定</span>
    </div>;
    const recFooter =<div className={style['footer']}>
      <span className={style['okBtn']} onClick={()=>this.handleSaveRecommend()}>确定</span>
    </div>;
    const scaleFooter = <div className={style['footer']}>
      <span className={style['print']} onClick={this.onPrint}><img src={printIcon} alt=""/>打印</span>
      <span className={style['okBtn']} onClick={()=>this.closeTable()}>确定</span>
    </div>;
    const {chronicMagItem,tableList,saveAssessInfos,chronicDesease,formulaResult,showHide,calcuFormula} = this.props;
    const {showAssess,isAssessConfirm,tableName,tableId,parentId,parentIndex,isRecommendConfirm,showRecommend,radioVal,possible} = this.state;
    return <div className={style["tips"]} style={{marginBottom:'15px'}}>
              <div className={`${style["tips-title"]} ${style["chronic"]}`}>
                <div className={style["tips-name"]}>
                  <img src={chronicPic} />
                  <h2>{chronicMagItem&&chronicMagItem.name||chronicDesease&&chronicDesease.name||'病情提示'}</h2>
                  <span className={style["redTips"]}>(页面信息有更新可能影响评估结果)</span>
                </div>
                <div className={style["tips-btn"]} style={{display:chronicMagItem&&chronicMagItem.name||chronicDesease&&chronicDesease.name?'block':'none'}}>
                  <span
                    className={style["tipsDetails"]}
                    style={{width:'70px'}}
                    onClick={this.showAssessFn}
                  >
                    管理和评估
                  </span>
                  <span className={style["tipsDetails"]} onClick={() => this.showTableList(chronicDesease&&chronicDesease.id||chronicMagItem&&chronicMagItem.id)}>量表
                  </span>
                </div>
                <div className={style["tips-btn"]} style={{display:chronicMagItem&&chronicMagItem.name||chronicDesease&&chronicDesease.name?'none':'block'}}>
                <span
                  className={style["tipsDetails"]}
                  style={{width:'70px'}}
                  onClick={this.showRecommendFn}
                >
                    推荐结果
                  </span>
                </div>
              </div>
              <div className={style["content"]}> 
                  {this.getDetail()}
              </div>
              <ConfirmModal visible={showHide&&showHide.showList} noFooter='true' title='全部量表' close={this.close} titleBg="#DFEAFE" icon={allTableIcon} height={450} width={450}>
                      <ul className={style['toast-cont']}>
                        {tableList&&tableList.map((v,i)=>{
                          return <li>
                            <span className={style["scaleName"]}>
                              <i onClick={this.handleListClick.bind(this,v)}>{'【'+v.name+'】'}</i>
                              {formulaResult&&formulaResult[v.id]?<i className={style['res']}>{'结果：'}{formulaResult[v.id].calcalculate&&formulaResult[v.id].calcalculate.result.value+' '+ (formulaResult[v.id].calcalculate.result.text?formulaResult[v.id].calcalculate.result.text:'')}</i>:''}
                            </span>
                            <span className={style["listResult"]} onClick={()=>this.handleAddAssessItem(v,i,j)}>
                              <img src={add} />
                              加入病历记录
                            </span>
                          </li>
                        })}
                      </ul>
              </ConfirmModal>
              {showHide&&showHide.showTable?<ComplexModal onclose={this.closeTable} footer={scaleFooter}
                      title={tableName}
                      icon={tableIcon}
                      top={20}
                      bottom={20}
                      width={820}>
                <ScaleTable title={tableName} tableId={tableId} parentId={parentId} parentIndex={parentIndex}></ScaleTable>
              </ComplexModal>:''}
              {showAssess?<ComplexModal onclose={this.showAssessFn} footer={footer}
                      title='管理和评估'
                      icon={manageIcon}
                      top={'3%'}
                      bottom={'3%'}
                      width={820}>
                <AssessResult handleSave={saveAssessInfos}
                              handleSaveCalcu={this.handleSaveCalcu}
                              closeAssess={this.showAssessFn}
                              showScaleFn={this.showTable.bind(this)}
                              calcuFormula={calcuFormula}
                              radioVal={radioVal}
                              possible={possible}
                              isAssessConfirm={isAssessConfirm}></AssessResult>
              </ComplexModal>:''}
              {showRecommend?<ComplexModal onclose={this.showRecommendFn} footer={recFooter}
                                        title='推荐结果'
                                        icon={manageIcon}
                                        top={20}
                                        bottom={20}
                                        width={820}>
                <AssessResult handleSave={saveAssessInfos}
                              handleSaveCalcu={this.handleSaveCalcu}
                              closeAssess={this.showRecommendFn}
                              isRecommend={true}
                              showScaleFn={this.showTable.bind(this)}
                              calcuFormula={calcuFormula}
                              radioVal={radioVal}
                              possible={possible}
                              isAssessConfirm={isRecommendConfirm}></AssessResult>
              </ComplexModal>:''}
      </div>
  }
}
export default ChronicInfo;