/** 
 * Creator:     
 * CreatDate:   
 * descripts：  床位图新组件
*/
import React, { Component } from 'react';
import { Row, Col, message, Button, Card, Icon, Popover, Tooltip } from 'antd';
import { $http } from '../../../containers/config/https';
// import PatientProcess from '../Patient/PatientProcess';
// import ChildbirthRegister from '../Childbirth/ChildbirthRegister';
// import Memorandum from '../BedChart/Memorandum';
import PatientCourseInfo from '../Patient/PatientCourseInfo.jsx';
import DivideBed from './DivideBed'
import PatientInfoDetail from '../Patient/PatientInfoDetail.jsx'
import { $loadTemplate } from '../../lodop/Common/Print.js';
import { Util } from 'tools/index';
import './CSS/ObstetricalDepartment.less';

let user;

class ObstetricalDepartment extends Component {
  constructor(props) {
    super(props);
    user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.state = {
      ShowChild: false,
      locID: user.locID,
      bedIcon: [],
      quickBtn: 'ALL',
      searchValue: '',
      searchFlag: false,
      admID: '',
      patBasicInfo: [],
      thatID: '',
      clickID: '',
      birthVisible: false,
      chickedM: false,
      mouseInID: '',
      isenter: '0',
      isclick: '',
      buttonTitle: '打印床头卡',
      buttonTitle1: '打印腕带',
      visible: false,
    }
  }

  componentDidMount() {
    this.getPatients();
    this.props.onRef && this.props.onRef(this);
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return
    }
  }

  onConsumeRef = (ref) => {
    this.childConsume = ref;
  };

  MouseEnter(item) {
    let parentState = this.props.getData();
    if (((parentState.selectBedID !== '') && (parentState.selectBedID !== item.id)) || ((parentState.admID != '') && (item.patInfo.admInfo === undefined))) {
      this.props.updateData({
        mouseInID: item.id,
        buttondisplay: 'inline-block'
      })

    }
    if ((item.unavailReason !== '') && (parentState.admID === '')) {
      this.props.updateData({
        mouseInID: item.id,
        buttondisplay: 'inline-block',
      })
    }
  }

  MouseLeave(item) {
    this.props.updateData({
      mouseInID: '',
      buttondisplay: 'none',
    })
  }

  onCardClick(item) {
    let parentState = this.props.getData();
    if (item.unavailReason !== '') {
      return;
    }
    if ((item.patInfo.admInfo === undefined) || (this.props.briefInformation)) {
      return;
    }
    else {
      if (item.id === parentState.selectBedID) {
        setTimeout(() => {
          this.props.updateData({
            selectBedID: '',
            mouseInID: '',
            admID: '',
            patID: '',
            otherSelectID: '',
						preSeparationBedFlag: '',
          })
        }, 100)
      } else {
        setTimeout(() => {
          this.props.updateData({
						preSeparationBedFlag: item.patInfo?.selectType || '', // 预分床标志
            admID: item.patInfo.admInfo.admID,
            patID: item.patInfo.basicInfo.patID,
            selectBedID: item.id,
            patStatus: 'A',
            otherSelectID: '',
            mouseInID: '',
          })
        }, 100)
      }
    }
  }

  /**包床 */
  charterBed = (bedID, admID, flag, e) => {
    e.stopPropagation()
    if ((this.props.admID === '') && (admID === '')) {
      message.error('请先选择患者!');
      return
    }
    if (admID === '') { admID = this.props.admID }
    let data = {
      params: [{
        bedID: bedID,
        userID: user.userID,
        admID: admID,
        hospID: user.hospID,
        status: flag,
      }]
    }
    $http.post('urlDeault', this, {
      code: '04020006',
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          if (flag !== '4') { message.success('包床成功!'); }
          else { message.success('结束包床完成!'); }
          setTimeout(() => {
            this.props.updateData({
              admID: '',
              patID: '',
              selectBedID: '',
              otherSelectID: '',
              mouseInID: '',
              roomLoading: true,
            })
          }, 100)
          this.props.getPatients();
        } else {
          message.error('包床失败!:' + res.errorMessage);
          this.props.getPatients();
        }
      }
    })
  }

  /** 
      * 换床 
      * 或
      * 结束包床操作
     */
  allotBed = (bedID, admID, unavailReason, e) => {
    e.stopPropagation()
    if (unavailReason === '') {
      //换床
      let data = {
        params: [
          {
            patInfo:
            {
              bedID: this.props.selectBedID,
              userID: user.userID,
              admID: this.props.admID,
              hospID: user.hospID,
              transType: '4',
              transStatus: '1',
            },
            exchangePatInfo:
            {
              bedID: bedID,
              userID: user.userID,
              admID: admID,
              hospID: user.hospID,
              transType: '4',
              transStatus: '1',
            }
          }

        ]
      }
      $http.post('urlDeault', this, {
        code: '04020005',
        data: data,
        success: (res) => {
          if (+res.errorCode === 0) {
            message.success('换床成功！!');
            setTimeout(() => {
              this.props.updateData({
                admID: '',
                patID: '',
                selectBedID: '',
                otherSelectID: '',
                mouseInID: '',
                roomLoading: true,
              })
            }, 100)
            this.props.getPatients();
          } else {
            message.error('分床失败!:' + res.errorMessage);
            this.props.getPatients();
          }
        }
      })
    }
    else {
      this.charterBed(bedID, admID, '4', e);
    }
  }

  /** 分床
     * 医生，护士，暂时为空
     */
  divideBed = (bedID, e) => {
    e.stopPropagation();
    this.handleSeparateBeds(bedID, '');
    return;
  }

  // 分床 / 分床
  handleSeparateBeds = (bedID, type) => {
    if (this.props.admID === '') {
      message.warning('请先选中患者！');
      return;
    }
    this.refs.DivideBed.setState({
      visible: true,
      admID: this.props.admID,
      bedID: bedID || undefined,
      patStatus: this.props.patStatus,
      separateBedsType: type
    }, () => {
      this.refs.DivideBed.getDivideInfo();
    })
  }

  onBedTitleClick = (admID, e) => {
    e.stopPropagation();
    this.PatInfoDetail.showModal();
  }

  handlePrintBedCard = (admID, type, bedID, e) => {
    e.stopPropagation();
    let data = {};
    data = {
      params: [{
        admID: admID,
        bedID: bedID,
      }]
    }
    let code = (type === 'BedCard') ? '04140012' : '04140013'
    let templateCode = (type === 'BedCard') ? 'BedCard' : 'Wristband'
    $http.post('urlS', this, {
      code: code,
      data: data,
      success: function (res) {
        if (res.errorCode === '0') {
          //加载模板
          $loadTemplate(templateCode, res.result);
        }
      }
    })
  }

  //查询
  getPatients = () => {
    let data = {
      params: [{
        wardID: user.locID,
        regStatus: 'REG'
      }]
    }
    $http.post('urlDeault', this, {
      code: '04110015',
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          this.setState({
            patBasicInfo: res.result
          });
        } else {
          message.error('查询失败：' + res.errorMessage);
        }
      }
    })
  }

  //患者ID/床号/姓名(回车查询)
  onSearchClick = (e) => {
    this.setState({
      searchFlag: true,
    })
  }

  //查询输入框改变
  onSearchChange = (e) => {
    this.setState({
      searchFlag: false,
      searchValue: e.target.value,
    })
  }

  onQuickBtnClick = (e) => {
    let id = e.target.value;
    if (e.target.value === this.state.clickIconId) {
      id = '';
    }
    this.setState({
      clickIconId: id,
      quickBtn: id,
    })
  }

  //选中小孩数据信息
  onBabyClick = (babyID, babyPatID, e) => {
    e.stopPropagation();
    setTimeout(() => {
      this.props.updateData({
        selectBedID: '',
        mouseInID: '',
        admID: babyID,
        patID: babyPatID,
        otherSelectID: '',
      })
    }, 100)
  }

  //选中的数据消失
  showChildData = (showId, e) => {
    this.setState({
      ShowChild: true,
      fouceId: showId
    })
  }

  //患者姓名点击
  patNameClick = (patID, admID, e) => {
    e.stopPropagation();
    this.childConsume.showModal(admID, patID);
  }

  noneChildData = () => {
    this.setState({
      ShowChild: false,
      fouceId: ''
    })
  }

  //转出产房
  onChildbirth = (e) => {
    if (this.state.admID == '') {
      message.warn('请选择患者！');
      return;
    }
    this.setState({
      birthVisible: true,
    })
  }

  // 调用公共组件的连接事件
  onRef = (ref) => {
    this.child = ref
  }

  // 绑定子组件
  onRef = (ref) => {
    this.PatInfoDetail = ref
  }

  render() {
    const isenter = this.state.isenter
    const propsState = this.props.getData();
    let patInfo = this.props.BedInfo.patInfo;
    const childInfo = this.props.BedInfo.patInfo.childInfo
    let patSexDesc = ''
    if (patInfo.basicInfo !== undefined) {
      patSexDesc = patInfo.basicInfo.patSexDesc;
    }
    let bedInfo = this.props.BedInfo;
    let background = '#F7F7F7';
    if (patInfo.basicInfo) {
      switch (patInfo.basicInfo.patSexCode) {
        case '1': background = '#40A9FF'; break
        case '2': background = '#F759AB'; break
        case '9': background = '#A0D911'; break
        case '0': background = '#A0D911'; break
      }
    }
    if (this.props.BedInfo.unavailReason !== '') background = '#722ED1';
    return (
      <div className="bed item-bed icon">
        {
          (patInfo.admInfo !== undefined) ?
            (
              <Card
                className={
                  "bed ant-card-bordered-sex " +
                  (propsState.selectBedID === this.props.BedInfo.id ? "ant-card-bordered-" + patInfo.basicInfo.patSexCode + "c" : '')
                }
                size="small"
                style={{ height: '100%' }}
                // headStyle={{ background: 'rgb(247, 89, 171)' }}
                onMouseOver={this.showChildData}
                // onMouseLeave={this.noneChildData}
                headStyle={{
                  color: '#ffffff',
                  background: background,
                }}
                title={
                  <Popover
                    overlayClassName="antpopoverinner" placement="bottomLeft" content={
                      (
                        <div>
                          <p>患者ID:{patInfo.basicInfo.patNo}</p>
                          <p>性别:{patInfo.basicInfo.patSexDesc}</p>
                          <p>年龄:{patInfo.admInfo.admAge}</p>
                          <p>责医:{patInfo.admInfo.admDocDesc}</p>
                          <p>责护:{patInfo.admInfo.admNurDesc} </p>
                          <p>就诊日期:{patInfo.admInfo.admDate}</p>
                          <p>就诊时间:{patInfo.admInfo.admTime}</p>
                          <p>诊断:{patInfo.admInfo.admDiag}</p>
                        </div>
                      )
                    } >
                    <div

                      onClick={this.onBedTitleClick.bind(this, patInfo.admInfo.admID)}>
                      <div className="bedcode">
                        {this.props.BedInfo.displayRoom === "N" ? this.props.BedInfo.bedDescripts : (this.props.BedInfo.roomDescripts + "-" + this.props.BedInfo.bedDescripts)}
                      </div>
                      <div
                        className="patButton"
                      ><Tooltip title='打印床头卡'><Icon type='printer' onClick={this.handlePrintBedCard.bind(this, patInfo.admInfo.admID, 'BedCard', this.props.BedInfo.id)} />
                        </Tooltip>
                        <Tooltip title='打印腕带'>
                          <Icon type='tag' onClick={this.handlePrintBedCard.bind(this, patInfo.admInfo.admID, 'Wristband', this.props.BedInfo.id)} />
                        </Tooltip>
                      </div>
                      <div
                        className="patName"
                        style={{ paddingRight: "3px" }}
                        onClick={this.patNameClick.bind(this, patInfo.basicInfo.patID, patInfo.admInfo.admID)}
                      >
                        {patInfo.basicInfo.patName}
                      </div>
                      <div className="nurseLevel">
                        {
                          this.props.BedInfo.unavailReason !== '' ?
                            this.props.BedInfo.unavailDay :
                            patInfo.admInfo.admNurLevelID === '' ? '' :
                              <div
                                title={patInfo.admInfo.admNurLevelDesc}
                                className="bedicon"
                                style={{
                                  width: patInfo.admInfo.nurLevelIcon.size + "px",
                                  height: patInfo.admInfo.nurLevelIcon.size + "px",
                                  backgroundPosition: (-((patInfo.admInfo.nurLevelIcon.position % 10 - 1) * 18)) + "px" + " " + (-(parseInt(+patInfo.admInfo.nurLevelIcon.position / 10) * 18)) + "px"
                                }}
                              > </div>
                        }
                      </div>
                    </div>
                  </Popover>
                }
                actions={
                  bedInfo.unavailReason === '' ?
                    patInfo.admInfo.admIcon.length === 0 ? [<span></span>] :
                      patInfo.admInfo.admIcon.map(
                        (item) => {
                          return (
                            <div
                              title={item.title}
                              className="bedicon"
                              style={{
                                width: "18px",
                                height: "18px",
                                backgroundPosition: (-((item.position % 10 - 1) * 18)) + "px" + " " + (-(parseInt(+item.position / 10) * 18)) + "px"
                              }}
                            > </div>
                          );
                        }
                      ) :

                    [
                      <div
                        title={bedInfo.unavailTitle}
                        className="bedicon"
                        style={{
                          width: "18px",
                          height: "18px",
                          backgroundPosition: (-((bedInfo.unavailPosition % 10 - 1) * 18)) + "px" + " " + (-(parseInt(+bedInfo.unavailPosition / 10) * 18)) + "px"
                        }}
                      >
                      </div>

                    ]

                }
                bodyStyle={
                  (!this.props.briefInformation) ?
                    (this.props.BedInfo.unavailReason === '') ? {

                    } : {
                      background: "#E9E9E9",
                    } : {
                      height: '0px',
                      padding: '0px',
                    }
                }
                onClick={this.onCardClick.bind(this, this.props.BedInfo)}
                onMouseEnter={this.MouseEnter.bind(this, this.props.BedInfo)}     //移入
                onMouseLeave={this.MouseLeave.bind(this)}     //移出
              >
                {
                  (!this.props.briefInformation) ? (
                    <Row className=''>
                      <div style={{ display: 'flex' }}>
                        <div className='card-left-container' style={{ borderRight: '1px solid #eae3e3' }}>
                          <Row>
                            <Col span={24}
                              style={{
                                maxHeight: '50px',
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                              }}
                            >登记号： {patInfo.basicInfo.patNo}</Col>
                            <Col span={24} style={{
                              maxHeight: '50px',
                              overflow: 'hidden',
                              whiteSpace: 'nowrap',
                              textOverflow: 'ellipsis',
                            }}>责医/责护:{patInfo.admInfo.admDocDesc}/{patInfo.admInfo.admNurDesc}</Col>
                            <Col span={24}
                              style={{
                                maxHeight: '50px',
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                              }} >就诊日期:{patInfo.admInfo.admDate + " " + patInfo.admInfo.admTime} </Col>
                            <Col span={24}
                              id="lineEllipsis"
                              style={{
                                maxHeight: '50px',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                              }}>诊断:{patInfo.admInfo.admDiag}</Col>
                          </Row>
                          {/* <div className="card-left-info"
                          >
                            <p className='info-line'>
                              <span className='info-key' style={{ marginTop: '5px' }}>登记号：</span>
                              <span className='info-value' style={{ marginTop: '5px' }}>{patInfo.basicInfo.patNo}</span>
                            </p>
                            <p className='info-line'>
                              <span className='info-key' style={{ marginTop: '-7px' }}>就诊日期：</span>
                              <span className='info-value' style={{ marginTop: '-7px' }}>{patInfo.admInfo.admDate + " " + patInfo.admInfo.admTime}</span>
                            </p>
                            <p className='info-line'>
                              <span className='info-key' style={{ marginTop: '-7px' }}>责医/责护：</span>
                              <span className='info-value' style={{ marginTop: '-7px' }}>{patInfo.admInfo.admDocDesc}/{patInfo.admInfo.admNurDesc}</span>
                            </p>
                            <p className='info-line'>
                              <span className='info-key' style={{ marginTop: '-7px' }}>诊断：</span>
                              <span id='description' style={{ marginTop: '-7px' }} title={patInfo.admInfo.admDiag} className='info-value'>{patInfo.admInfo.admDiag}</span>
                            </p>
                          </div> */}
                        </div>
                        <div className="card-right" style={{ width: '40%', height: '130px', overflow: 'auto', position: 'relative', textAlign: 'center' }}>
                          {
                            !Util.isEmpty(childInfo) && childInfo.length > 0 ?
                              childInfo.map((v, k) => {
                                return (
                                  <div className='card-right-container'
                                    style={{ border: propsState.admID == v.babyAdmID ? '1px solid #cc00ee' : '0px' }}
                                    key={k} onClick={this.onBabyClick.bind(this, v.babyAdmID, v.childPatID)}
                                  >
                                    <div className='card-right-item'>
                                      <span className='right-item-index'>{k + 1}</span>
                                      <div className='right-item-detail'>
                                        <p>{v.childPatNo}</p>
                                        <p>{v.childPatName}｜{v.childbirthSexDesc}</p>
                                        <p>{v.childbirthWeight}</p>
                                      </div>
                                    </div>
                                  </div>
                                )
                              }) :

                              <Col span={12} style={{
                                width: '100%', height: '20px', position: 'absolute', top: '50%', marginTop: '-10px',
                                fontSize: '16px', fontWeight: 'bold'
                              }}>
                                暂无数据
                              </Col>
                          }
                        </div>
                        <div className="buttonPosition-icon">
                          <Button
                            className="buttonStyle"
                            type="primary"
                            style={{
                              zIndex: "1000",
                              display: (propsState.buttondisplay === "inline-block") && (this.props.BedInfo.id === propsState.mouseInID) ? "inline-block" : "none"
                            }}
                            onClick={this.allotBed.bind(this, this.props.BedInfo.id, this.props.BedInfo.patInfo.admInfo.admID, this.props.BedInfo.unavailReason)}
                          >
                            {
                              this.props.BedInfo.unavailReason === '' ? "换床" : "结束包床"
                            }

                          </Button>
                        </div>
                      </div>
                    </Row>
                  ) : ''
                }
              </Card>
            )
            : (
              <Card
                title={
                  <div className="bedcode">
                    {this.props.BedInfo.roomDescripts + "-" + this.props.BedInfo.bedcode}
                  </div>
                }
                hoverable
                // style={{ height: '200px' }}
                actions={[<span></span>]}
                bodyStyle={
                  (!this.props.briefInformation) ? {
                  } : {
                    height: '0px',
                    padding: '0px',
                  }
                }
                onClick={this.onCardClick.bind(this, this.props.BedInfo)}
                onMouseEnter={this.MouseEnter.bind(this, this.props.BedInfo)}     //移入
                onMouseLeave={this.MouseLeave.bind(this)}     //移出
              >
                {

                  <div>
                    <div style={{ height: '100%', width: '100%' }}>
                      <div
                        title={bedInfo.iconTitle}
                        className="bedicon"
                        style={{
                          margin: '27px 0 0 150px',
                          width: bedInfo.iconSize + "px",
                          height: bedInfo.iconSize + "px",
                          backgroundPosition: (-((bedInfo.iconPosition % 10 - 1) * 18)) + "px" + " " + (-(parseInt(+bedInfo.iconPosition / 10) * 18)) + "px"
                        }}
                      >
                      </div>
                      <span className="emptyMsg-bed">暂无入住患者</span>
                    </div>
                    <div className="buttonPosition-icon">
                      <Button
                        className="buttonStyle"
                        type="primary"
                        onClick={this.divideBed.bind(this, this.props.BedInfo.id)}
                        style={{
                          display: (propsState.buttondisplay === "inline-block") && (this.props.BedInfo.id === propsState.mouseInID) &&
                            ((propsState.patStatus === "A") || (propsState.patStatus === "I") || (propsState.patStatus === "O")) ? "inline-block" : "none"
                        }}
                      >
                        分床
                      </Button>
                      <br />
                      {
                        this.props.selectBedID !== '' ? (
                          <Button
                            className="buttonStyle"
                            type="primary"
                            onClick={this.charterBed.bind(this, this.props.BedInfo.id, '', "2")}
                            style={{ display: (propsState.buttondisplay === "inline-block") && (this.props.BedInfo.id === propsState.mouseInID) ? "inline-block" : "none" }} >
                            包床
                          </Button>
                        ) : ''
                      }
                    </div>
                  </div>


                }
                <DivideBed
                  ref="DivideBed"
                  briefInformation={this.props.briefInformation}
                  selectBedID={this.props.selectBedID}
                  admID={this.props.admID}
                  updateData={this.props.updateData}
                  getData={this.props.getData}
                  getPatients={this.props.getPatients}
                  locID={this.props.locID}
                  child={this.props.child}
                ></DivideBed>

              </Card>
            )
        }
        <PatientCourseInfo
          activeKey="PatientCourse"
          onRef={this.onConsumeRef}
        />
        <PatientInfoDetail
          onRef={this.onRef}
          getPatients={this.props.getPatients}
          admID={patInfo.admInfo != undefined ? patInfo.admInfo.admID : ''}
        />
      </div>
    )
  }
};

export default ObstetricalDepartment;





