import React, { Component } from "react";
import style from "./index.less";
import possibleImg from "../../common/images/possible.png";
import doubtImg from "../../common/images/doubt.png";
import recommendImg from "../../common/images/recommend.png";
import tipsImg from "../../common/images/tips.png";
import vigilantImg from "../../common/images/vigilant.png";
import showImg from "../../common/images/show.png";
import hideImg from "../../common/images/close.png";
import infoPic from "../../common/images/info-pic.png";
import chronicPic from "../../common/images/chronic.png";
import level1 from "../../common/images/级别1.png";
import close from "../../common/images/close-icon.png";
import printIcon from '@common/images/team.png';
import DetailsModal from './DetailsModal';
import PushDiag from "./PushDiag";
import DiagnosticItem from "@containers/DiagnosticItem";
import store from "@store";
import { getWindowInnerHeight } from "@common/js/func";
import {addLabel} from '@store/actions/inspect';
import {addAssistLabel} from '@store/actions/assistCheck';
import {windowEventHandler} from '@utils/tools'
import {ConfirmModal,ComplexModal} from '@commonComp';
import AssessResult from '../AssessResult';
import mocks from '../../mock/chronicTable.js'

class PushItems extends Component {
  constructor(props) {
    super(props);

    this.state = {
      moreAssay: false,
      moreCheck: false,
      show:true,
      showInfo:false,
      showOption:false,
      showTable:false,
      showAssess:false      //评估弹窗
    };

    this.showMore = this.showMore.bind(this);
    this.closeMore = this.closeMore.bind(this);
    this.billing = this.billing.bind(this);
    this.changeAssay = this.changeAssay.bind(this);
    this.changeCheck = this.changeCheck.bind(this);
    this.showTips = this.showTips.bind(this);
    this.hideTips = this.hideTips.bind(this);
    this.showTableList = this.showTableList.bind(this);
    this.confirm = this.confirm.bind(this);
    this.close = this.close.bind(this);
    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.$cont = React.createRef();
  }

  showMore(type) {
    this.setState({ [type]: true });
  }

  closeMore(type) {
    this.setState({ [type]: false });
  }
  showAssessFn(){
    this.setState({
      showAssess:!this.state.showAssess
    });
  }
  getCurrentDate(){
    let myDate = new Date();
    let year = myDate.getFullYear();       //获取完整的年份(4位,1970-????)
    let mon = myDate.getMonth()-0+1;       //获取当前月份(0-11,0代表1月)
    let day = myDate.getDate();            //获取当前日(1-31)
    let date = year+'-'+(mon<10?'0'+mon:mon)+'-'+(day<10?'0'+day:day);
    return date;
  }

  billing() {
    const { assay, check } = this.props.pushMessage;
    const checkedAssay = assay.filter(item => item.checked);
    const checkedCheck = check.filter(item => item.checked);
    this.props.billing(checkedAssay, checkedCheck);
    // if(checkedAssay.length > 0 || checkedCheck.length > 0) {
    //   const Height = $(".src-components-BodyContainer-2SgEx").height();
    //   const adviceHeight = $(".src-common-components-ItemBox-1Bpz3").height();
    //   const winHeight = window.innerHeight;
    //   const scrollTop = Height;
    //   $('#addScrollEvent').scrollTop(100000)
    // }
    let obj = {   //添加化验
      details: [],
      name: '',
      questionId: '',
      showType: 1,
    }
    let obj1 = {  //添加辅检
      name: '',
      questionId: '',
      showType: 1,
      time:this.getCurrentDate(),
      value:''
    }
    if(checkedAssay.length > 0){
      let assayArr = [],tmpDetail=[]
      for(let i = 0;i < checkedAssay.length;i++){
        let tmpObj = JSON.parse(JSON.stringify(obj));
        if (checkedAssay[i].controlType == 0) {
          tmpDetail = checkedAssay[i].questionMapping
        }else if(checkedAssay[i].controlType == 1 || checkedAssay[i].controlType == 6){
          tmpDetail.push(checkedAssay[i])
        }
        tmpObj.questionId = checkedAssay[i].id
        tmpObj.name = checkedAssay[i].name
        tmpObj.details = tmpDetail
        assayArr.push(tmpObj)
      }
      store.dispatch(addLabel(assayArr))
    }
    if(checkedCheck.length > 0){
      let checkArr = []
      for(let i = 0;i < checkedCheck.length;i++){
        let tmpObj = JSON.parse(JSON.stringify(obj1));
        tmpObj.questionId = checkedCheck[i].id
        tmpObj.name = checkedCheck[i].name
        checkArr.push(tmpObj)
      }
      store.dispatch(addAssistLabel(checkArr))
    }
    if(checkedAssay.length > 0){
      document.getElementById("inspectResultData").scrollIntoView(true)
    }else{
      if(checkedCheck.length > 0){
        document.getElementById("assistResultData").scrollIntoView(true)
      }else{
        return;
      }
    }
  }

  changeAssay(item) {
    this.props.changeAssay(item);
  }

  changeCheck(item) {
    this.props.changeCheck(item);
  }

  showTips(tips) {
    const { getTipsDetails, showTipsDetailsModal } = this.props;
    getTipsDetails && getTipsDetails();
    showTipsDetailsModal && showTipsDetailsModal()
  }
  hideTips() {
    const { hideTipsDetailsModal } = this.props;
    hideTipsDetailsModal && hideTipsDetailsModal()
  }

  // 量表部分
  showTableList(id){//量表
    const {getTableList,questionId} = this.props;
    // getTableList(questionId&&questionId.id);
    if(id){
      getTableList(id);
    }
  }
  confirm(){
    const {hideList} = this.props;
    hideList&&hideList();
  }
  close(){
    const {hideList} = this.props;
    hideList&&hideList();
  }
  showInfo(){//显示静态知识
    this.setState({
      showInfo:true
    })
  }
  closeInfo(){//关闭静态知识
    this.setState({
      showInfo:false
    })
  }
  showOption(){
    this.setState({
      showOption:true
    })
  }
  closeOption(){
    this.setState({
      showOption:false
    })
  }
  showTable(){
    this.setState({
      showTable:true
    })
  }
  closeTable(){
    this.setState({
      showTable:false
    })
  }
  getTableInfo(){//整个量表模块
    const {chronicMagItem} = this.props;
    const {showInfo,showOption} = this.state;
    let info = 
        <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||'冠状动脉'}</h2>
                  <span className={style["redTips"]}>(页面信息有更新可能影响评估结果)</span>
                </div>
                <div className={style["tips-btn"]}>
                  <span
                    className={style["tipsDetails"]}
                    style={{width:'70px'}}
                    onClick={this.showAssessFn}
                  >
                    管理和评估
                  </span>
                  <span
                    className={style["tipsDetails"]}
                    onClick={() => this.showTableList(chronicMagItem&&chronicMagItem.id)}
                  >
                    量表
                  </span>
                </div>
              </div>
              <div className={style["content"]}>
                <div className={style["list"]}>
                  <p>
                    <span>患者可能有糖尿病周围神经病变</span>
                    <img src={infoPic} className={style["infoPic"]} onClick={this.showInfo}/>
                    ：
                  </p>
                  <p>
                    <span className={style["listName"]} onClick={this.showTable}>【密西根糖尿病周围神经病筛查表】</span>
                    <span className={style["listResult"]}>
                      结果：
                      <i>轻度</i>
                      {/*<img src={level1} />*/}
                    </span>
                  </p>
                  <div className={style["infoBox"]} style={{display:showInfo?'block':'none'}}>
                    <p className={style["infoTitle"]}>
                      静态知识
                      <img src={close} onClick={this.closeInfo}/>
                    </p>
                    <div className={style["infoCon"]}>
                      在美国，接受关节置换的病例中约8.5%为糖尿病患者。而糖尿病是关节置换术后各种并发症和死亡的危险因素之一，血糖控制不佳会加大此风险。 　　糖化血红蛋白（HbA1c）水平是衡量糖尿病控制是否良好的标准之一。研究发现HbA1c >7.0%者术后并发症率明显增加，但与术后深部感染并无特别关系。 　　美国学者Giori NJ等所在医院从2004年10月1日起对所有拟行全关节置换的糖尿病患者常规检测术前HbA1c水平。如果HbA1c >7.0%，则要求患者由其初级保健提供者
                    </div>
                  </div>
                </div>
              {/*核心指标*/}
                <div className={`${style["list"]} ${style["mainList"]}`}>
                  <p>
                    <span>患者可能有脑血管疾病</span>
                    <img src={infoPic} className={style["infoPic"]}/>
                    ：
                  </p>
                  <p>
                    <span className={style["listBtn"]}>加入病历记录</span>
                    <span className={style["listResult"]}>
                      可能结果：
                      <i onClick={this.showOption}>请选择</i>
                      <img src={level1} />
                    </span>
                  </p>
                  <div className={`${style["infoBox"]} ${style["mainBox"]}`} style={{display:showOption?'block':'none'}}>
                    <p className={style["infoTitle"]}>
                      结果选择
                      <img src={close} onClick={this.closeOption}/>
                    </p>
                    <div className={style["infoCon"]}>
                      <div className={style["infoOption"]}>
                        <span>是否贫血：</span>
                        <span>
                          <img src={infoPic} />
                          是
                        </span>
                        <span>
                          <img src={infoPic} />
                          否
                        </span>
                      </div>
                      <div className={style["infoConBtn"]}>
                        <span>确定</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
    return info;
  }
  componentDidMount() {
    const height = getWindowInnerHeight() - 200;
    this.$cont.current.style.height = height + "px";

    windowEventHandler('resize', ()=>{
      const height = getWindowInnerHeight() - 200;
      this.$cont.current.style.height = height + "px";
    });
  }

  render() {
    const {
      vigilant,
      determine,
      doubt,
      possible,
      assay,
      check,
      tips,
      showTipsDetails,
      tipsDetails,
      tmpFlg,
    } = this.props.pushMessage;
    const footer = <div className={style['footer']}>
      <span className={style['print']}><img src={printIcon} alt=""/>打印</span>
      <span className={style['okBtn']}>确定</span>
    </div>;
    const { tipsDiscalimer,tableList ,showList,chronicMagItem} = this.props;
    const { moreAssay, moreCheck ,show,showTable,showAssess} = this.state;
    const {
      showMore,
      closeMore,
      billing,
      changeCheck,
      changeAssay,
      showAdd,
      showTips,
      showTableList
    } = this;
    let assayNum = 0;
    let assayNum2 = 0; 
    let assayHide = assay.map((item, index) => {
      assayNum = assayNum + item.name.length + 2;
      if (assayNum > 28) {
        assayNum2 = assayNum2 + item.name.length + 2; 
        if(assayNum2 > 21) {
          return;
        } else {
          return (
            <span>
              
              <input
                id={item.id + item.name}
                onChange={() => changeAssay(item)}
                type="checkbox"
                checked={item.checked}
              />
              <label for={item.id + item.name}>{item.name}</label>
            </span>
          );
        }
      } else {
        return (
          <span>
            
            <input
              id={item.id + item.name}
              onChange={() => changeAssay(item)}
              type="checkbox"
              checked={item.checked}
            />
            <label for={item.id + item.name}>{item.name}</label>
          </span>
        );
      }
    });

    const assays = assay.map(item => {
      return (
        <span>
          <input
            id={item.id + item.name}
            onChange={() => changeAssay(item)}
            type="checkbox"
            checked={item.checked}
          />
          <label for={item.id + item.name}>{item.name}</label>
        </span>
      );
    });

    let checkNum = 0;
    let checkNum2 = 0;
    let checkHide = check.map((item, index) => {
      checkNum = checkNum + item.name.length + 2;
      if (checkNum > 28) {
        checkNum2 = checkNum2 + item.name.length + 2; 
        if(checkNum2 > 21) {
          return;
        }else {
          return (
            <span>
              <input
                id={item.id + item.name}
                onChange={() => changeCheck(item)}
                type="checkbox"
                checked={item.checked}
              />
              <label for={item.id + item.name}>{item.name}</label>
            </span>
          );
        }


        
      } else {
        return (
          <span>
            <input
              id={item.id + item.name}
              onChange={() => changeCheck(item)}
              type="checkbox"
              checked={item.checked}
            />
            <label for={item.id + item.name}>{item.name}</label>
          </span>
        );
      }
    });

    const checks = check.map(item => {
      return (
        <span>
          <input
            id={item.id + item.name}
            onChange={() => changeCheck(item)}
            type="checkbox"
            checked={item.checked}
          />
          <label for={item.id + item.name}>{item.name}</label>
        </span>
      );
    });

    const vigilants = vigilant.map((item, index) => {
      return <div key={item.id} className={style['push-diag-item']}><DiagnosticItem item={item}/></div>;
    });

    return (
      <div className={style["push-content-wrapper"]}>
        <div className={style["push-content"]} ref={this.$cont}>
          <div style = {{width: '420px'}}>
            {vigilant && vigilant.length > 0 && (
              <div className={style["vigilant"]}>
                <div className={style["title"]}>
                  <img src={vigilantImg} />
                  警惕
                </div>
                <div className={style["vigilantContent"]}>{vigilants}</div>
              </div>
            )}
            {/* 不展示确诊 */}
            {/* {determine && determine.length>0 && <PushDiag titleBg='#FAEBEC' icon={possibleImg} title='确诊' diagList={determine} maxShowNum={28}/>} */}
            {doubt && doubt.length > 0 && (
              <PushDiag
                titleBg="#FAEBEC"
                icon={doubtImg}
                title="疑似诊断"
                diagList={doubt}
                maxShowNum={26}
              />
            )}
            {possible && possible.length > 0 && (
              <PushDiag
                titleBg="#FAEBEC"
                icon={possibleImg}
                title="可能诊断"
                diagList={possible}
                maxShowNum={26}
              />
            )}
            <div className={style["diagnose"]}>
              {vigilant.length === 0 &&
                determine.length === 0 &&
                doubt.length === 0 &&
                possible.length === 0 && (
                  <div className={style["doubt"]}>
                    <h1>
                      <img src={doubtImg} />
                      疑似诊断
                    </h1>
                    <div className={style["no-push"]}>无</div>
                  </div>
                )}
            </div>

            <div className={style["recommend"]}>
              <h1>
                <img src={recommendImg} />
                推荐检验检查
                <div className={style["billing"]} 
                     style={assay.length === 0 && check.length === 0 ? {color: 'gray', border: '1px solid gray'} : ''} 
                     onClick={assay.length === 0 && check.length === 0 ? '' : billing}>
                    开单
                </div>
              </h1>
              <div>
                {assay.length === 0 && check.length === 0 ? (
                  <span>无</span>
                ) : (
                  <ul>
                    <li className={style["firstLi"]}>
                      <div className={style["title"]}>化验：</div>
                      <div className={style["content"]}>
                        {assay.length === 0
                          ?<span >无</span>
                          : moreAssay
                          ? assays
                          : assayHide}
                        {assayNum2 > 21 ? (
                          <span
                            style={
                              moreAssay
                                ? { display: "none" }
                                : { display: "inline-block" }
                            }
                            className={style["show"]}
                            onClick={() => showMore("moreAssay")}
                          >
                            更多
                            <img src={showImg} />
                          </span>
                        ) : (
                          ""
                        )}
                        <span
                          style={
                            moreAssay
                              ? { display: "inline-block" }
                              : { display: "none" }
                          }
                          className={style["close"]}
                          onClick={() => closeMore("moreAssay")}
                        >
                          收起
                          <img src={hideImg} />
                        </span>
                      </div>
                    </li>
                    <li className={style["lastLi"]}>
                      <div className={style["title"]}>检查：</div>
                      <div className={style["content"]}>
                        {check.length === 0
                          ? "无"
                          : moreCheck
                          ? checks
                          : checkHide}
                        {checkNum2 > 21 ? (
                          <span
                            style={
                              moreCheck
                                ? { display: "none" }
                                : { display: "inline-block" }
                            }
                            className={style["show"]}
                            onClick={() => showMore("moreCheck")}
                          >
                            更多
                            <img src={showImg} />
                          </span>
                        ) : (
                          ""
                        )}
                        <span
                          style={
                            moreCheck
                              ? { display: "inline-block" }
                              : { display: "none" }
                          }
                          className={style["close"]}
                          onClick={() => closeMore("moreCheck")}
                        >
                          收起
                          <img src={hideImg} />
                        </span>
                      </div>
                    </li>
                  </ul>
                )}
              </div>
            </div>
            {show?this.getTableInfo():''}
            <div className={style["tips"]}>
              <h1>
                <img src={tipsImg} />
                提示信息
              </h1>
              <div className={style["content"]}>
                {tips && tips.introduceDetailList ? (
                  <div>
                    <div className={style["title"]}>
                      {tips.tagName}
                      <span
                        className={style["tips-details"]}
                        onClick={() => showTips(tips)}
                        style={{display:tmpFlg?'none':'inline-block'}}
                      >
                        详情
                      </span>
                    </div>
                    {tips.introduceDetailList &&
                      tips.introduceDetailList.map((item, index) => {
                        return (
                          item.position.indexOf("1") > -1 && (
                            <div>
                              <div
                                dangerouslySetInnerHTML={{
                                  __html: item.title
                                }}
                              />
                              <div
                                dangerouslySetInnerHTML={{
                                  __html: item.content
                                }}
                              />
                              {item.isReason === 1 && (
                                <div className={style["warn"]}>
                                  {tipsDiscalimer.data.data[0]&&tipsDiscalimer.data.data[0].description}
                                </div>
                              )}
                            </div>
                          )
                        );
                      })}
                  </div>
                ) : (
                  "无"
                )}
              </div>
            </div>
          </div>
        </div>
        {tipsDiscalimer.data && <div className={style['disTips']} dangerouslySetInnerHTML={{__html: tipsDiscalimer.data.data[1]&&tipsDiscalimer.data.data[1].description}}></div>}
        {showTipsDetails && <DetailsModal  
            showTipsDetails = {showTipsDetails}
            hideTips = {this.hideTips}
            tipsDetails = {tipsDetails}/>}
        {/*<ConfirmModal visible={showList} okText='确定' cancelText='' confirm={this.confirm} close={this.close}>*/}
        <ConfirmModal 
        visible={showList} 
        noFooter="true" 
        close={this.close}
        height={300}
        width={400}>
          <h2 className={style['toast-title']}>全部量表</h2>
          <ul className={style['toast-cont']}>
            {tableList&&tableList.map((v,i)=>{
              return <li>
              {/*<a href="#">{'【'+v.name+'】'}</a>*/}
              <span>{'【'+v.name+'】'}</span>
              </li>
            })}
          </ul>    
        </ConfirmModal>
        <ConfirmModal 
        visible={showTable} 
        noFooter="true" 
        close={this.closeTable}
        height={800}
        width={820}>
          <div className={style['tableBox']}>
            <h2 className={style['toast-title']}>密西根糖尿病神经筛查表（MDNS）</h2>
            <h1>密西根糖尿病神经筛查表（MDNS）</h1>
            <p>MDNS可与MNSI联合应用以确定是否存在周围神经病变，在一段时间内对患者进行评分可以评估疾病的进展情况。</p>
            <table className={style['table']}>
              <thead>
                <tr>
                  {mocks.data.title.map((v,i)=>{
                    return <td>{v.name}</td>
                  })}  
                </tr>
              </thead>
              <tbody>
                {mocks.data.details.map((v,i)=>{
                    return <tr>
                    <td>{v.name}</td>
                    <td>
                      {v.details.map((it,index)=>{
                        return <td style={{display:'block'}}>{it.detailName}</td>
                      })}
                    </td>
                    <td></td>
                    <td></td>
                    </tr>
                  })} 
              </tbody>
            </table>
            <div>
              <p>
                1. 计算方法：<br/>
              感觉损伤得分=左右两侧感觉检查项目的分数之和
              肌力得分=左右两侧肌力检查项目的分数之和
              反射得分=左右两侧反射检查项目的分数之和
              体格检查得分=感觉损伤得分+肌力得分+反射得分
              </p>
              <p>
                2. 临床体格检查部分：<br/>
              最低得分0  最高得分46， 分数越高，周围神经病越重
              </p>
            </div>
          </div>
          <div className={style["tableBtn"]}>
            <span>打印</span>
            <span className={style["confirmBtn"]}>确定</span>
          </div>
        </ConfirmModal>
        {showAssess?<ComplexModal onclose={this.showAssessFn} footer={footer}
                      title='管理和评估'>
          <AssessResult></AssessResult>
        </ComplexModal>:''}
      </div>
    );
  }
}

export default PushItems;
