//收费员个人结账（住院）
import React from 'react';
import { DatePicker, Table, Button, Tabs, Row, Col, Card, message } from 'antd';
import moment from 'moment';
import { $http } from '../../../containers/config/https';
import { Util } from 'tools/index';
import store from '../../../store'
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $loopPrint } from '../../lodop/Common/Print.js';
import '../style/index.less';
const { TabPane } = Tabs;

export default class InvRecordHospital extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			data: [],
			Topdata: [],
			INVReportsArr: undefined,
			userInfo: {},
			showLoading: true,
			// 表格数据总条数
			invtotal: 0,
			deptotal: 0,
			page: 1,
			pageSize: 10,
			page2: 1,
			pageSize2: 10,
			languageTable1: {}, // 国际化Table1
			languageTable2: {}, // 国际化Table2
			languageData: {}, // 国际化语言包
			language: {},   // 国际化语言
			languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
			stopDateTime: moment().format('YYYY-MM-DD HH:mm:ss'),
			loading2: false
		}
	}

	//初始化数据
	componentDidMount() {
		this.tableList("InvRecordHospital", "InvRecordHospital");
		this.tableList("InvRecordHospitallist", "InvRecordHospitallist");
		if (this.props.flag === 'modal') {
			this.props.onRef(this)
			this.setState({
				userInfo: this.props.userInfo
			}, () => {
				this.invRecordQuery()
				this.DepositQuery()
			})
		} else {
			this.getStartDate()
		}
	}

	// 获取主列表columns收费
	tableList = (reactCode, compontName) => {
		var data = {
			params: [{
				"reactCode": [reactCode],
				"compontName": compontName,
				"type": "C"
			}]
		}
		$http.post('urlS', this, {
			code: '01040073',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let resC = res.result.C
					let { languageCode } = this.state
					for (var i = 0; i < resC.length; i++) {
						resC[i].key = i;
					}
					if (languageCode === "EN") {
						resC.map((item, i) => {
							item.title = item.enDescripts
						})
					}

					if (languageCode === "CN") {
						resC.map((item, i) => {
							item.title = item.descripts
						})
					}
					let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
						return {
							align: item.align,
							widthNum: parseInt(item.width),
							width: item.width,
							dataIndex: item.dataIndex,
							title: <div onDoubleClick={() => this.setState({ ColumnAuthority: compontName }, () => this.columnRef.onOpenModel())}>{item.title}</div>,
							display: item.display,
							key: item.seqNo
						}
					}) : '';
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
					if (compontName === 'InvRecordHospital') {
						this.setState({
							columns: filterArr,
							languageTable1: res.result.B || {},  // 国际化Table1
							languageTable2: res.result.C || {},  // 国际化Table2
							languageData: res.result.language || {},  // 国际化语言包
						}, () => {
							this.LanCNEN(this.state.languageCode)
						})
					} else {
						this.setState({
							columns2: filterArr,
						})
					}
				}
			}
		})
	}

	LanCNEN = (code) => {
		let { languageData } = this.state
		this.setState({
			language: languageData[code]
		})
	}

	//结账时间区开始时间
	getStartDate = () => {
		let data = {}
		data = {
			params: [{
				"userID": JSON.parse(window.sessionStorage.userData).userID,
				"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				"type": "I"
			}],
		};
		$http.post("urlS", this, {
			code: '05100100',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					if (res.result.length > 0) {
						this.setState({
							INVReportsArr: res.result[0].footDateTime === ' ' ? undefined : res.result[0].footDateTime
						}, () => {
							this.invRecordQuery()
							this.DepositQuery()
						})
					} else {
						this.invRecordQuery()
						this.DepositQuery()
					}

				}
			},
			error: function (err) {
				this.setState({ errMsg: "数据加载失败，请重试!" });
			}
		});
	}

	//基础数据(收费\集中打印)
	invRecordQuery = () => {
		let { page, pageSize } = this.state;
		let data = {}
		data = {
			params: [{
				"startDate": this.state.INVReportsArr ? moment(this.state.INVReportsArr).utcOffset(480).format('YYYY-MM-DD HH:mm:ss') : '',
				"stopDate": this.state.stopDateTime,
				"userID": JSON.parse(window.sessionStorage.userData).userID,
				"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				"reportsID": this.state.userInfo.ID || '',
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page,
				sortColumn: 'code',
				sortOrder: 'asc'
			}]
		}
		$http.post('urlDeanlt', this, {
			code: '05100144',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for (var i = 0; i < res.result.length; i++) {
						res.result[i].key = i;
					}
					this.setState({ data: res.result.InvRecordArr, invtotal: res.result.TotalInvCount, loading: false })
				} else {
					this.setState({ data: [], invtotal: 0, loading: false })

				}
			}
		})
	}

	//基础数据(账户预交金\住院押金)
	DepositQuery = () => {
		/**
		* @ByShizi: 分页异常处理
		* 需求 #1245
		* Create 2023-05-15
		* */
		this.setState({ loading2: true });
		let { page2, pageSize2 } = this.state;
		let data = {}
		data = {
			params: [{
				"startDate": this.state.INVReportsArr ? moment(this.state.INVReportsArr).utcOffset(480).format('YYYY-MM-DD HH:mm:ss') : '',
				"stopDate": this.state.stopDateTime,
				"userID": JSON.parse(window.sessionStorage.userData).userID,
				"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				"reportsID": this.state.userInfo.ID || '',
			}],
			pagination: [{
				pageSize: pageSize2,
				currentPage: page2,
				sortColumn: 'code',
				sortOrder: 'asc'
			}]
		}
		$http.post('urlDeanlt', this, {
			code: '05100192',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for (var i = 0; i < res.result.length; i++) {
						res.result[i].key = i;
					}
					this.setState({ Topdata: res.result.DepositArr, deptotal: res.result.TotalDepCount, loading2: false })
				} else {
					this.setState({ Topdata: [], deptotal: 0, loading2: false })
				}
			},
			error: function () {
				this.setState({ loading2: false })
			}
		})
	}

	/**
	* @ByShizi: 单击结账 - 结账防抖，避免多次触发
	* Create 2022-11-18
	* */
	handInvoicing = Util.debounce(() => {
		let data = {
			params: [{
				"startDate": this.state.INVReportsArr ? moment(this.state.INVReportsArr).utcOffset(480).format('YYYY-MM-DD HH:mm:ss') : '',
				"stopDate": this.state.stopDateTime,
				"userID": JSON.parse(window.sessionStorage.userData).userID,
				"hospID": JSON.parse(window.sessionStorage.userData).hospID,
			}]
		}
		$http.post('urls', this, {
			code: '05100145',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success("结账成功！")
					this.getStartDate()
					this.setState({ ReportID: res.ReportID }, () => { this.PrintReport() })
				}
			}
		})
	})

	// 撤销结账
	revokeFoot = () => {
		let data = {
			params: [{
				type: 'I'
			}]
		}
		$http.post('urls', this, {
			code: '05100356',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success("撤销结账成功！")
					this.invRecordQuery()
					this.DepositQuery()
					this.getStartDate()
				}
			}
		})
	}

	// 挂号收费显示分页总条数
	showinvTotal(invtotal) {
		return `共 ${invtotal} 条`;
	}

	// 充值显示分页总条数
	showdepTotal(deptotal) {
		return `共 ${deptotal} 条`;
	}

	// 页码改变的回调，参数是改变后的页码及每页条数
	appPageChange = (page, pageSize) => {
		this.setState({
			page: page,
			pageSize: pageSize,
		}, () => {
			// 重新调用查询方法
			this.invRecordQuery()
		});
	}

	// 条数改变的回调
	apponShowSizeChange = (current, size) => {
		this.setState({
			page: current,
			pageSize: size,
		}, () => {
			// 重新调用查询方法
			this.invRecordQuery()
		});
	}

	// 页码改变的回调，参数是改变后的页码及每页条数
	appPageChange2 = (page, pageSize) => {
		this.setState({
			page2: page,
			pageSize2: pageSize,
		}, () => {
			// 重新调用查询方法
			this.DepositQuery()
		});
	}

	// 条数改变的回调
	apponShowSizeChange2 = (current, size) => {
		this.setState({
			page2: current,
			pageSize2: size,
		}, () => {
			// 重新调用查询方法
			this.DepositQuery()
		});
	}
	onColumnRef = (ref) => {
		this.columnRef = ref;
	}

	PrintReport = () => {
		// if (this.state.userInfo.ID) {
		// 	let data = {}
		// 	data = {
		// 		params: [{
		// 			"ID": this.state.userInfo.ID,
		// 			"userID": JSON.parse(window.sessionStorage.userData).userID,
		// 		}]
		// 	}
		// 	$http.post('urls', this, {
		// 		code: '05100282',
		// 		data: data,
		// 		success: function (res) {
		// 			if (+res.errorCode === 0) {
		// 				$loopPrint('', res.result);
		// 			}
		// 		}
		// 	})
		// } else {
		// 	let data = {}
		// 	data = {
		// 		params: [{
		// 			"startDate": this.state.INVReportsArr ? moment(this.state.INVReportsArr).utcOffset(480).format('YYYY-MM-DD HH:mm:ss') : '',
		// 			"endDate": moment(moment().format('YYYY-MM-DD HH:mm:ss')).format('YYYY-MM-DD HH:mm:ss'),
		// 			"userID": JSON.parse(window.sessionStorage.userData).userID,
		// 			"hospID": JSON.parse(window.sessionStorage.userData).hospID,
		// 		}]
		// 	}
		// 	console.log(this.state.userInfo.stDateTime)
		// 	$http.post('urls', this, {
		// 		code: '05100283',
		// 		data: data,
		// 		success: function (res) {
		// 			if (+res.errorCode === 0) {
		// 				$loopPrint('', res.result);
		// 			}
		// 		}
		// 	})
		// }
		let data = {}
		data = {
			params: [{
				"startDate": this.state.INVReportsArr ? moment(this.state.INVReportsArr).utcOffset(480).format('YYYY-MM-DD HH:mm:ss') : '',
				"endDate": moment(moment().format('YYYY-MM-DD HH:mm:ss')).format('YYYY-MM-DD HH:mm:ss'),
				"userID": JSON.parse(window.sessionStorage.userData).userID,
				"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				"IDStr": this.state.userInfo.ID ? this.state.userInfo.ID : this.state.ReportID,
				"type": "I",
			}]
		}
		$http.post('urls', this, {
			code: '05100406',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					$loopPrint('', res.result);
				}
			}
		})
	}

	// 不可用日期
	disabledDate = (current) => {
		return current && (current > moment().endOf('day') || current < (this.state.userInfo.stDateTime ? moment(this.state.userInfo.stDateTime, 'YYYY-MM-DD HH:mm:ss') : moment(this.state.INVReportsArr, 'YYYY-MM-DD HH:mm:ss')));
	}

	// 更改日期
	onDateChange = (value, dateString) => {
		this.setState({ stopDateTime: dateString })
	}

	render() {
		let { language } = this.state
		return (
			<div style={{ width: '100%', height: '100%', background: '#F5F7FE' }} className='hosptial-adm-body'>
				<Card className="department-header" bodyStyle={{ padding: '10px' }}>
					<Col span={18} >
						{language.InvRecordHospitalClosingtimearea && language.InvRecordHospitalClosingtimearea.descripts}：<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="未获取到有效时间" value={this.state.userInfo.stDateTime ? moment(this.state.userInfo.stDateTime) : (this.state.INVReportsArr ? moment(this.state.INVReportsArr) : undefined)} disabled style={{ marginRight: '10px' }} />
						<DatePicker
							showTime
							format="YYYY-MM-DD HH:mm:ss"
							placeholder="End"
							value={this.state.stopDateTime === null ? moment(moment(), 'YYYY-MM-DD HH:mm:ss') : moment(this.state.stopDateTime, 'YYYY-MM-DD HH:mm:ss')}
							style={{ marginRight: '20px' }}
							disabledDate={this.disabledDate}
							onChange={this.onDateChange}
						/>
					</Col>
					<Col span={6} style={{ textAlign: 'right' }}>
						<Button style={{ marginRight: '20px' }} onClick={this.getStartDate}>{language.InvRecordHospitalInquire && language.InvRecordHospitalInquire.descripts}</Button>
						<Button style={{ marginRight: '20px' }} type="primary" onClick={this.handInvoicing} disabled={(Util.isEmpty(this.state.data) && Util.isEmpty(this.state.Topdata)) || this.props.flag === 'modal' ? true : false}>{language.InvRecordHospitalSettleaccounts && language.InvRecordHospitalSettleaccounts.descripts}</Button>
						{/* <Button style={{ marginRight: '20px' }} type="primary" onClick={this.revokeFoot} disabled={(Util.isEmpty(this.state.data) && Util.isEmpty(this.state.Topdata)) || this.props.flag === 'modal' || Util.isEmpty(this.state.lastINVReportsID) ? true : false}>{language.InvRecordHospitalRevokeFoot && language.InvRecordHospitalRevokeFoot.descripts}</Button> */}
						<Button onClick={this.PrintReport}>{language.InvRecordHospitalPrintthestatement && language.InvRecordHospitalPrintthestatement.descripts}</Button>
					</Col>
				</Card>

				<Card style={{ marginTop: 10 }} bodyStyle={{ padding: '10px' }}>
					<Tabs className="table-body-height">
						<TabPane tab={language.InvRecordHospitalCharge && language.InvRecordHospitalCharge.descripts} key="U">
							<Row>
								<Table
									style={{ height: store.getState().tableHeight.y + 55 + 'px' }}
									dataSource={this.state.data}
									columns={this.state.columns}
									className='TableA'
									pagination={false}
									scroll={{ x: 900, y: store.getState().tableHeight.y }}
									bordered
									loading={this.state.loading}
								/>
								<CommonPagination size="small" current={this.state.page} total={this.state.invtotal} search='search'
									onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.data}
									onChange={this.appPageChange} />
								<ColumnAuthoritysModel
									clientWidth='900px'
									compontName={this.state.ColumnAuthority}
									configType="C"
									onRef={this.onColumnRef}
									reloadData={() => this.tableList("InvRecordHospital", this.state.ColumnAuthority)}
								/>
							</Row>
						</TabPane>
						<TabPane tab={language.InvRecordHospitalDeposit && language.InvRecordHospitalDeposit.descripts} key="I">
							<Row>
								<Table
									style={{ height: store.getState().tableHeight.y + 55 + 'px' }}
									dataSource={this.state.Topdata}
									columns={this.state.columns2}
									className='TableA'
									pagination={false}
									scroll={{ x: 900, y: store.getState().tableHeight.y }}
									bordered
									loading={this.state.loading2}
								/>
								<CommonPagination size="small" current={this.state.page2} total={this.state.deptotal} search='search'
									onShowSizeChange={this.apponShowSizeChange2} complete={true} dataSource={this.state.Topdata}
									onChange={this.appPageChange2} />
							</Row>
						</TabPane>
					</Tabs>
				</Card>
			</div>
		)
	}
}