/** 
 * Creator:     JYW
 * CreatDate:   2019-03-20
 * descripts：  床位组件
*/
import React, { Component } from 'react';
import { Card, Icon, message, Button, Row, Col, Popover, Tooltip } from 'antd';
import { $http } from '../../../containers/config/https';
import { Util } from 'tools';
import QRCode from 'qrcode.react';
import DivideBed from './DivideBed'
import PatientInfoDetail from '../Patient/PatientInfoDetail.jsx'
import PatientCourseInfo from '../Patient/PatientCourseInfo.jsx';
import './CSS/bedchart.less';
import { $loadTemplate } from '../../lodop/Common/Print.js';

let user;
class Bed extends Component {
	constructor(props) {
		super(props);
		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		this.state = {
			isenter: '0',
			isclick: '',
			mouseInID: '',
			buttonTitle: '打印床头卡',
			buttonTitle1: '打印腕带',
			visible: false,
			groupDesc: user.groupDesc,
			mouseInAdmID: '',
			mouseInPatID: '',
		}
	}

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

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

	MouseEnter(item) {
		let parentState = this.props.getData();
		if (item.patInfo.admInfo) {
			this.props.updateData({
				mouseInAdmID: item.patInfo.admInfo.admID,
				mouseInPatID: item.patInfo.basicInfo.patID,
			})
		}
		if ((((parentState.selectBedID !== '') && (parentState.selectBedID !== item.id)) || ((parentState.admID != '') && (item.patInfo.admInfo === undefined))) && (this.state.groupDesc.indexOf('护士') > -1)) {
			this.props.updateData({
				mouseInID: item.id,
				buttondisplay: 'inline-block'
			})

		} else if (((item.unavailReason !== '') && (parentState.admID === '')) && (this.state.groupDesc.indexOf('护士') > -1)) {
			this.props.updateData({
				mouseInID: item.id,
				buttondisplay: 'inline-block',
			})
		} else { // 没选择床位时鼠标移入展示
			this.props.updateData({
				mouseInID: item.id,
				buttondisplay: '',
			})
		}
	}

	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)
			}
		}
	}

	/** 
	 * 换床 
	 * 或
	 * 结束包床操作
	*/
	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);
		}
	}

	/**包床 */
	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();
				}
			}
		})
	}

	/** 分床
	 * 医生，护士，暂时为空
	 */
	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();
	}
	//患者姓名点击
	patNameClick = (patID, admID, e) => {
		e.stopPropagation();
		this.childConsume.showModal(admID, patID);
	}

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

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

	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);
				}
			}
		})
	}

	/**
	 * @ByShizi: 占床/取消占床
	 * Create 2023-04-23
	 * */
	handleBedOccupancy = async (bedInfo) => {
		try {
			let data = {
				params: [{
					bedStatuCode: bedInfo?.statusCode === '04' ? '02' : '04',
					bedID: bedInfo?.id || '',
				}]
			}
			let res = await React.$asyncPost(this, '04020026', data);
			message.success(res.errorMessage || '操作成功');
			setTimeout(() => {
				this.props.updateData({
					admID: '',
					patID: '',
					selectBedID: '',
					otherSelectID: '',
					mouseInID: '',
					roomLoading: true,
				})
			}, 100)
			this.props.getPatients();
		} catch (error) {
			console.log(error)
		}
	}

	render() {
		const { QRCodeVisible } = this.props;
		const propsState = this.props.getData();
		let patInfo = this.props.BedInfo.patInfo;
		let patSexDesc = ''
		if (patInfo.basicInfo !== undefined) {
			patSexDesc = patInfo.basicInfo.patSexDesc;
			// if (patSexDesc === '男') { patSexDesc = 'man' }
			// else if (patSexDesc === '女') { patSexDesc = 'woman' }
			// else { patSexDesc = 'other' }
		}
		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" : "")
								}
								style={{ height: '100%' }}
								headStyle={{
									color: '#ffffff',
									background: background,
								}}
								title={
									<Popover
										overlayClassName="antpopoverinner" placement="bottomLeft" content={
											(
												<div>
													<p>人员标识:{patInfo.basicInfo.patNo}</p>
													<p>姓名:{patInfo.basicInfo.patName}</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 + ' ' + patInfo.admInfo.admTime}</p>
													<p>诊断:{patInfo.admInfo.admDiag}</p>
													<p>总费用:{patInfo.admInfo.totalAmtIP ? patInfo.admInfo.totalAmtIP : '0.00'}</p>
													<p>预交金:{patInfo.admInfo.accDepositIP ? patInfo.admInfo.accDepositIP : '0.00'}</p>
													<p>余额:{patInfo.admInfo.purposeBlanceIP ? patInfo.admInfo.purposeBlanceIP : '0.00'} </p>
												</div>
											)
										} >
										<div className="patCardTitle"
											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 style={{ paddingLeft: '3px' }} type='tags' onClick={this.handlePrintBedCard.bind(this, patInfo.admInfo.admID, 'Wristband', this.props.BedInfo.id)} />
												</Tooltip>
											</div>
											<div
												className="patName ellipsis"
												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 (
														<Tooltip title={item.title}>
															{item && 'type' in item && item.type ? (
																<span
																	className="custom-bed-icon"
																	style={{
																		background: item.type === 'NurseCare1' ? '#f5222d' : (item.type === 'NurseCare2' ? '#40a9ff' : (item.type === 'NurseCare3' ? '#52c41a' : '')),
																		// color: item.type === 'NurseCare3' ? '#000' : ''
																	}}
																>
																	{item.type === 'NurseCare1' ? '一' : (item.type === 'NurseCare2' ? '二' : (item.type === 'NurseCare3' ? '三' : ''))}
																</span>
															) : (
																<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>
															)}
														</Tooltip>
													);
												}
											) :
										[
											<Tooltip title={bedInfo.unavailTitle}>
												{bedInfo && 'type' in bedInfo && bedInfo.type ? (
													<span
														className="custom-bed-icon"
														style={{ background: bedInfo.type === 'NurseCare1' ? 'red' : (bedInfo.type === 'NurseCare2' ? 'blue' : (bedInfo.type === 'NurseCare3' ? '#fff' : '')) }}
													>
														{bedInfo.type === 'NurseCare1' ? '一' : (bedInfo.type === 'NurseCare2' ? '二' : (bedInfo.type === 'NurseCare3' ? '三' : ''))}
													</span>
												) : (
													<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>
												)}
											</Tooltip>
										]
								}
								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="">
											{
												<Row style={{ position: 'relative' }}>
													<Col span={12}>{patInfo.basicInfo.patNo}</Col><Col span={4}>{patInfo.basicInfo.patSexDesc}  </Col> <Col id="linehidden" span={4}>{patInfo.admInfo.admAge}  </Col>
													<Col span={12}>责医:{patInfo.admInfo.admDocDesc}</Col> <Col span={12} style={{
														maxHeight: '50px',
														overflow: 'hidden',
														whiteSpace: 'nowrap',
														textOverflow: 'ellipsis',
													}}>责护:{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>
													<Col span={24}
														id="medicalNo"
														style={{
															maxHeight: '50px',
															overflow: 'hidden',
															textOverflow: 'ellipsis',
														}}>住院号:{patInfo.basicInfo.patMedicalNo}</Col>
													<Col span={24}
														style={{
															maxHeight: '50px',
															overflow: 'hidden',
															whiteSpace: 'nowrap',
															textOverflow: 'ellipsis',
														}} >费别:{patInfo.admInfo.admReasonDesc}
													</Col>
													{QRCodeVisible && patInfo && 'basicInfo' in patInfo && patInfo.basicInfo && 'patNo' in patInfo.basicInfo && patInfo.basicInfo.patNo ? (
														<div className="flex-center" style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', background: '#fff' }}>
															<QRCode
																renderAs="svg" // 渲染方式默认canvas
																level="Q" // L(<7%),M(<15%),Q(<25%),H(<30%)
																value={patInfo?.basicInfo?.patNo}
																size={116} // 二维码的大小
																fgColor="#000000" // 二维码的颜色
															/>
														</div>
													) : ''}
												</Row>
											}
											<div className="buttonPosition">
												<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, patInfo.admInfo.admID, this.props.BedInfo.unavailReason)}
												>
													{
														this.props.BedInfo.unavailReason === "" ? "换床" : "结束包床"
													}
												</Button>
											</div>
										</Row>
									) : ""
								}
							</Card>
						) : (
							<Card
								title={
									<div className="bedcode">
										{this.props.BedInfo.displayRoom === "N" ? this.props.BedInfo.bedDescripts : (this.props.BedInfo.roomDescripts + "-" + this.props.BedInfo.bedDescripts)}
									</div>
								}
								hoverable
								actions={[<span></span>]}
								headStyle={{
									// background: "#A8E8A3",
								}}
								bodyStyle={
									(!this.props.briefInformation) ? {
										background: this.props.BedInfo?.statusCode === '04' ? '#ffecec' : '#F0FBF8',
									} : {
										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) ? '' : (
										<div style={{ cursor: this.props.selectBedID !== '' && this.props.BedInfo?.statusCode === '04' ? 'no-drop' : 'pointer' }}>
											<div style={{ height: '100%', width: '100%' }}>
												<div
													title={bedInfo.iconTitle}
													className="bedicon"
													style={{
														margin: '27px 0 0 89px',
														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">{this.props.BedInfo?.statusCode === '04' ? '床位已被占用' : '暂无入住患者'}</span>
											</div>
											<div className="buttonPosition">
												{this.props.BedInfo?.statusCode !== '04' ? (
													<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.BedInfo?.statusCode !== '04' && this.props.selectBedID !== '' && user?.hospCode !== 'H23' ? ( // 2023/08/07广州番禺不展示包床按钮
													<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>
												) : ''
												}
												{Util.isEmpty(this.props.BedInfo?.patInfo) && !this.props.selectBedID ? (
													<Button
														className="buttonStyle"
														type="primary"
														onClick={() => this.handleBedOccupancy(this.props.BedInfo)}
														style={{ display: this.props.BedInfo.id === propsState.mouseInID && propsState?.buttondisplay !== 'none' ? 'inline-block' : 'none', width: 'auto' }}
													>
														{this.props.BedInfo.statusCode === '04' ? '取消占床' : '占床'}
													</Button>
												) : ''}
											</div>
										</div>
									)
								}
							</Card>
						)
				}
				<PatientCourseInfo
					activeKey="PatientCourse"
					onRef={this.onConsumeRef}
				/>

				<PatientInfoDetail
					onRef={this.onRef}
					getPatients={this.props.getPatients}
					admID={patInfo.admInfo != undefined ? patInfo.admInfo.admID : ""}
				/>

				{/* 分床 */}
				<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>
			</div>
		)
	}
};

export default Bed;