/*
 * Create:      柿子
 * CreateDate:  2023/10/31
 * Describe：   床位图图标设置
 * */
import React, { Component } from 'react';
import { Icon, Button, Popover, Steps } from 'antd';
import QRCode from 'qrcode.react';
import emptyBedImg from '../images/empty-bed.png'
import moment from 'moment';

const { Step } = Steps;

class BedItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contextMenuPos: null,
      menuWidth: 180, // 菜单宽度
      menuHeight: 12 + 13 * 36,
      rightMenuList: [{
        code: 'BedCard',
        title: '打印床头卡',
      }, {
        code: 'Wristband',
        title: '打印腕带',
      }, {
        code: 'PatientInfoDetail',
        title: '修改入院信息',
      }, {
        code: 'ModifyPatInfo',
        title: '修改基本信息',
      }, {
        title: '生命体征',
      }, {
        title: '医嘱单',
      }, {
        code: 'AllotBed',
        title: '换床',
      }, {
        code: 'LookUpEMR',
        title: '住院病历',
      }, {
        code: 'Discharge',
        title: '出院',
      }, {
        code: 'TransLoc',
        title: '转科',
      }, {
        code: 'MoveToWaitZone',
        title: '移入等候区',
      }, {
        code: 'MoveToDisWaitZone',
        title: '移入出院等候区',
      }, {
        code: 'MoveToWithdrawalArea',
        title: '移入退院区',
      }, {
        code: 'PatientCourse',
        title: '患者历程',
      }],
      mouseOverFlag: 'N',
      diagMouseFlag: 'N'
    };
  };

  handleRenderIcon = (iconData = [], ellipsisNum, borderFlag) => {
    let renderIcon = iconData && Array.isArray(iconData) ? JSON.parse(JSON.stringify(iconData)) : [];
    let ellipsisFlag = 'N';  // 溢出点点点展示标志
    if (ellipsisNum !== 'N' && iconData && Array.isArray(iconData) && iconData.length > ellipsisNum) {
      renderIcon = renderIcon.slice(0, ellipsisNum);
      ellipsisFlag = 'Y';
    }
    return renderIcon && renderIcon.map((item, index) => {
      return (
        !(ellipsisFlag === 'Y' && ellipsisNum && index === ellipsisNum - 1) ? ( // 如果隐藏隐藏，最后一个则展示溢出图标
          <Popover key={index} content={item?.iconDesc || item?.words || '无'}>
            <span
              key={index}
              className={['span-color-border', 'span-color-border-hover', 'bed-item-keywords-icon'].join(' ')}
              style={{
                color: item?.fillMode === 'B' ? (item?.color || '') : '#fff',
                cursor: 'pointer',
                border: '1px solid ' + (item?.color || '#e8e8e8'),
                background: item?.fillMode === 'P' ? (item?.color || '#fff') : 'none'
              }}
            >
              {item?.words || '无'}
            </span>
          </Popover>
        ) : <Icon type="ellipsis" />
      )
    })
  };

  // 右键菜单
  handleRightClick = (e) => {
    React.$stopPropagation(e);
    React.$preventDefault(e);
    const { menuWidth, menuHeight } = this.state;
    let clickX = e.clientX;
    let clickY = e.clientY;
    // 检查是否超过屏幕宽度
    if (clickX + menuWidth > window.innerWidth) {
      clickX -= menuWidth;
    }
    if (clickX < 0) {
      clickX = 0;
    }
    // 检查是否超过屏幕高度
    if (clickY + menuHeight > window.innerHeight) {
      clickY -= menuHeight;
    }
    if (clickY < 48) { // 头菜单高度不能超过菜单栏【侧菜单忽略】
      clickY = 48;
    }
    this.setState({ contextMenuPos: { left: clickX, top: clickY } }, () => {
      this.props.onRightClick && this.props.onRightClick(); // 右键菜单
    });
  };

  handleClick = () => {
    this.props.onClick && this.props.onClick(); // 单击床位图
  };

  // 床位图右键菜单点击事件
  handleMenuClick = (e, code) => {
    React.$stopPropagation(e);
    const { bedInfo, rowData } = this.props;
    this.props?.handleBedRightClick(code, bedInfo, rowData); // 病区信息
  };

  // 鼠标移入 / 移出
  handleMouseOver = (e, flag) => {
    this.setState({ mouseOverFlag: flag });
  };

  // 诊断移入事件
  handleDiagMouse = (e, flag) => {
    if (e.target !== e.currentTarget) return;
    this.setState({ diagMouseFlag: flag });
  }

  render() {
    const { style, bedModeID, bedInfo, rightMenuVisible, rowData } = this.props;
    const { contextMenuPos, rightMenuList, mouseOverFlag, diagMouseFlag } = this.state;
    const iconArr = bedInfo?.icon || [];
    const headerIcon = iconArr && Array.isArray(iconArr) ? iconArr.filter(item => item?.position === 'TR') : []; // 床位图头部icon
    const footerIcon = iconArr && Array.isArray(iconArr) ? iconArr.filter(item => item?.position === 'B') : []; // 床位图尾部icon
    const patName = bedInfo?.patName || '';
    const roomDesc = bedInfo?.roomDescripts || bedInfo?.bedDescripts || ''; // 床位所属房间
    const bedCode = bedInfo?.bedCode || '';
    return (
      <div
        style={{ ...style, boxShadow: (rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id) || mouseOverFlag === 'Y') ? ('0px 0px 4px 0px ' + (bedInfo?.headerBg || '#666')) : '' }}
        className={['bed-item'].join(' ')}
        onClick={this.handleClick}
        onContextMenu={this.handleRightClick}
        onMouseEnter={(e) => this.handleMouseOver(e, 'Y')} // 移入
        onMouseLeave={(e) => this.handleMouseOver(e, 'N')} // 移出
      >
        <div
          style={{
            background: (bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2' ? '#fff' : (bedInfo?.headerBg || '#F7F7F7'),
            paddingRight: headerIcon && (headerIcon.length > 3 || (headerIcon && headerIcon.length === 3 && patName?.length > 4)) ? '1px' : '',
            borderLeft: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '' : (
              '1px solid ' + ((rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? (bedInfo?.headerBg || '#666') : '#D3D3D3')),
            borderRight: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '' : (
              '1px solid ' + ((rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? (bedInfo?.headerBg || '#666') : '#D3D3D3')),
            borderTop: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '' : (
              '1px solid ' + ((rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? (bedInfo?.headerBg || '#666') : '#D3D3D3')),
            borderBottom: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '' : '1px solid #D3D3D3',
            borderRadius: (rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? '0' : '4px 4px 0 0'
          }}
          className="bed-item-header flex-between-center"
        >
          {/* 床号 */}
          <div
            style={{
              fontWeight: (roomDesc?.length || 0) + (bedCode?.length || 0) > 6 ? 'normal' : 'bold',
              color: bedInfo?.statusCode !== '1' ? '#333' : '#fff',
            }}
            className="bed-item-header-room two-lines-ellipsis"
          >
            <strong>{(roomDesc ? (roomDesc + '-') : '') + bedCode}</strong>
          </div>
          {/* 姓名 */}
          <div
            style={{
              width: `calc(100% - ${patName?.length > 4 ? (headerIcon && headerIcon.length > 3 ? '122px' : '140px') : '156px'})`,
              fontWeight: patName?.length > 4 ? 'normal' : 'bold',
              color: bedInfo?.statusCode !== '1' ? '#333' : '#fff',
            }}
            className="bed-item-header-name two-lines-ellipsis"
          >
            <strong>{patName}</strong>
          </div>
          <div
            style={{
              width: patName?.length > 4 ? (headerIcon && headerIcon.length > 3 ? '38px' : '56px') : '74px',
              paddingLeft: headerIcon && (headerIcon.length > 3 || (headerIcon && headerIcon.length === 3 && patName?.length > 4)) ? '2px' : '',
              justifyContent: headerIcon && (headerIcon.length > 3 || (headerIcon && headerIcon.length === 3 && patName?.length > 4)) ? '' : 'flex-end',
            }}
            className={['bed-item-header-icon', 'flex-wrap-align-items', headerIcon && (headerIcon.length > 3 || (headerIcon && headerIcon.length === 3 && patName?.length > 4)) ? 'bed-item-mini-icon' : ''].join(' ')}
          >
            {/* 床位顶部图标 */}
            {this.handleRenderIcon(headerIcon, patName?.length > 4 ? 4 : (patName?.length < 4 && headerIcon && headerIcon.length > 8 ? 8 : 'N'))}
          </div>
        </div>
        <div
          style={{
            display: bedModeID === '3' ? 'none' : 'block',
            height: bedModeID === '3' ? '0' : '136px',
            background: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '#F7F7F7' : '#fff',
            borderLeft: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '' : (
              '1px solid ' + ((rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? (bedInfo?.headerBg || '#666') : '#D3D3D3')),
            borderRight: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '' : (
              '1px solid ' + ((rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? (bedInfo?.headerBg || '#666') : '#D3D3D3')),
          }}
          className="bed-item-content"
        >
          {bedModeID === '1' ? ( // 详情
            <>
              {bedInfo && 'admID' in bedInfo && bedInfo.admID ? ( // 已分床
                <div className="bed-item-content-item bed-item-body">
                  <div>
                    <div className="bed-item-content-icon">
                      <i style={{ color: bedInfo?.patSexDesc === '男' ? '#0095FF' : (bedInfo?.patSexDesc === '女' ? '#FF4800' : '') }} className="iconfont icon-personnel"></i>
                    </div>
                    <div className="bed-item-content-title ellipsis">
                      <span>{bedInfo?.patNo || ''}</span>
                      <span style={{ margin: '0 8px' }}>{bedInfo?.patSexDesc || ''}</span>
                      <span>{bedInfo?.patAge || ''}</span>
                    </div>
                  </div>
                  {/* 费别 */}
                  <div>
                    <div className="bed-item-content-icon">
                      <i className="iconfont icon-card"></i>
                    </div>
                    <div className="bed-item-content-title ellipsis">
                      {bedInfo?.admReasonDesc || '费别：不详'}
                    </div>
                  </div>
                  {/* 住院信息 */}
                  <div>
                    <div className="bed-item-content-icon">
                      <i className="iconfont icon-time"></i>
                    </div>
                    <div className="bed-item-content-title">
                      <span className="common-number">{bedInfo?.patMedicalNo || ''}</span>
                      <span style={{ margin: '0 8px' }}>{'12-12 12:00入院'}</span>
                      <span className="common-number">{bedInfo?.admInDays || ''}</span>
                      天
                    </div>
                  </div>
                  {/* 诊断 */}
                  <div>
                    <div className="bed-item-content-icon">
                      <i style={{ fontSize: '16px' }} className="iconfont icon-diag"></i>
                    </div>
                    <div
                      className={[diagMouseFlag === 'Y' ? 'bed-item-content-diag two-lines-ellipsis' : '', 'bed-item-content-title ellipsis'].join(' ')}
                      onMouseOver={(e) => this.handleDiagMouse(e, 'Y')} // 移入
                      onMouseOut={(e) => this.handleDiagMouse(e, 'N')} // 移出
                    >
                      {bedInfo?.admDiag || '诊断：不详'}
                    </div>
                  </div>
                  {/* 责医 */}
                  <div>
                    <div className="bed-item-content-icon">
                      <i className="iconfont icon-doctor"></i>
                    </div>
                    <div className="bed-item-content-title ellipsis">
                      {bedInfo?.admDocDesc || '责任医师：不详'}
                    </div>
                  </div>
                  {/* 责护 */}
                  <div>
                    <div className="bed-item-content-icon">
                      <i className="iconfont icon-nurse"></i>
                    </div>
                    <div className="bed-item-content-title ellipsis">
                      {bedInfo?.admNurDesc || '责任护士：不详'}
                    </div>
                  </div>
                </div>
              ) : (bedInfo?.statusCode === '2' ? ( // 包床
                <div className="bed-item-content-item bic-wrapped-bed flex-column-center">
                  <div className="bic-wrapped-bed-day flex-center">
                    包床
                    <span className="bic-wrapped-bed-num common-number">
                      {bedInfo?.unavailDay || ''}
                    </span>
                  </div>
                  <div className="bic-wrapped-bed-time">
                    开始包床时间: {bedInfo?.unavailDateTime || moment(moment().subtract(parseInt(bedInfo?.unavailDay || 0), 'days')).format('MM-DD HH:mm')}
                  </div>
                </div>
              ) : (bedInfo?.statusCode === '02' ? ( // 占床
                <div className="bed-item-content-item bic-bed-occupancy flex-column-center">
                  <i className="iconfont icon-bed-occupancy" />
                  床位已被占用
                </div>
              ) : ( // 空床
                <div className="bed-item-content-item bic-empty-bed flex-column-center">
                  {/* <i className="iconfont icon-empty-bed" /> */}
                  <img src={emptyBedImg} alt="" />
                  空床
                </div>
              )))}
            </>
          ) : (bedModeID === '2' && bedInfo && 'patNo' in bedInfo && bedInfo.patNo ? ( // 二维码
            <div className="bed-item-content-item flex-center" style={{ position: 'absolute', top: 0, left: 0, background: '#fff' }}>
              <QRCode
                renderAs="svg" // 渲染方式默认canvas
                level="Q" // L(<7%),M(<15%),Q(<25%),H(<30%)
                value={bedInfo?.patNo || ''}
                size={116} // 二维码的大小
                fgColor="#000000" // 二维码的颜色
              />
            </div>
          ) : '')}
          {/* 分床 | 包床 | 占床等操作按钮 */}
          {mouseOverFlag === 'Y' && (
            <div style={{ display: 'flex' }} className="bic-float-btn flex-column-center">
              <Button
                type="primary"
                style={{ display: (rowData && 'admID' in rowData && rowData.admID) && !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? 'block' : 'none', marginTop: '10px' }}
                onClick={(e) => this.handleMenuClick(e, 'SeparateBeds')}
              >
                分床
              </Button>
              <Button
                type="primary"
                style={{ display: (rowData && 'admID' in rowData && rowData.admID) && !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? 'block' : 'none', marginTop: '10px' }}
                onClick={(e) => this.handleMenuClick(e, 'WrappedBed')}
              >
                包床
              </Button>
              <Button
                type="primary"
                style={{ display: (rowData?.id || rowData?.bedID) && (rowData && 'admID' in rowData && rowData.admID) && (bedInfo && 'admID' in bedInfo && bedInfo.admID) && (rowData?.admID !== bedInfo?.admID) ? 'block' : 'none', marginTop: '10px' }}
                onClick={(e) => this.handleMenuClick(e, 'AllotBed')}
              >
                换床
              </Button>
              <Button
                type="primary"
                style={{
                  display: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? 'block' : 'none',
                  marginTop: '10px'
                }}
                onClick={(e) => this.handleMenuClick(e, 'BedOccupancy')}
              >
                占床
              </Button>
              <Button
                type="danger"
                style={{ display: bedInfo?.statusCode === '04' ? 'block' : 'none', marginTop: '10px' }}
                onClick={(e) => this.handleMenuClick(e, 'CancelBedOccupancy')}
              >
                取消占床
              </Button>
              <Button
                type="danger"
                style={{ display: bedInfo?.statusCode === '2' ? 'block' : 'none', marginTop: '10px' }}
                onClick={(e) => this.handleMenuClick(e, 'CancelWrappedBed')}
              >
                结束包床
              </Button>
            </div>
          )}
          {/* 床位费 */}
          {bedInfo && 'bedFee' in bedInfo && Array.isArray(bedInfo.bedFee) && bedInfo.bedFee.length > 0 && (
            <div className="bic-fee">
              <Popover
                placement="right"
                content={(
                  <Steps className="bic-steps" progressDot current={bedInfo?.bedFee?.length || 0} direction="vertical">
                    {bedInfo.bedFee.map((feeItem, feeIndex) => {
                      return (
                        <Step title={feeItem?.title || ''} description={feeItem?.descripts || ((feeItem?.type || '') + ':' + (feeItem?.price || '0') + '元') || ''} key={feeIndex} />
                      )
                    })}
                  </Steps>
                )}>
                <span>{(bedInfo?.bedTotalPrice || '0') + '元'}</span>
              </Popover>
            </div>
          )}
        </div>
        <div
          style={{
            borderColor: !((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '#F7F7F7' : ((rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? (bedInfo?.headerBg || '#666') : '#D3D3D3'),
            borderRadius: (rowData && 'id' in rowData && String(rowData?.id) === String(bedInfo?.id)) || mouseOverFlag === 'Y' ? '0' : '0 0 4px 4px'
          }}
          className="bed-item-footer flex-wrap-align-items"
        >
          {!((bedInfo && 'admID' in bedInfo && bedInfo.admID) || bedInfo?.statusCode === '2') ? '' : (footerIcon && Array.isArray(footerIcon) && footerIcon.length > 0 ? (
            this.handleRenderIcon(footerIcon, 12, 'Y')
          ) : (
            <span style={{ color: '#999', fontSize: '12px' }}>暂无信息</span>
          ))}
        </div>

        {/* 右键菜单 */}
        <div className="common-right-menu-wrap" style={{ visibility: rightMenuVisible ? 'visible' : 'hidden', ...contextMenuPos }}>
          {rightMenuList && rightMenuList.map((item, index) => {
            return (
              <div key={index} className="common-right-menu-option" onClick={(e) => this.handleMenuClick(e, item?.code || '')}>
                {item?.title || '暂无描述'}
              </div>
            )
          })}
        </div>
      </div >
    )
  }
};

export default BedItem;