// 手术申请
import React, { Component } from 'react';
import { Row, Col, Table, Select, Button, message, Checkbox, Input, Icon, Tooltip } from 'antd';
import { $http } from '../../../containers/config/https';
import moment from 'moment';
import CommonPagination from 'components/pagination/index';
import CommonRangePicker from 'components/rangePicker/index';
import store from 'store';
import './style/OperationSearch.less';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';

// 用户数据
let userData;
export default class DoctorDiag extends Component {
	constructor(props) {
		super(props);
		this.state = {
			//tableType: 'C',
			type: "checkbox",
			columns: [],
			tableData: [],              // table数据
			total: 0,                  // table数据总量            
			applyLocData: [],			// 申请科室下拉数据
			operationRoomData: [],		// 手术间下拉数据
			operationTypeData: [],		// 手术类型下拉数据
			operationStatusData: [],	// 手术状态下拉数据
			patWardData: [],			// 患者病区下拉数据
			stDate: moment(new Date()).add(-3, 'days').format('YYYY-MM-DD'), 				// 开始日期
			endDate: moment(new Date()).add(1, 'days').format('YYYY-MM-DD'),     // 结束日期
			applyDateFlag: '',			// 按申请日期
			applyLocID: '',				// 申请科室
			operationRoomID: '',		// 手术间
			operationStatusID: '',		// 手术状态
			operationTypeID: '',		// 手术类型
			patWardID: '',				// 患者病区
			number: '',					// 患者信息
			condition: '',				// 条件
			page: '1',
			pageSize: '10',
			clickFlag: false,
			checked: false,
			patNumber: '',
			errorList: [],
			clickCol: '',
			tableWidth: 0,
			selectedRows: [],//左边的勾选清除
			editingKey: '',
			opertaionData: [],
			operationStatus: '',
			locType: '',
			operationType: '',
			TableListData: [],
			visibleOperationCheck: false,
			iconType: "double-left",
			size: 'small',
			search: 'search',
			totalWidth: '',
			selectPatient: [],
			admID: '',
			ENObj: {},
			CNObj: {},
			languageObj: {},

		}
		userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
	}

	componentDidMount() {
		this.getTableTitle();
		this.getApplyLocData();
		this.getPatWardData();
		this.getOption();
		this.getOperationInfo();
		this.getselect();
		//document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
	}

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

	onColumnRef = (ref) => {
		this.columnRef = ref;
	}

	//查询表头信息
	getTableTitle = () => {
		let data = {
			params: [{
				reactCode: ['OperationPatients'],
				compontName: 'OperationPatients',
				type: "C",
			}]
		}
		$http.post('urlS', this, {
			code: '01040073',
			data: data,
			success: function (res) {
				// console.log(res);
				if (+res.errorCode === 0) {
					let column = res.result.C;
					if (userData.language == 'EN') {
						for (let i = 0; i < column.length; i++) {
							column[i].title = column[i].enDescripts
						}
					}
					let columns = res.result?.C || [];
					if (columns && columns.length > 0) {
						columns = columns.map(item => {
							return {
								...item,
								render: (text, record) => {
									if (item.dataIndex === 'patDiag') {
										return (
											<Tooltip title={text} onClick={e => React.$stopPropagation(e)}>
												<span className="ellipsis" style={{ width: '100%', display: 'block' }} onClick={e => React.$stopPropagation(e)}>
													{text}
												</span>
											</Tooltip>
										);
									} else {
										return text;
									}
								}
							}
						})
					}
					this.setState({
						columns,
						tableWidth: res.totalWidth,
						ENObj: res.result.language.EN,
						CNObj: res.result.language.CN,
						//languageObj: languageObj
					}, () => {
						this.getOperationInfo();
					})
				}
			}
		});
	}

	//患者病区
	handlePat = (e) => {
		this.setState({
			patWardID: e
		}, () => {
			this.getOperationInfo();
		});
	};

	//登记名/证件/姓名
	handlePatNumber = (e) => {
		this.setState({
			patNumber: e.target.value
		}, () => {
			this.getOperationInfo();
		})
	}

	//状态
	handleStatusData = (e) => {
		this.setState({
			operationStatus: e
		}, () => {
			this.getOperationInfo();
		})
	}

	//类型
	handleoperationType = (e) => {
		this.setState({
			operationType: e
		}, () => {
			this.getOperationInfo();
		})
	}

	// 获取下拉框数据
	getselect = () => {
		let data = {
			params: [{
				locID: userData.locID
			}]
		};
		$http.post('urlDeault', this, {
			code: "04160005",
			data: data,
			success: function (res) {
				//	console.log(res);
				if (+res.errorCode === 0) {
					this.setState({
						operationRoomData: res.result
					})
				}
			},
			error: function (error) {
				message.error('失败：' + error);
			}
		});
	}

	//获取科室下拉数据
	getApplyLocData = () => {
		let data = {
			params: [{
				hospID: userData.hospID,
				type: 'O^I^OI^E',
			}]
		}
		$http.post('urlS', this, {
			code: '04020008',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						applyLocData: res.result.Data,
					})
				}
			}
		});
	}

	//获取病区下拉数据
	getPatWardData = () => {
		let data = {
			params: [{
				hospID: userData.hospID,
				type: 'W',
			}]
		}
		$http.post('urlS', this, {
			code: '04020008',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						patWardData: res.result.Data,
					})
				}
			}
		});
	}

	// 获取下拉数据源
	getSelectData = () => {
		let data = {
			params: [{

			}]
		};
		$http.post('urlDeault', this, {
			code: "**",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						conTypeData: res.result.conType
					})
				}
			},
			error: function (error) {
				message.error('失败：' + error);
			}
		});
	}

	// 获取下拉数据源
	getOption = () => {
		let data = {
			params: [{

			}]
		};
		$http.post('urlDeault', this, {
			code: "04160007",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						operationStatusData: res.result.operationStatusData,
						operationTypeData: res.result.operationTypeData,
						locType: res.result.locType,
					})
				}
			},
			error: function (error) {
				message.error('失败：' + error);
			}
		});
	}

	// 查询手术信息
	getOperationInfo = () => {
		this.setState({
			clickFlag: true
		})
		let { page, pageSize, patWardID, patNumber, operationStatus, operationType } = this.state;
		let data = {
			"params": [{
				startDate: moment(this.state.stDate).format('YYYY-MM-DD'),
				stopDate: moment(this.state.endDate).format('YYYY-MM-DD'),
				applyFlag: 'N',
				applyLocID: "",
				operationRoomID: "",
				operationStatusID: operationStatus,
				operationType: operationType,
				patNumber: patNumber,
				patWardID: patWardID,
				finishFlag: this.state.checked ? 'Y' : "N",
				menuFlag: 'NurseOrder',		//菜单标记，NurseOrder-护士医嘱录入
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page,

			}]
		};
		$http.post('urlDeault', this, {
			code: "04160006",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let tableData = res.result.Data;
					for (let i = 0; i < tableData.length - 1; i++) {
						tableData[i].key = i
					}
					this.setState({
						tableData,
						clickCol: '',
						total: res.result.TotalCount,
						clickFlag: false
					})
				} else {
					this.setState({
						clickFlag: false
					})
				}
			},
			error: function (error) {
				message.error('失败：' + error);
				this.setState({
					clickFlag: false
				})
			}
		});
	}

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

			}
		}
	}

	// 翻页
	onChange = (page, pageSize) => {
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.getOperationInfo();
		});
	};

	onShowSizeChange = (current, size) => {
		this.setState({ page: current, pageSize: size }, () => {
			// 重新调用查询方法
			this.onChange(current, size);
		})
	};

	// 获取Checkbox操作后的值
	handleCheckbox = (e) => {
		this.setState({ checked: e.target.checked });
	}

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

	requestConsome = () => {
		this.childConsume.showModal();
	};

	//单元格点击事件
	onTableRow = (record, index) => {
		const { admID, patID } = record
		// console.log(record, index);
		return {
			//双击行 
			onClick: () => {
				let patientData = {}
				patientData = {
					admID,
					patID,
				}

				this.setState({
					admID,
					patID,
					indexID: record.id
				}, () => {
					sessionStorage.setItem('patientData', JSON.stringify(patientData));
					setTimeout(() => {
						if (this.props.child) this.props.child.loadPatientMsg(this.state.indexID);
					}, 300)
					this.props.updateState({ admID });
				})
			}
		}
	}

	setRowClassName = (record) => {
		return record.id == this.state.indexID ? 'clickRowStyle' : '';
	}

	onMenuFoldClick = (e) => {
		let obj = {};
		if (this.props.iconType != "double-left") {
			obj.leftspan = 5;
			obj.rightspan = 19;
			obj.iconType = "double-left"
			this.props.updateState(obj);
		}
		else {
			obj.leftspan = 0;
			obj.rightspan = 24;
			obj.iconType = "double-right"
			this.props.updateState(obj);
		}
	}

	renderColItem = (col, colIndex, text, record, index) => {
		let obj = {
			children: text,
			props: {
				style: {}
			},
		};
		obj.props.style.width = col.width;
		obj.children = <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
		return obj;
	}

	render() {
		var language = userData.language
		var languageObj = {}
		if (language == "EN") {
			languageObj = this.state.ENObj
		} else {
			languageObj = this.state.CNObj
		}

		let width = this.state.totalWidth.split("px")[0] || 300;
		width = Number(width);
		const columns = this.state.columns.map((col, colIndex) => {
			return {
				...col,
				render: this.renderColItem.bind(this, col, colIndex),
			};
		});
		return (
			this.props.iconType == "double-left" ? (
				<Col className="patientList operationSearch">
					<ColumnAuthoritysModel
						clientWidth='800px'
						compontName="OperationPatients"
						configType="C"
						onRef={this.onColumnRef}
						reloadData={this.getTableTitle}
					/>
					<Row className="searchTitle">
						<Col span={10}>
							<span className='scheduling-title-border' style={{ top: 1 }}></span>
							<span style={{ marginLeft: 20 }}>{languageObj.OperationPatientsSearchPatients != null ? languageObj.OperationPatientsSearchPatients.descripts : ""}</span>
						</Col>
						<Col span={5} offset={9} style={{ width: "30px" }}>
							<Icon className="foldIcon" style={{ fontSize: "18px", marginLeft: 51 }} type={this.props.iconType} onClick={this.onMenuFoldClick.bind(this)} />
						</Col>
					</Row>
					<Row className="inputSearch">
						<Input
							style={{ width: "94%", marginLeft: '8px' }}
							allowClear
							placeholder={languageObj.OperationPatientsPatNoNumberPatName != null ? languageObj.OperationPatientsPatNoNumberPatName.descripts : ""}
							value={this.state.patNumber}
							onChange={this.handlePatNumber}
						>
						</Input>
					</Row>
					<Row style={{ marginLeft: '10px' }}>
						<CommonRangePicker
							width={319}
							label={languageObj.OperationPatientsDate != null ? languageObj.OperationPatientsDate.descripts : ""}
							startDate={moment(new Date()).add(-3, 'days')}
							endDate={moment(new Date()).add(1, 'days')}
							format={'YYYY-MM-DD'}
							startChange={(date) => this.setState({ stDate: date })}
							endChange={(date) => this.setState({ endDate: date })}
						/>
					</Row>
					<div className="quickSearch">
						<Row className="quikselect">
							<Col span={12}>
								<span>{languageObj.OperationPatientsStatus != null ? languageObj.OperationPatientsStatus.descripts : ""}</span>
								<Select
									allowClear
									style={{ width: "65%", marginLeft: '8px' }}
									value={this.state.operationStatus} onChange={this.handleStatusData}
								>
									{this.state.operationStatusData.map(data => (<Select.Option key={data.id} value={data.id}>{data.descripts}</Select.Option>))}
								</Select>
							</Col>
							<Col span={12}>
								<span style={{ marginRight: '8px' }} >{languageObj.OperationPatientsApplyDate != null ? languageObj.OperationPatientsApplyDate.descripts : ""}</span>
								<Checkbox style={{ marginRight: '8px' }} checked={this.state.checked} onChange={this.handleCheckbox}></Checkbox>
							</Col>
						</Row>
						<Row className="quikselect">
							<Col span={12}>
								<span>{languageObj.OperationPatientsType != null ? languageObj.OperationPatientsType.descripts : ""}</span>
								<Select
									allowClear
									style={{ width: '65%', marginLeft: '8px' }}
									value={this.state.operationType} onChange={this.handleoperationType}
								>
									{this.state.operationTypeData.map(data => (<Select.Option key={data.id} value={data.id}>{data.descripts}</Select.Option>))}
								</Select>
							</Col>
							<Col span={12}>
								<span>{languageObj.OperationPatientsInWard != null ? languageObj.OperationPatientsInWard.descripts : ""}</span>
								<Select
									value={this.state.patWardID} onChange={this.handlePat}
									allowClear
									style={{ width: '65%', marginLeft: '8px' }}
								>
									{this.state.patWardData.map(data => (<Select.Option key={data.id} value={data.id}>{data.descripts}</Select.Option>))}
								</Select>
							</Col>
						</Row>
						<Row className="QSearch">
							{/* <Col span={12}>
								&nbsp;&nbsp;&nbsp;<Checkbox checked={this.state.checked} onChange={this.handleCheckbox}>申请日期</Checkbox>
							</Col> */}
							<Col span={4} offset={20}>
								<Button size="small" type='primary' onClick={this.getOperationInfo}> {languageObj.OperationPatientsSearch != null ? languageObj.OperationPatientsSearch.descripts : ""}</Button>
							</Col>
						</Row>
					</div>
					<div>
						<Table
							onHeaderRow={column => {
								return {
									onDoubleClick: () => {
										this.columnRef.onOpenModel();
									},
								};
							}}
							onRow={this.onTableRow}
							style={{ margin: '57px 20px 0', height: store.getState().tableHeight.y - 45 + 'px' }}
							columns={this.state.columns}
							dataSource={this.state.tableData}
							pagination={false}
							scroll={{ x: this.state.tableWidth, y: store.getState().tableHeight.y }}
							bordered
							showHeader={true}
							// rowSelection={rowSelection}
							className="visinger"
							rowKey={(row) => {
								return row.id;
							}}
							rowClassName={this.setRowClassName}
						/>
						{/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
						<CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
							onShowSizeChange={this.onShowSizeChange.bind(this)} complete={false} dataSource={this.state.tableData}
							loading={this.state.loading} onChange={this.onChange.bind(this)} />
					</div>
				</Col>
			)
				:
				<Icon className="openfoldIcon" style={{ fontSize: "18px", overflow: 'hidden', zIndex: '1000', height: '22px', width: '22px' }} type={this.props.iconType} onClick={this.onMenuFoldClick.bind(this)} />
		)
	}
}