/**
 * 生命体征填写(多人)
 */
import React from 'react';
import { $http } from '../../../containers/config/https';
import { Table, Row, Col, Button, DatePicker, TimePicker, message, Select, Input, Switch, Tag } from 'antd';
import Moment from 'moment';
import store from '../../../store';
// import fetchJsonp from 'fetch-jsonp';
import './CSS/VitalSigns.less';
import { temperature } from 'tools/index';
// 组件const
const { Option } = Select;

class VitalSigns extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			column: [],
			tableData: [],
			tableWidth: 1000,
			saveData: {},
			clickRow: '',
			clickCol: '',
			date: '',
			time: '',
			times: [],
			bedList: [],
			stBed: '',
			endBed: '',
			patNo: '',
			errorList: [],
			needFlag: false,
			childFlag: false
		};
	}

	componentDidMount() {
		let leftList = document.querySelectorAll('.vignHeight  .ant-table-body');
		if (leftList.length > 0) {
			leftList[0].style.height = store.getState().tableHeight.y + 75 + 'px';
		}
		message.config({ top: 400, duration: 3 });
		this.getConfigData();
	}

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

	// 获取配置数据
	getConfigData = () => {
		let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		let data = {
			params: [
				{
					hospID: user.hospID, //医院ID
					wardID: user.locID,
					status: 'Y',
					addPatCol: '3',
					childFlag: this.state.childFlag ? 'Y' : 'N'
				}
			]
		};
		$http.post('urlADS', this, {
			code: '04040006',
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					let column = [];
					let obj = {};
					obj.key = 'patName';
					obj.title = '姓名';
					obj.dataIndex = 'patName';
					obj.width = '110px';
					obj.align = 'center';
					obj.fixed = 'left';
					column.push(obj);

					obj = {};
					obj.key = 'admBedCode';
					obj.title = '床号';
					obj.dataIndex = 'admBedCode';
					obj.width = '110px';
					obj.align = 'center';
					obj.fixed = 'left';
					column.push(obj);
					obj = {};

					obj.key = 'patNo';
					obj.title = '患者ID';
					obj.dataIndex = 'patNo';
					obj.width = '110px';
					obj.align = 'center';
					obj.fixed = 'left';
					column.push(obj);
					column = column.concat(res.result.config);
					let width = res.result.width;
					this.setState(
						{
							date: res.result.date,
							time: res.result.time,
							times: res.result.times,
							column: column,
							tableWidth: width,
							bedList: res.result.bedList
						},
						() => {
							this.handleSearch();
						}
					);
				}
			}
		});
	};

	//保存数据
	handleSave = () => {
		let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		let data = {
			params: [
				{
					dataList: this.state.saveData,
					hospID: user.hospID, //医院ID
					userID: user.userID, //用户ID
					date: this.state.date,
					time: this.state.time
				}
			]
		};
		$http.post('urlADS', this, {
			code: '04040007',
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					if (res.errorList.length !== 0) {
						message.error(res.errorList.join(';'));
					} else {
						message.success('保存成功！');
					}
					this.handleSearch();
				}
			}
		});
	};

	//查询数据
	handleSearch = () => {
		let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		let patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
		let num = '';
		if (this.state.patNo.length > 0) {
			let No = this.state.patNo ? this.state.patNo : '';
			num = (Array(10).join(0) + No).slice(-10);
		}
		let data = {
			params: [
				{
					hospID: user.hospID, //医院ID
					wardID: user.locID,
					flag: this.state.needFlag ? 'Y' : 'N',
					date: this.state.date,
					time: this.state.time,
					stBed: this.state.stBed,
					endBed: this.state.endBed,
					patNo: num ? num : '',
					admID: patientData.admID,
					childFlag: this.state.childFlag ? 'Y' : 'N'
				}
			]
		};
		$http.post('urlADS', this, {
			code: '04040005',
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					this.setState({
						tableData: res.result.patList,
						clickRow: '',
						clickCol: '',
						saveData: {},
						errorList: res.result.errorList,
						patNo: num != undefined ? num : ''
					});
				}
			}
		});
	};

	///单元格点击事件
	onTableRow = (record, index) => {
		return {
			onClick: (event) => {
				this.setState({
					clickRow: record.admID
				});
			},
			onDoubleClick: (event) => { }
		};
	};

	//编辑框文本变化事件
	onChange = (col, record, index, e) => {
		e.stopPropagation();
		let errorList = this.state.errorList;
		errorList[index + '.' + col.dataIndex] = 0;
		let value = e.target.value;
		record[col.dataIndex] = e.target.value;
		let saveData = this.state.saveData;
		if (e.target.value == '') {
			// 清除关联项目
			let linkedItemCodeArr = col.linkedItemCodeStr.split('^');
			for (let i = 0; i < linkedItemCodeArr.length; i++) {
				record[linkedItemCodeArr[i]] = '';
			}
		}
		let saveRecord = saveData[record.admID];
		if (!saveRecord) {
			saveData[record.admID] = { [col.dataIndex]: value };
		} else {
			saveData[record.admID][col.dataIndex] = value;
		}

		if ((col.normalRangeFrom !== '' || col.normalRangeTo !== '') && value !== '') {
			//非负浮点数（正浮点数 + 0）：^\d+(\.\d+)?$
			var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; //正浮点数
			errorList[index + '.' + col.dataIndex] = 0;
			if (!regex.test(value)) {
				//message.warn("请注意：" + col.title + "数据格式不正确");
				errorList[index + '.' + col.dataIndex] = 1;
			} else {
				if (col.normalRangeFrom !== '' && parseFloat(value) < parseFloat(col.normalRangeFrom)) {
					//message.warn("请注意：" + col.title + "值小于正常低值");
					errorList[index + '.' + col.dataIndex] = 2;
				}
				if (col.normalRangeTo !== '' && parseFloat(value) > parseFloat(col.normalRangeTo)) {
					// message.warn("请注意：" + col.title + "值大于正常高值");
					errorList[index + '.' + col.dataIndex] = 2;
				}

				if (col.normalRangeFrom !== '' && parseFloat(value) < parseFloat(col.errorRangeFrom)) {
					//message.warn("请注意：" + col.title + "值小于错误低值");
					errorList[index + '.' + col.dataIndex] = 3;
				}
				if (col.normalRangeTo !== '' && parseFloat(value) > parseFloat(col.errorRangeTo)) {
					// message.warn("请注意：" + col.title + "值大于错误高值");
					errorList[index + '.' + col.dataIndex] = 3;
				}
			}
		}
		this.forceUpdate();
	};

	//支持上下左右回车切换
	onKeyDownEnter = (col, row, colObj, e) => {
		if (e !== '') {
			e.stopPropagation();
		}
		// col 列
		// row 行
		if (e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40 && e.keyCode !== 13) {
			return false;
		}
		let column = this.state.column;
		let flag = true;
		let first = '',
			end = ''; //第一个和最后一个可编辑的列
		for (var i = 0; i < column.length; i++) {
			if (column[i].editable === 'Y' && first === '') {
				first = i;
			}
			if (column[i].editable === 'Y') {
				end = i;
			}
		}
		if (col === end && row === this.state.tableData.length - 1) {
			this.setState({ clickCol: 0 + '.' + first });
			return;
		}
		switch (e.keyCode) {
			case 37: //左
				col--;
				break;
			case 38: //上
				row--;
				break;
			case 39: //右
				col++;
				break;
			case 40: //下
				row++;
				break;
			case 13:
				flag = false;
				this.onPressEnter(col, row, e);
				break;
		}
		if (row > this.state.tableData.length - 1) {
			return false;
		}
		if (col > end) {
			col = first;
			row = row + 1;
		}
		let value = e.target.value;
		if ((colObj.normalRangeFrom !== '' || colObj.normalRangeTo !== '') && value !== '') {
			//非负浮点数（正浮点数 + 0）：^\d+(\.\d+)?$
			// var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; //正浮点数
			let regex = /^\d+(\.\d+)?$/
			if (!regex.test(parseFloat(value))) {
				message.warn('请注意：' + colObj.title + '数据格式不正确');
			} else {
				if (colObj.normalRangeFrom !== '' && parseFloat(value) < parseFloat(colObj.normalRangeFrom)) {
					message.warn('请注意：' + colObj.title + '值小于正常低值');
				}
				if (colObj.normalRangeTo !== '' && parseFloat(value) > parseFloat(colObj.normalRangeTo)) {
					message.warn('请注意：' + colObj.title + '值大于正常高值');
				}
			}
		}
		if (flag) {
			this.setState({ clickCol: row + '.' + col });
		}
	};

	///编辑框回车事件
	onPressEnter = (colIndex, index, e) => {
		if (e !== '') {
			e.stopPropagation();
		}
		let column = this.state.column;
		let clickCol = this.state.clickCol;
		let first = '';
		let next = '';
		for (var i = 0; i < column.length; i++) {
			if (column[i].editable === 'Y' && first === '') {
				first = i;
			}
			if (column[i].editable === 'Y' && next === '' && i > colIndex) {
				next = i;
			}
		}
		if (next === '') {
			next = first;
			index = index + 1;
		}

		if (index < this.state.tableData.length) {
			clickCol = index + '.' + next;
		} else {
			clickCol = '0.' + first;
		}
		this.setState({ clickCol: clickCol });
	};

	///失去焦点触发的事件
	onBlur = (col, record, index, e) => {
		e.stopPropagation();
		let value = e.target.value;
		if ((col.normalRangeFrom !== '' || col.normalRangeTo !== '') && value !== '') {
			//非负浮点数（正浮点数 + 0）：^\d+(\.\d+)?$
			// var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; //正浮点数
			let regex = /^\d+(\.\d+)?$/
			if (!regex.test(parseFloat(value))) {
				message.warn('请注意：' + col.title + '数据格式不正确');
			} else {
				if (col.normalRangeFrom !== '' && parseFloat(value) < parseFloat(col.normalRangeFrom)) {
					message.warn('请注意：' + col.title + '值小于正常低值');
				}
				if (col.normalRangeTo !== '' && parseFloat(value) > parseFloat(col.normalRangeTo)) {
					message.warn('请注意：' + col.title + '值大于正常高值');
				}
			}
		}
		this.setState({ clickCol: '' });
	};

	/// 修改日期
	handleDateChange = (date, datetimeString) => {
		let today = Moment(this.state.toDay);
		/*
		if (Moment(datetimeString).valueOf() > today.valueOf()) {
			message.warn('日期不能超过当天!');
			return;
		}
		*/
		this.setState(
			{
				date: datetimeString
			},
			() => {
				this.handleSearch();
			}
		);
	};

	disabledDate = (dateValue) => {
		if (this.state.toDay === '') {
			return false;
		}
		let today = Moment(this.state.toDay);
		return dateValue.valueOf() > today.valueOf();
	};

	///修改时间
	onTimeSelect = (value) => {
		this.setState(
			{
				time: value
			},
			() => {
				this.handleSearch();
			}
		);
	};

	///起始床位
	onStBedSelect = (value) => {
		this.setState({
			stBed: value
		});
	};

	///结束床位
	onEndBedSelect = (value) => {
		this.setState({
			endBed: value
		});
	};

	///患者ID
	onPatNoChange = (e) => {
		e.stopPropagation();
		this.setState({
			patNo: e.target.value
		});
	};

	//空白栏选择
	onBlankItemChange = (col, record, index, colIndex, value) => {
		let errorList = this.state.errorList;
		if (!value) {
			value = '';
		}
		errorList[index + '.' + col.dataIndex] = 0;
		record[col.dataIndex] = value;
		let saveData = this.state.saveData;
		let saveRecord = saveData[record.admID];
		if (!saveRecord) {
			saveData[record.admID] = { [col.dataIndex]: value };
		} else {
			saveData[record.admID][col.dataIndex] = value;
		}
		this.forceUpdate();
		this.onPressEnter(colIndex, index, '');
	};

	///单元格样式修改
	renderColItem = (col, colIndex, text, record, index) => {
		let obj = {
			children: text,
			props: {
				style: {}
			}
		};
		if (record.need[col.dataIndex] == '1') {
			obj.props.className = 'colors NeedTest';
		}
		if (record.need[col.dataIndex] == '2') {
			obj.props.className = 'colors TestedAndMeasured';
		}

		if (index + '.' + colIndex === this.state.clickCol && col.editable === 'Y') {
			if (col.blankItemFlag === 'Y') {
				text = (
					<Select
						autoFocus={true}
						allowClear={true}
						key={index + '.' + col.dataIndex}
						style={{ width: '100%' }}
						defaultValue={text}
						onChange={this.onBlankItemChange.bind(this, col, record, index, colIndex)}
					>
						{col.blankItem.map((item) => {
							return <Option key={item}>{item}</Option>;
						})}
					</Select>
				);
			} else {
				if (col.linkItem !== '' && record[col.linkItemCode] === '') {
					message.warn('请先录入关联项目值!');
				}
				text = (
					<Input
						autoFocus="autoFocus"
						key={index + '.' + col.dataIndex}
						style={{
							backgroundColor:
								this.state.errorList[index + '.' + col.dataIndex] === undefined
									? '#ffffff'
									: this.state.errorList[index + '.' + col.dataIndex] === 0
										? '#ffffff'
										: this.state.errorList[index + '.' + col.dataIndex] === 1 ||
											this.state.errorList[index + '.' + col.dataIndex] === 3
											? '#f50'
											: '#faad14'
						}}
						defaultValue={text}
						onChange={this.onChange.bind(this, col, record, index)}
						onBlur={this.onBlur.bind(this, col, record, index)}
						onKeyDown={this.onKeyDownEnter.bind(this, colIndex, index, col)}
					/>
				);
			}
			obj.children = text;
			return obj;
		} else {
			obj.props.style.backgroundColor =
				this.state.errorList[index + '.' + col.dataIndex] === undefined
					? record.admID == this.state.clickRow ? '#bfe6f8' : '#ffffff'
					: this.state.errorList[index + '.' + col.dataIndex] === 0
						? record.admID == this.state.clickRow ? '#bfe6f8' : '#ffffff'
						: this.state.errorList[index + '.' + col.dataIndex] === 1 ||
							this.state.errorList[index + '.' + col.dataIndex] === 3
							? '#ff5500'
							: '#faad14';
			return obj;
		}
	};

	///点击单元格
	onCell = (colIndex, record, index) => {
		return {
			onClick: (event) => {
				this.setState({
					clickCol: index + '.' + colIndex
				});
			},
			onDoubleClick: (event) => { }
		};
	};

	//需测体征查询
	onSwitchChange = (flag) => {
		this.setState({ needFlag: flag }, () => {
			this.handleSearch();
		});
	};

	//婴儿体征
	personTypeChange = (flag) => {
		this.setState({ childFlag: flag }, () => {
			this.getConfigData();
		});
	};

	//预览体温单
	previewTemperature = () => {
		temperature.previewTemperature(this.state.clickRow);
		return;
		/*
				if (this.state.clickRow == '') {
						message.warn("请先选择患者");
						return;
				}
				let dllInput = {};
				dllInput.exeName = "XYSTemperature.exe";
				dllInput.path = "C:\\ProgramData\\XYS\\XYSService\\plugins\\Temperature\\";
				let parameter = "";
				let sessionObj = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
				Object.keys(sessionObj).forEach(function (key) {
						parameter = parameter + key + ":" + sessionObj[key] + ",";

				});
				parameter = parameter + "wardID:" + sessionObj.locID;
				parameter = parameter + "," + "admID:" + this.state.clickRow;
				dllInput.parameter = parameter;

				let data = 'input={"inputDir":"Temperature/OpenExe.dll","clsName":"OpenExe.ExeObj","funcName":"CreateProcess","dllInput":' + JSON.stringify(dllInput) + '}'
				let that = this
				fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
						jsonpCallback: 'JsonCallback',
						timeout: 30000,
				})
						.then(function (response) {
								return response.json()
						}).then(function (json) {
						}).catch(function (ex) {
						})
				*/
	};

	///行背景色
	setRowClassName = (record) => {
		if (this.state.clickRow == '') {
			return '';
		}
		return record.admID == this.state.clickRow ? 'clickRowStyle1' : '';
	};
	
	render() {
		const tableHeight = store.getState().tableHeight.y;
		const columns = this.state.column.map((col, colIndex) => {
			return {
				...col,
				render: this.renderColItem.bind(this, col, colIndex),
				onCell: this.onCell.bind(this, colIndex)
			};
		});
		let stBedList = [],
			endBedList = [];
		this.state.bedList.map((bed) => {
			let stDisabled = false,
				endDisabled = false;
			if (this.state.endBed !== '' && parseInt(bed) > parseInt(this.state.endBed)) {
				stDisabled = true;
			}
			if (this.state.stBed !== '' && parseInt(bed) < parseInt(this.state.stBed)) {
				endDisabled = true;
			}
			stBedList.push(
				<Option disabled={stDisabled} key={bed}>
					{' '}
					{bed}{' '}
				</Option>
			);
			endBedList.push(
				<Option disabled={endDisabled} key={bed}>
					{' '}
					{bed}{' '}
				</Option>
			);
		});
		let times = [];
		this.state.times.map((time) => {
			times.push(<Option key={time}> {time} </Option>);
		});

		return (
			<div className="colors">
				<div className="table-operations">
					<Row style={{ height: '48px', padding: '0 24px 0px 24px' }}>
						<Col span={20} style={{ lineHeight: '48px', height: '48px' }}>
							日期选择:{' '}
							<DatePicker
								// disabledDate={this.disabledDate}
								style={{ width: '10%', margin: '0px 15px 0 0' }}
								onChange={this.handleDateChange}
								value={this.state.date === '' ? null : Moment(this.state.date, 'YYYY-MM-DD')}
							/>
							<Select
								style={{ width: '10%', margin: '0px 15px 0 0' }}
								value={this.state.time}
								onChange={this.onTimeSelect}
								placeholder="时间"
							>
								{times}
							</Select>
							起始床号:<Select
								allowClear={true}
								value={this.state.stBed}
								onChange={this.onStBedSelect}
								placeholder="起始床号"
								style={{ width: '10%', margin: '0px 15px 0 0' }}
							>
								{stBedList}
							</Select>
							结束床号:<Select
								allowClear={true}
								value={this.state.endBed}
								onChange={this.onEndBedSelect}
								placeholder="结束床号"
								style={{ width: '10%', margin: '0px 15px 0 0' }}
							>
								{endBedList}
							</Select>
							患者ID:<Input
								allowClear={true}
								value={this.state.patNo}
								onChange={this.onPatNoChange}
								placeholder="患者ID(Enter)"
								onPressEnter={this.handleSearch}
								style={{ width: '10%', margin: '0px 15px 0 0' }}
							/>
							需测体征:{' '}
							<Switch
								style={{ margin: '0 15px 0 0' }}
								checked={this.state.needFlag}
								onChange={this.onSwitchChange}
							/>
							婴儿:{' '}
							<Switch
								style={{ margin: '0 15px 0 0' }}
								checked={this.state.childFlag}
								onChange={this.personTypeChange}
							/>
						</Col>
						<Col span={4} style={{ textAlign: 'right', lineHeight: '48px', height: '48px' }}>
							<Button
								onClick={this.handleSearch}
								style={{ background: '#FFFFFF', margin: '0px 10px 0 0' }}
							>
								查询
							</Button>
							<Button
								onClick={this.handleSave}
								type="primary"
								style={{ color: '#fff', margin: '0px 10px 0 0' }}
							>
								保存
							</Button>
							<Button onClick={this.previewTemperature} type="primary" style={{ color: '#fff' }}>
								预览
							</Button>
						</Col>
					</Row>
				</div>

				<div style={{ width: '100%', height: '10px', background: '#f0f2f5' }} />
				<div style={{ padding: '0 12px' }} className="vitalSingTable">
					<div>
						<Row style={{ minHeight: '40px', padding: '8px 0px 8px 0px' }}>
							<Col span={24} style={{ textAlign: 'right' }}>
								<div className="contentment" style={{ float: 'Right' }}>
									<span className="contenttemp" />&nbsp;&nbsp;错误数据
									<span className="contenttmp" />&nbsp;&nbsp;非正常数据
									<span className="contenttim" />&nbsp;&nbsp;需测未测
									<span className="contentopr" />&nbsp;&nbsp;需测已测
								</div>
							</Col>
						</Row>
						<Table
							className="vignHeight"
							onRow={this.onTableRow}
							columns={columns}
							dataSource={this.state.tableData}
							scroll={{ x: this.state.tableWidth, y: store.getState().tableHeight.y + 90 + 'px' }}
							style={{ height: store.getState().tableHeight.y + 136 }}
							pagination={false}
							rowClassName={this.setRowClassName}
							rowKey={(row) => {
								return row.admID;
							}}
							bordered
						/>
					</div>
				</div>
			</div>
		);
	}
}
export default VitalSigns;
