/**
 * 移动护理权限审核 | 移动护理记录
 * creator:JYW
 * date:2020-11-27
 */
import React from 'react';
import { Row, Col, Button, Card, Tabs, Spin, Progress, Modal, message } from 'antd';
import { $http } from '../../../containers/config/https';
import { getLodop } from '../../lodop/Common/LodopFuncs.js';
import { $fastReportTemplate } from '../../lodop/Common/FastReportPrint.js';
import { Util, dayFormat } from 'tools/index';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx';
import TipHeader from 'pages/Cashier/charges/component/TipHeader';
import store from 'store';
import PatientList from '../Patient/PatientList';
import moment from 'moment';
import RangeDatePicker from 'components/rangePicker/index';
import PublicModalQueryTable from 'pages/common/PublicModalQueryTable';
import 'pages/Cashier/charges/style/style.less';
import './style/index.less'; //引入样式
const { TabPane } = Tabs;
let user;

class NurseEmrRecord extends React.Component {
	constructor({ history }) {
		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		var patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
		var date = new Date();
		super();
		this.history = history;
		this.state = {
			iconType: 'double-left',
			leftspan: 5,
			rightspan: 19,
			userInfo: {},
			patient: [],
			selectPatient: {},
			templateList: [], //模板列表
			patientData: patientData,
			columns: {}, //表格数据列头
			dataSource: [], //表格数据
			total: 0,
			page: 1,
			pageSize: 20,
			emrRecordID: '',
			activeKey: '0',
			iEMRTemplateflag: '',
			endColumns: [
				{
					title: '时间',
					dataIndex: 'creatDateTime',
					key: 'creatDateTime',
					align: 'left',
					width: '140px'
				},
				{
					title: '填写人',
					dataIndex: 'creatUserName',
					key: 'creatUserName',
					align: 'left',
					width: '140px'
				}
			],
			admDateFrom: moment().subtract(14, 'days').format(dayFormat),
			admDateTo: moment(date).format(dayFormat),
			successCount: 0,
			errorCount: 0,
			fullLoading: false,
			percentCount: 0,
			patActiveKey: '1', // 患者列表单选|多选
			printSource: [], // 一键打印数据源
			printTip: ''
		};
	}

	componentDidMount() {
		this.getTemplateList();
		this.onClickRowPublicTop({});
		// 数据加载成功关闭loading
		if (this.child) this.child.handleLoading();
	}

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

	updateState = (state) => {
		console.log('state', state)
		if (state && 'activeKey' in state && state.activeKey) {
			this.setState({ patActiveKey: state?.activeKey || '1' });
		} else {
			this.setState(state, () => {
				if (this.state.selectPatient.patNo) {
					this.onClickRowPublicTop(this.state.selectPatient);
					this.getTemplateList();
				}
			});
		}
	};

	onClickRowPublicTop = (record) => {
		if (!record.patNo && !this.state.patientData.patID) {
			return;
		}
		var data = {
			params: [
				{
					number: record.patNo || this.state.patientData.patID, // 登记号/身份证号
					cardTypeID: '', //卡类型id
					cardNo: '' //卡号
				}
			]
		};
		$http.post('urlS', this, {
			code: '03040004',
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					this.setState({
						userInfo: res.data || [] // 用户数据
					});
				}
			}
		});
	};

	//获取模板
	getTemplateList = () => {
		var that = this;
		let data = {
			params: [
				{
					hospID: user.hospID,
					admID: that.state.selectPatient.admID || that.state.patientData.admID,
					useFlag: 'N'
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '10020001',
			data: data,
			success: function (res) {
				let activeKey = that.state.activeKey;
				if (res.result.TemplateList.length > 0 && activeKey == 0) {
					activeKey = res.result.TemplateList[0].id;
					if (!that.state.columns[activeKey]) {
						this.getTemplateColumns(res.result.TemplateList[0].id);
						this.getTemplateData(res.result.TemplateList[0].id);
					} else {
						this.getTemplateData(that.state.activeKey);
					}
				} else {
					this.getTemplateData(that.state.activeKey);
				}
				that.setState(
					{
						templateList: res.result.TemplateList,
						activeKey: activeKey,
						iEMRTemplateflag: res.result.iEMRTemplateflag
					},
					() => {
						that.child.handleLoading();
					}
				);
			}
		});
	};

	//获取列头
	getTemplateColumns = (id) => {
		let that = this;
		$http.post('urlDeault', this, {
			code: '10020015',
			data: {
				params: [
					{
						IEMRTemplateID: id
					}
				]
			},
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode == '0') {
					var columnsArr = [];
					for (var i = 0; i < res.result.length; i++) {
						var data = res.result;
						let column = {
							title: data[i].IEMRTempElementDesc,
							dataIndex: data[i].IEMRTempElementCode,
							key: data[i].IEMRTempElementCode,
							align: 'left',
							width: '120px'
						};
						columnsArr.push(column);
					}
					columnsArr = that.state.endColumns.concat(columnsArr);
					let columns = that.state.columns;
					if (!columns[id]) {
						columns[id] = columnsArr;
					}
					that.setState({
						columns: columns
					});
				}
			}
		});
	};

	/**
	 * 获取模板数据
	 * @param {模板ID} templateID  
	 */
	getTemplateData = (templateID) => {
		let that = this;
		$http.post('urlDeault', this, {
			code: '04220014',
			data: {
				params: [
					{
						templateID: templateID,
						admID: that.state.selectPatient.admID || that.state.patientData.admID,
						startDate: this.state.admDateFrom,
						endDate: this.state.admDateTo
					}
				],
				pagination: [
					{
						pageSize: this.state.pageSize,
						currentPage: this.state.page
					}
				]
			},
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode == '0') {
					that.setState({
						dataSource: res.result,
						total: res.total
					});
				}
			}
		});
	};

	setRowClassNamePublic2 = (record) => { };

	//点击tab页签
	onTabChange = (tab) => {
		this.setState(
			{
				activeKey: tab
			},
			() => {
				this.child.handleLoading();
				if (!this.state.columns[tab]) {
					this.getTemplateColumns(tab);
				}
				this.getTemplateData(tab);
			}
		);
	};

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

	// 操作行
	onClickRowPublic1 = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				this.setState({ emrRecordID: record.id }, () => {
					//this.dataTable2Data();
				});
			}
		};
	};

	// 选中行操作
	setRowClassNamePublic1 = (record) => {
		return record.id === this.state.emrRecordID ? 'clickRowStyle' : '';
	};

	startChange(date) {
		this.setState({
			admDateFrom: date
		});
	}

	endChange(date) {
		this.setState({
			admDateTo: date
		});
	}

	/**
		 * 查询数据
		 */
	searchData = () => {
		this.getTemplateData(this.state.activeKey);
	};

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

	// otherData 为全部打印其他参数
	handlePrint = (templateID, index, resolve, reject, otherData = {}) => {
		/*
		if ((user.hospID == 25) || (user.hospID == 50) || (user.hospID == 52) || (user.hospID == 55) || (user.hospID == 62) || (user.hospID == 63) || (user.hospID == 64) || (user.hospID == 65) || (user.hospID == 66) || (user.hospID == 67) || (user.hospID == 68)|| (user.hospID == 57)) {
			this.handlePrintOLD()
		} else {
			this.handlePrintNew()
		}
		*/
		if (this.state.iEMRTemplateflag === 'Y') {
			this.handlePrintNew(templateID, index, resolve, reject, otherData)
		} else {
			this.handlePrintOLD(templateID, index, resolve, reject, otherData)
		}
	};

	handlePrintOLD = (templateID, index, resolve, reject, otherData = {}) => {
		let that = this;
		let data = {
			isTips: templateID ? 'N' : '',
			params: [{
				templateID: templateID || that.state.activeKey,
				admID: otherData?.admID || that.state.selectPatient?.admID || that.state.patientData?.admID || '',
				patID: otherData?.patID || that.state.selectPatient?.patID || that.state.patientData?.patID || '',
				hospID: otherData?.hospID || user?.hospID || ''
			}]
		};
		$http.post('urlS', this, {
			code: '04220015',
			data: data,
			success: function (res) {
				if (res.errorCode == '0') {
					//加载模板
					LODOP = getLodop();
					LODOP.PRINT_INIT(res.result.template); //打印初始化
					eval(res.result.data); //执行打印内容
					templateID && this.handleRecordUploadStatus(index, 'success', resolve, reject);
				} else {
					templateID && this.handleRecordUploadStatus(index, 'error', resolve, reject);
				}
			},
			error: function () {
				templateID && this.handleRecordUploadStatus(index, 'error', resolve, reject);
			}
		});
	};

	handlePrintNew = async (templateID, index, resolve, reject, otherData = {}) => {
		try {
			let that = this;
			let data = {
				isTips: templateID ? 'N' : '',
				params: [
					{
						templateID: templateID || that.state.activeKey,
						admID: otherData?.admID || that.state.selectPatient?.admID || that.state.patientData?.admID || '',
						patID: otherData?.patID || that.state.selectPatient?.patID || that.state.patientData?.patID || '',
						hospID: otherData?.hospID || user?.hospID || ''
					}
				]
			};
			let res = await React.$asyncPost(this, '04220020', data);
			if (res.errorCode == '0') {
				let result = res.result
				let data = result.data
				for (var i = 0; i < data.length; i++) {
					var dataResult = data[i];
					$fastReportTemplate(result.template, user.hospID, dataResult, '');
				}
				templateID && this.handleRecordUploadStatus(index, 'success', resolve, reject);
			} else {
				templateID && this.handleRecordUploadStatus(index, 'error', resolve, reject);
			}
		} catch (error) {
			templateID && this.handleRecordUploadStatus(index, 'error', resolve, reject);
		}
	};

	// 修改打印状态
	handleRecordUploadStatus = (index, type, resolve, reject) => {
		const { printSource, printTip } = this.state;
		if (type === 'success') {
			this.state.successCount = this.state.successCount + 1;
			resolve && resolve();
		} else {
			this.state.errorCount = this.state.errorCount + 1;
			resolve && resolve();
		}
		this.setState({ percentCount: (((index + 1) / printSource.length).toFixed(2)) * 100 }, () => {
			const { successCount } = this.state;
			if (printSource.length - 1 === index) {
				clearInterval(this.percentTimer);
				Modal.success({
					title: (printTip || '一键打印') + '完成',
					content: '成功了：' + successCount + '个。'
				});
				// 清除操作数据
				this.setState({ successCount: 0, errorCount: 0, fullLoading: false, percentCount: 100 })
			}
		});
	};

	// 批量一键打印
	handleBatchPrint = () => {
		const { selectPatient } = this.state;
		if (!(selectPatient?.admID)) {
			message.error('请选择需要操作患者！');
			return;
		}
		this.handleAllPrint([selectPatient?.admID || '']); // 走打印全部逻辑，传入当前选择的患者
		// let _this = this;
		// this.setState({ fullLoading: true, percentCount: 0, printSource: templateList, printTip: '一键打印' }, () => {
		// 	this.percentTimer = setInterval(() => {
		// 		this.setState({ percentCount: this.state.percentCount + 1 > 99 ? 99 : this.state.percentCount + 1 })
		// 	}, 1000);
		// 	async function run() {
		// 		for (let i = 0; i < templateList.length; i++) {
		// 			let IEMRTemplateID = templateList[i]?.IEMRTemplateID || ''
		// 			await _this.handleConfirmPrinting(IEMRTemplateID, i);
		// 		}
		// 	}
		// 	run().then((res) => {
		// 		console.log(res, '执行完成');
		// 	})
		// })
	}

	handleConfirmPrinting = async (templateID, index, otherData) => {
		let _this = this;
		await Promise.resolve(templateID, index);
		return await new Promise((resolve, reject) => {
			setTimeout(async () => {
				_this.handlePrint(templateID, index, resolve, reject, otherData)
			}, 300)
		});
	};

	// 打印全部
	handleAllPrint = async (admArr, type) => {
		try {
			if (!(admArr && admArr.length > 0)) {
				message.warning('请勾选患者打印全部！注：患者列表切换多选')
				return;
			}
			let data = {
				params: [{
					hospID: user?.hospID || '',
					admArr: admArr
				}]
			}
			let res = await React.$asyncPost(this, '04220023', data);
			console.log('res', res)
			let tableData = Util.addKeyValueToDataSource(res?.result || []);
			if (type === 'modal') {
				let selectedRowKeys = tableData && tableData.map(item => item.key);
				this.printConfirmRef && this.printConfirmRef.modifyVisible(true, {
					tableData,
					selectedRows: tableData,
					selectedRowKeys,
				});
			} else {
				this.handleConfirmAllPrint({ selectedRows: tableData }, '一键打印')
			}
		} catch (error) {
			console.log(error)
		}
	};

	// 确认全部打印
	handleConfirmAllPrint = (data, printTip = '打印全部') => {
		let selectedRows = data?.selectedRows || [];
		let printData = [];
		for (let i = 0; i < selectedRows.length; i++) {
			printData = printData.concat(selectedRows[i]?.tempPrintData || []);
		}
		if (!(printData && printData.length > 0)) {
			message.error('无打印数据！');
			return;
		}
		let _this = this;
		this.setState({ fullLoading: true, percentCount: 0, printSource: printData, printTip }, () => {
			this.percentTimer = setInterval(() => {
				this.setState({ percentCount: this.state.percentCount + 1 > 99 ? 99 : this.state.percentCount + 1 })
			}, 1000);
			async function run() {
				for (let i = 0; i < printData.length; i++) {
					let templateID = printData[i]?.templateID || '';
					await _this.handleConfirmPrinting(templateID, i, printData[i]);
				}
			}
			run().then((res) => {
				console.log(res, '执行完成');
			})
		})
	};

	render() {
		const { fullLoading, percentCount, patActiveKey, printTip, patient } = this.state;
		// 组件所需参数
		const param = {
			// 表头配置
			columns: this.state.columns[this.state.activeKey],
			// 表格数据
			data: this.state.dataSource,
			// 数据总条数
			total: this.state.total,
			// 数据页数
			page: this.state.page,
			// x: 1600,
			height: store.getState().tableHeight.y - 15,
			y: store.getState().tableHeight.y,
			x: 900,
			isOnRow: true,
			rowClassName: true
		};
		let TabPaneArr = [];
		this.state.templateList.map((item) => {
			TabPaneArr.push(
				<TabPane tab={item.IEMRTemplateDesc} key={item.id}>
					<div className="condition">
						<RangeDatePicker
							format="YYYY-MM-DD"
							label="时间:"
							labelwidth="50px"
							totalwidth="350"
							width="280px"
							float="left"
							startDate={this.state.admDateFrom}
							endDate={this.state.admDateTo}
							// defaultValue={[moment(this.state.defaultValueObj.stDate, dateFormat), moment(this.state.defaultValueObj.endDate, dateFormat)]}
							startChange={this.startChange.bind(this)}
							endChange={this.endChange.bind(this)}
						/>
						<Button type="primary" style={{ margin: '0 25px', width: 100 }} onClick={this.searchData}>
							查询
						</Button>
						<Button type="primary" style={{ margin: '0 25px', width: 100 }} onClick={() => this.handlePrint()}>
							打印
						</Button>
						<Button type="primary" style={{ margin: '0 25px', width: 100 }} onClick={this.handleBatchPrint}>
							一键打印
						</Button>
						<Button type="primary" style={{ margin: '0 25px', width: 100 }} onClick={() => this.handleAllPrint(patient, 'modal')}>
							打印全部
						</Button>
					</div>
					{this.state.activeKey == item.id ? (
						<PubilcTablePagination
							param={param}
							handelThis={this}
							onRef={this.onRef}
							onClickRowPublic={this.onClickRowPublic1}
							setRowClassNamePublic={this.setRowClassNamePublic1}
						/>
					) : (
						''
					)}
				</TabPane>
			);
		});
		return (
			<Spin
				indicator={null}
				spinning={fullLoading}
				wrapperClassName="nurse-emr-record-spin"
				tip={(
					<div style={{ textAlign: 'center' }}>
						<Progress style={{ width: '240px' }} percent={percentCount} />
						<div>
							{(printTip || '一键打印') + (percentCount === 100 ? '完成' : '中，请耐心等待…')}
						</div>
					</div>
				)}
			>
				<div style={{ width: '100%', height: '100%' }} className="mobile-care-form-record">
					<Row style={{ height: '100%', width: '100%', overflow: 'hidden' }}>
						<Col
							className={this.state.iconType == 'double-left' ? '' : 'visibleIcon'}
							span={this.state.leftspan}
							style={{
								border: this.state.iconType == 'double-left' ? '1px solid #cccccc' : '0px',
								height: '100%',
								overflowY: 'hidden',
								background: '#ffffff',
								boxSizing: 'border-box'
							}}
						>
							<PatientList
								type="radio"
								check="checkbox"
								activeKey={patActiveKey}
								updateState={this.updateState}
								iconType={this.state.iconType}
							/>
						</Col>
						<Col span={this.state.rightspan} style={{ border: '1px solid #cccccc', height: '100%' }}>
							<Row>
								<Col span={10}>
									<div>
										<TipHeader
											userInfo={this.state.userInfo}
											key={this.state.userInfo.patID + this.state.userInfo.accTSubID}
										/>
									</div>
								</Col>
								<Col span={14} className="otherInfo">
									<Row>
										<Col span={4} style={{ textAlign: 'center', background: '#F7FBFF' }}>
											<div className="payBox">
												<p className="p2" style={{ color: '#007AFF' }}>
													￥<span>{this.state.selectPatient.patBillTCAmt || '0'}</span>
												</p>
												<p>统筹金额</p>
											</div>
										</Col>
										<Col
											span={4}
											style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
										>
											<div className="payBox">
												<p className="p2" style={{ color: '#007AFF' }}>
													￥<span>{this.state.selectPatient.patBillAllowAmt || '0'}</span>
												</p>
												<p>优惠</p>
											</div>
										</Col>
										<Col
											span={4}
											style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
										>
											<div className="payBox">
												<p className="p2" style={{ color: '#007AFF' }}>
													￥<span>{this.state.selectPatient.patBillZFAmt || '0'}</span>
												</p>
												<p>个人自费</p>
											</div>
										</Col>
										<Col
											span={4}
											style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
										>
											<div className="payBox">
												<p className="p2" style={{ color: '#007AFF' }}>
													{/* accYJPayAmt */}
													{/* /**
												* @By zxz: 预交金没有值
												* Create 2022-06-20
												* */ }
													￥<span>{this.state.selectPatient.accDepositIP || '0'}</span>
												</p>
												<p>预交金</p>
											</div>
										</Col>
										<Col
											span={4}
											style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
										>
											<div className="payBox">
												<p className="p2" style={{ color: '#007AFF' }}>
													{/* opBalance */}
													{/* /**
												* @By zxz: 没有值
												* Create 2022-06-20
												* */ }
													￥<span>{this.state.selectPatient.purposeBlanceIP || '0'}</span>
												</p>
												<p>当前余额</p>
											</div>
										</Col>
									</Row>
								</Col>
							</Row>
							<Card style={{ height: store.getState().tableHeight.y + 135 + 'px', marginTop: 10 }}>
								<Tabs onChange={this.onTabChange} activeKey={this.state.activeKey}>
									{TabPaneArr}
								</Tabs>
							</Card>
						</Col>
					</Row>

					{/* 打印全部 */}
					<PublicModalQueryTable
						cancelText="关闭"
						okText="打印"
						title="打印全部"
						autoQueryFlag="N"
						width="42vw"
						doubleRecordFlag="N"
						idIndex="key"
						multipleFlag="Y"
						tableHeight={store.getState().tableHeight.y - 148}
						componentName="NurseEmrRecordAllPrintModal"
						onRef={ref => this.printConfirmRef = ref}
						handleOk={this.handleConfirmAllPrint}
					/>
				</div>
			</Spin>
		);
	}
}

export default NurseEmrRecord;
