//门诊收费员个人结账
import React from 'react';
import { DatePicker, Table, Button, Tabs, Row, Col, 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';
const { TabPane } = Tabs;

export default class InvRecordDeposit extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			data: [],
			Topdata: [],
			INVReportsArr: undefined,
			userInfo: {},
			showLoading: true,
			invtotal: 0,
			deptotal: 0,
			page: 1,
			pageSize: 20,
			page2: 1,
			pageSize2: 20,
			InvRecordcolumns: [],
			Depositcolumns: [],
			languageTable1: {}, // 国际化Table1
			languageTable2: {}, // 国际化Table2
			languageData: {}, // 国际化语言包
			language: {},   // 国际化语言
			languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
			stopDateTime: moment().format('YYYY-MM-DD HH:mm:ss'),
			ReportID: ''
		}
		/*this.InvRecordcolumns = [
				{
						title: '发票号',
						dataIndex: 'invNo',
						width: '100px',
						align: 'center'
				},
				{
						title: '时间',
						dataIndex: 'payDate',
						width: '100px',
						align: 'center',
						render: (text, record) => (
								<span>
										{record.payDate}&nbsp;&nbsp;{record.payTime}
								</span>
						)
				},
				{
						title: '病人ID',
						dataIndex: 'patNo',
						width: '100px',
						align: 'center'
				},
				{
						title: '病人姓名',
						dataIndex: 'patName',
						width: '100px',
						align: 'center'
				},
				{
						title: '金额',
						dataIndex: 'totalAmt',
						width: '100px',
						align: 'center'
				},
				{
						title: '支付方式',
						dataIndex: 'payInvAmt',
						width: '100px',
						align: 'center'
				},
				{
						title: '优惠金额',
						dataIndex: 'discountAmt',
						width: '100px',
						align: 'center'
				},
				{
						title: '状态',
						dataIndex: 'statusDesc',
						width: '100px',
						align: 'center'
				},
		]
this.Depositcolumns = [
		{
				title: '交易时间',
				dataIndex: 'payDate',
				width: '100px',
				align: 'center',
				render: (text, record) => (
						<span>
								{record.payDate}&nbsp;&nbsp;{record.payTime}
						</span>
				)
		},
		{
				title: '病人ID',
				dataIndex: 'patNo',
				width: '100px',
				align: 'center'
		},
		{
				title: '病人卡号',
				dataIndex: 'patcardNo',
				width: '100px',
				align: 'center'
		},
		{
				title: '姓名',
				dataIndex: 'patName',
				width: '100px',
				align: 'center'
		},
		{
				title: '性别',
				dataIndex: 'patSexID',
				width: '100px',
				align: 'center'
		},
		{
				title: '操作员',
				dataIndex: 'payUserID',
				width: '100px',
				align: 'center'
		},
		{
				title: '交易方式',
				dataIndex: 'payModeID',
				width: '100px',
				align: 'center'
		},
		{
				title: '交易类型',
				dataIndex: 'paymentType',
				width: '100px',
				align: 'center'
		},
		{
				title: '金额',
				dataIndex: 'payAmt',
				width: '100px',
				align: 'center'
		},
]*/
	}

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

	// 获取主列表columns收费
	tableList = () => {
		var data = {
			params: [{
				"reactCode": ["InvRecordDeposit"],
				"compontName": "InvRecordDeposit",
				"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.columnRef1.onOpenModel()}>{item.title}</div>,
							display: item.display,
							key: item.seqNo
						}
					}) : '';
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
					this.setState({
						InvRecordcolumns: filterArr,
						languageTable1: res.result.B || {},  // 国际化Table1
						languageTable2: res.result.C || {},  // 国际化Table2
						languageData: res.result.language || {},  // 国际化语言包
					}, () => {
						this.LanCNEN(this.state.languageCode)
					})
				}
			}
		})
	}

	// 获取主列表columns押金
	tableList2 = () => {
		var data = {
			params: [{
				"reactCode": ["InvRecordDeposit"],
				"compontName": "InvRecordDepositlist",
				"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.columnRef2.onOpenModel()}>{item.title}</div>,
							display: item.display,
							key: item.seqNo
						}
					}) : '';
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
					this.setState({
						Depositcolumns: 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": "U"
			}],
		};
		$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: '05100101',
			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 = () => {
		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: '05100178',
			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, loading: false })
				} else {
					this.setState({ Topdata: [], deptotal: 0, loading: 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: '05100128',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success("结账成功！")
					this.invRecordQuery()
					this.DepositQuery()
					this.getStartDate()
					this.setState({ ReportID: res.ReportID }, () => { this.PrintReportByLodop() })
					//this.PrintReport(); // 打印结账单
				}
			}
		})
	})

	// 撤销结账
	revokeFoot = () => {
		let data = {
			params: [{ type: 'U' }]
		}
		$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: 1,
			pageSize2: size,
		}, () => {
			// 重新调用查询方法
			this.DepositQuery()
		});
	}

	onColumnRef1 = (ref) => {
		this.columnRef1 = ref;
	}

	onColumnRef2 = (ref) => {
		this.columnRef2 = ref;
	}

	/**
	 * 注释：
	 * @ByGJG lodop打印
	 * Create 2022-3-28
	 */
	PrintReportByLodop = () => {
		let data = {
			params: [{
				"startDate": this.state.INVReportsArr ? moment(this.state.INVReportsArr).utcOffset(480).format('YYYY-MM-DD HH:mm:ss') : '',
				"endDate": this.state.stopDateTime,
				"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": "O",
			}]
		}
		$http.post('urls', this, {
			code: '05100406',
			data: data,
			success: function (res) {
				$loopPrint('', res.result);
			}
		})
	}

	printData = () => {
		let data = {
			params: [{
				"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				"userID": JSON.parse(window.sessionStorage.userData).userID,
				"ID": this.props.userInfo.ID,
				"startDate": this.state.StartDate || '',
				"endDate": this.state.EndDate || '',
			}]
		}
		$http.post('urls', this, {
			code: '05100359',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					window.open(res.result);
				}
			}
		})
	}

	PrintReport = () => {
		if (this.state.ReportID || this.state.userInfo.ID) {
			//window.open("http://10.17.100.88:18080/demo/reportJsp/showReport.jsp?rpx=BaoAnOutpatientPersonal.rpx&ID=" + this.state.userInfo.ID + "&userID=" + JSON.parse(window.sessionStorage.userData).userID)
			//window.open("http://192.168.5.36:18080/demo/reportJsp/showReport.jsp?rpx=OutpatientPersonal.rpx&arg=" + this.state.userInfo.ID + "&userID=" + JSON.parse(window.sessionStorage.userData).userID)
			let data = {}
			data = {
				params: [{
					"ID": this.state.userInfo.ID ? this.state.userInfo.ID : this.state.ReportID,
					"userID": JSON.parse(window.sessionStorage.userData).userID,
					"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				}]
			}
			$http.post('urls', this, {
				code: '05100336',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						window.open(res.result);
					}
				}
			})
		} else {
			//window.open("http://10.17.100.88:18080/demo/reportJsp/showReport.jsp?rpx=BaoAnOutpatientPersonalTime.rpx&userID=" + JSON.parse(window.sessionStorage.userData).userID + "&hospID=" + JSON.parse(window.sessionStorage.userData).hospID + "&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'))
			let data = {}
			data = {
				params: [{
					"startDate": this.state.INVReportsArr ? moment(this.state.INVReportsArr).utcOffset(480).format('YYYY-MM-DD HH:mm:ss') : '',
					"endDate": this.state.stopDateTime,
					"userID": JSON.parse(window.sessionStorage.userData).userID,
					"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				}]
			}
			$http.post('urls', this, {
				code: '05100336',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						window.open(res.result);
					}
				}
			})
		}
	}

	PrintChargeReport = () => {
		//window.open("http://192.168.5.36:18080/demo/reportJsp/showReport.jsp?rpx=OutpatientCharge.rpx&arg=" + this.state.userInfo.ID + "&userID=" + JSON.parse(window.sessionStorage.userData).userID)
		let data = {}
		data = {
			params: [{
				"userID": JSON.parse(window.sessionStorage.userData).userID,
				"hospID": JSON.parse(window.sessionStorage.userData).hospID,
				"ID": this.state.userInfo.ID,
			}]
		}
		console.log(this.state.userInfo.stDateTime)
		$http.post('urls', this, {
			code: '05100281',
			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
		let session = JSON.parse(window.sessionStorage.userData)
		return (
			<div style={{ width: '100%', height: '100%' }}>
				<div className="department-header">
					<Row style={{ minHeight: '80px', padding: '0 24px' }}>
						<Col span={18} style={{ marginTop: '24px' }}>
							{language.InvRecordDepositClosingtimearea && language.InvRecordDepositClosingtimearea.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}
							/>
							<Button onClick={this.getStartDate} disabled={this.props.flag === 'modal' ? true : false}>{language.InvRecordDepositInquire && language.InvRecordDepositInquire.descripts}</Button>
						</Col>
						<Col span={6} style={{ textAlign: 'right', marginTop: '24px' }}>
							<Button style={{ marginRight: '20px' }} type="primary" onClick={this.handInvoicing} disabled={(Util.isEmpty(this.state.data) && Util.isEmpty(this.state.Topdata) && session.hospCode != 'H23') || this.props.flag === 'modal' ? true : false}>{language.InvRecordDepositSettleaccounts && language.InvRecordDepositSettleaccounts.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.InvRecordDepositRevokeFoot && language.InvRecordDepositRevokeFoot.descripts}</Button> */}
							<Button onClick={this.PrintReportByLodop} type="primary" ghost>{language.InvRecordDepositPrintthestatement && language.InvRecordDepositPrintthestatement.descripts}</Button>
							{/* <Button disabled={this.state.userInfo.ID ? false : true} onClick={this.PrintChargeReport}>充值结账单</Button> */}
						</Col>
					</Row>
				</div>
				<div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
				<div style={{ padding: 12 }} className="table-body-height">
					<Tabs>
						<TabPane tab={language.InvRecordDepositRegistration && language.InvRecordDepositRegistration.descripts} key="U">
							<Row>
								<Table
									style={{ height: store.getState().tableHeight.y + 30 + 'px' }}
									dataSource={this.state.data}
									columns={this.state.InvRecordcolumns}
									pagination={false}
									scroll={{ x: 900, y: store.getState().tableHeight.y - 20 }}
									bordered
									loading={this.state.loading}
								/>
								<CommonPagination
									pageSize="20"
									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='InvRecordDeposit'
									configType="C"
									onRef={this.onColumnRef1}
									reloadData={this.tableList}
								/>
							</Row>
						</TabPane>
						<TabPane tab={language.InvRecordDepositRecharge && language.InvRecordDepositRecharge.descripts} key="I">
							<Row>
								<Table
									style={{ height: store.getState().tableHeight.y + 30 + 'px' }}
									dataSource={this.state.Topdata}
									columns={this.state.Depositcolumns}
									pagination={false}
									scroll={{ x: 900, y: store.getState().tableHeight.y - 20 }}
									bordered
									loading={this.state.loading}
								/>
								<CommonPagination
									pageSize="20"
									size="small"
									current={this.state.page2}
									total={this.state.deptotal}
									search='search'
									onShowSizeChange={this.apponShowSizeChange2}
									complete={true}
									dataSource={this.state.Topdata}
									onChange={this.appPageChange2}
								/>
								<ColumnAuthoritysModel
									clientWidth='900px'
									compontName='InvRecordDepositlist'
									configType="C"
									onRef={this.onColumnRef2}
									reloadData={this.tableList2}
								/>
							</Row>
						</TabPane>
					</Tabs>
				</div>
			</div>
		)
	}
}