// 申请列表
import React from 'react';
import { Select, Row, Col, Button, Table, Input, message, Icon } from 'antd';
import { $http } from '../../../containers/config/https';
import store from 'store';
import CommonPagination from 'components/pagination/index';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import CommonRangePicker from 'components/rangePicker/index';
import moment from 'moment';
import asyncComponent from '../../../routers/AsyncComponent.js';
import './style/ApplyList.less';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
const { Option } = Select;
let user;

export default class Apply extends React.Component {

	constructor({ history }) {
		super();
		this.history = history;
		this.ComponentName = "";
		this.state = {
			// 表格数据
			tableData: [],
			// 表格数据总条数
			total: 0,
			size: 'small',
			search: 'search',
			totalWidth: '',
			showLoading: true,
			page: 1,
			pageSize: 10,
			headerHeight: 0,
			loading: false,
			columns: [],
			languageObj: {},
			ENObj: {},
			CNObj: {},
			patNumber: '',
			patNo: '',
			registerTimeStar: moment().format('YYYY-MM-DD'), 				// 开始日期
			registerTimeEnd: moment().format('YYYY-MM-DD'),     // 结束日期
			appTimeStar: moment().format('YYYY-MM-DD'), 				// 预约日期
			appTimeEnd: moment().format('YYYY-MM-DD'),     //  预约结束日期
			iconType: "double-left",
			admID: '',
			patID: '',
			LocArr: [],
			selectID: '',
			ENObj: {},
			CNObj: {},
		};
		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};

	}

	componentDidMount() {
		this.initData();
	}

	componentWillUnmount() {
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state, callback) => { return; }
	}


	initData() {
		// 组件加载完毕关闭loading
		this.setState({ showLoading: false });
		// 初始化列表数据
		this.handleQuery();
		this.getDetaList();
		var box = document.querySelector(".department-header");
		if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
			this.setState({ headerHeight: box.offsetHeight })
		}
	}



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

	// // 提供修改page和pageSize的回调函数
	// compilePage(page, pageSize) {
	// 	// 修改page，或者pageSize
	// 	this.setState({ page: page, pageSize: pageSize }, () => {
	// 		this.handleQuery();
	// 	})
	// }
	// 翻页
	onChange = (page, pageSize) => {
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.handleQuery();
		});
	};

	onShowSizeChange = (current, size) => {
		this.setState({ page: current, pageSize: size }, () => {
			// 重新调用查询方法
			this.onChange(current, size);
		})
	};
	// 获取列表头数据
	getDetaList = () => {
		// let data = {
		let data = {
			params: [{
			    reactCode: ['ApplicationList'],
				compontName: "ApplicationList",
				type: "C",
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					//let colums = [];
					let column = res.result.C;
					if (user.language == 'EN') {
						for (let i = 0; i < column.length; i++) {
							column[i].title = column[i].enDescripts
						}
					}
					this.setState({
						columns: res.result.C,
						tableWidth: res.totalWidth,
						ENObj: res.result.language.EN,
						CNObj: res.result.language.CN
					}, () => {
						this.handleQuery();
					})
				}
			}
		})
	};
	// 请求列表数据
	handleQuery = () => {
		this.setState({ loading: true })
		let { page, pageSize, patNo, patNumber } = this.state;
		let data = {
			params: [{
				patNo: patNumber,
				appNo: patNo,
				locID: this.state.selectID,
				appTimeStar: "",
				appTimeEnd: "",
				registerTimeStar: "",
				registerTimeEnd: "",
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page,
			}]
		};
		$http.post('urlS', this, {
			code: '03020059',
			data: data,
			success: function (res) {
				console.log(res);
				if (+res.errorCode === 0 && res.result) {
					for (var i = 0; i < res.result.ApplicationArr.length; i++) {
						res.result.ApplicationArr[i].key = i
					}
					this.setState({ tableData: res.result.ApplicationArr, total: res.result.totalCount, loading: false, LocArr: res.result.LocArr })
					this.child.handleLoading();
				} else {
					this.setState({ tableData: [], LocArr: [], total: 0, loading: false }, () => {
						// 关闭loading
						this.child.handleLoading();
					})
				}
			}
		})
	}


	handlePatNumber = (e) => {
		this.setState({
			patNumber: e.target.value
		}, () => {
			this.handleQuery();
		})
	}
	handlePatNo = (e) => {
		this.setState({
			patNo: e.target.value
		}, () => {
			this.handleQuery();
		})
	}
	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);

		}

	}

	//单元格点击事件
	onTableRow = (record, index) => {
		const { admID, patID } = record
		//  console.log(record, index);
		return {
			//双击行 
			onClick: () => {
				//this.columnRef.onOpenModel()
				let patientData = {}
				patientData = {
					admID,
					patID,
				}
				sessionStorage.setItem('patientData', JSON.stringify(patientData));
				this.setState({
					admID,
					patID
				}, () => {
					if (this.props.child) this.props.child.loadPatientMsg();
				})
			}
		}
	}
	onColumnRef = (ref) => {
		this.columnRef = ref;
	}
	onChangeselectID = (value) => {
		// console.log(value, "=======>");
		this.setState({ selectID: value }, () => {
			this.handleQuery();
		});
	}
	render() {
		const Component = asyncComponent(() => import('' + this.ComponentName));
		var language = user.language
		var languageObj = {}
		if (language == "EN") {
			languageObj = this.state.ENObj
		} else {
			languageObj = this.state.CNObj
		}
		return (
			this.props.iconType == "double-left" ? (
				<Col className="patientList">
					<ColumnAuthoritysModel
						clientWidth='800px'
						compontName="ApplicationList"
						configType="C"
						onRef={this.onColumnRef}
						reloadData={this.getDetaList}
					/>
					<Row className="searchTitle">
						<Col span={10}>
							<span className='scheduling-title-border'></span>
							<span style={{ marginLeft: 20 }}>{languageObj.ApplicationListSearchPatients != null ? languageObj.ApplicationListSearchPatients.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.ApplicationListPatNo != null ? languageObj.ApplicationListPatNo.descripts : ""}
							value={this.state.patNumber} onChange={this.handlePatNumber}
						>
						</Input>
					</Row>
					<Row className="input-temp">
						<span style={{ marginLeft: '8px' }}>{languageObj.ApplicationListRequest != null ? languageObj.ApplicationListRequest.descripts : ""}</span>
						<Input
							style={{ width: "75%" }}
							allowClear
							placeholder={languageObj.ApplicationListRequest != null ? languageObj.ApplicationListRequest.descripts : ""}
							value={this.state.patNo}
							onChange={this.handlePatNo}
						>
						</Input>
					</Row>
					<Row style={{ marginLeft: '10px' }}>
						<CommonRangePicker
							width={290}
							label={languageObj.ApplicationListAppTime != null ? languageObj.ApplicationListAppTime.descripts : ""}
							startDate={moment()}
							endDate={moment()}
							format={'YYYY-MM-DD'}
							startChange={(date) => this.setState({ appTimeStar: date })}
							endChange={(date) => this.setState({ startTime: date })}
						/>
					</Row>
					<Row style={{ marginLeft: '10px', marginTop: '4px' }}>
						<CommonRangePicker
							width={290}
							label={languageObj.ApplicationListRegister != null ? languageObj.ApplicationListRegister.descripts : ""}
							startDate={moment()}
							endDate={moment()}
							format={'YYYY-MM-DD'}
							startChange={(date) => this.setState({ registerTimeStar: date })}
							endChange={(date) => this.setState({ registerTimeEnd: date })}
						/>
					</Row>
					<div className="quick">
						<Row className="input-temp">
							<Col span={20}>
								<span style={{ marginLeft: '8px' }}>{languageObj.ApplicationListLocDesc != null ? languageObj.ApplicationListLocDesc.descripts : ""}</span>
								<Select
									style={{ width: "75%", marginLeft: '8px' }}
									allowClear
									value={this.state.selectID}
									onChange={this.onChangeselectID.bind(this)}
								>
									{this.state.LocArr.map(data => (<Select.Option key={data.id} value={data.id}>{data.descripts}</Select.Option>))}
								</Select>
							</Col>
							<Col span={4}>
								<Button size="small" type='primary' onClick={this.handleQuery}>{languageObj.ApplicationListSearch!= null ? languageObj.ApplicationListSearch.descripts : ""}</Button>
							</Col>
						</Row>
					</div>
					<div>
						<Table
							onHeaderRow={column => {
								return {
									onDoubleClick: () => {
										this.columnRef.onOpenModel();
									},
								};
							}}
							onRow={this.onTableRow}
							style={{ margin: '20px 20px 0', height: store.getState().tableHeight.y - 45 + 'px' }}
							columns={this.state.columns}
							dataSource={this.state.tableData}
							pagination={false}
							scroll={{ x: 3350, y: store.getState().tableHeight.y }}
							bordered
							showHeader={true}
							className="visinger"
							rowKey={(row) => {
								return row.admID;
							}}
						/>
						{/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
						<CommonPagination className="page-size" 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)} />
		)
	}
}

