// 病历信息
import React from 'react';
import {
	Tree, Input, Icon, Modal, Checkbox, message, Row, Col, Card, Popconfirm, Form, DatePicker, Button, Tooltip, Spin
} from 'antd';
// import _ from 'underscore'
import { $http } from 'containers/config/https';
import { Keup } from '../../../tools/index';
import { httpConfig } from 'containers/config/httpConfig';
import store from 'store';
import Moment from 'moment';
import { Util } from 'tools/index';
import "../../pharmacy/outpha/style/outpha.less";
import '../style/CMOrderSave.less';

import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import CaseInformationPageTabs from './CaseInformationPageTabs.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const { TreeNode } = Tree;
const { confirm } = Modal;
let timer = null;

class CaseInformationPage extends React.Component {
	constructor(props) {
		super(props)
		var userData = React.$getSessionData();
		var recordData = React.$getSessionData('patientData');
		var titleData = React.$getSessionData('titleData');
		this.state = {
			recordData,
			userData,
			titleData,
			expandedKeys: [],
			selectedKeys: [],
			treeSelectData: {},
			treeData: [],
			templateName: "",
			autoExpandParent: true,
			visible: false,
			modalTemplateData: [],
			oldModalTemplateData: [],
			modalRowData: {},
			isVResize: false,
			hNum: 100,
			vNum: 920,
			hNumLimit: 30,
			vNumLimit: 30,
			savedTemplatesData: [], // 已保存模板
			exampleVisible: false,
			tableData: [],
			columns: [],
			total: 0,
			page: 1,
			pageSize: 10,
			loading: false,
			showValidateResult: "show", // 是否显示错误下拉框
			templateValue: undefined,
			historyAdmID: "",
			spinLoading: false,
			loadingTitle: "",
			defaultMillisecond: 0, // 默认倒计时毫秒数
			isDeleteRecord: false, // 是否可以删除病历
			isUnlocking: true
		}
		this.resizeOffsetInfo = {
			clientTop: 0,
			clientLeft: 0
		}

		this.leftHeight = 0

		this.containerWidth = 0
	}

	componentDidMount() {
		let _this = this;
		this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
		this.initResizeInfo();
		this.getChineseAndEnglishData();
		this.props && this.props.onRef && this.props.onRef(this);
		// this.getSavedTemplatesData(); // 查询已保存病历列表
		// const throttled = _.throttle(() => {
		//   this.initResizeInfo()
		// }, 200)

		window.onresize = function () {
			setTimeout(function () {
				_this.initResizeInfo()
			}, 200);
		}
		this.getTreeData();
		this.insty() // 录入权限
	}

	static getDerivedStateFromProps(nextProps, prevState) {
		//该方法内禁止访问this
		if (nextProps.historyAdmID !== prevState.historyAdmID) {
			//通过对比nextProps和prevState，返回一个用于更新状态的对象
			return true
		}
		//不需要更新状态，返回null
		return null
	}

	componentDidUpdate(prevProps, prevState, snapshot) {
		// 做一些需要this.props的事
		if (this.props.historyAdmID && (this.props.historyAdmID !== this.state.historyAdmID) && this.props.isDidUpdate && this.props.isDidUpdate === "Y") {
			this.setState({ historyAdmID: this.props.historyAdmID }, () => {
				this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
				// this.getSavedTemplatesData(); // 查询已保存病历列表
				this.getTreeData();
				this.insty() // 录入权限
			})
		}
	}

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

	// 组件销毁时清除组件信息
	handleClearComponentInformation = () => {
		let { treeSelectData, modalRowData, selectedKeys, defaultMillisecond, recordData } = this.state;
		if (this.state.eMRRecordID && this.props.isOperable !== "Y") {
			this.jqAjax(this.state.eMRRecordID, (res) => {
				console.log(res)
			}) // 成功的回调
			// this.updateMedicalRecordLockStatus();
		}
		window.onresize = null;
		window.sessionStorage.setItem("showMessagePopUp", "Y");
		window.sessionStorage.setItem('outEMRDefaultTemplate', JSON.stringify({
			treeSelectData,
			modalRowData,
			selectedKeys,
			defaultMillisecond,
			admID: recordData && recordData.admID ? recordData.admID : ''
		})); // 保存当前加载的病历模板
		if (timer) {
			clearInterval(timer);
		}
	}

	// 同步请求 -- 解锁
	jqAjax = (eMRRecordID, success, error) => {
		if (window && window.$ && window.$.ajax) {
			let userData = React.$getSessionData();
			if (!(eMRRecordID && userData && userData.userID)) {
				return;
			}
			let url = httpConfig.ipDeault + httpConfig.urlAddress;
			let json = {
				params: [{
					patEMRRecordID: eMRRecordID,
				}]
			}
			let formData = Object.assign({}, json);
			let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : "");
			windowHost = windowHost + "/bdhealth/";
			// 判断是否是本地，如果是本地的话取https配置地址，线上则取地址栏地址 （内外网）
			url = windowHost && windowHost.indexOf("localhost") !== -1 ? url : windowHost;
			formData.code = "06050015";
			if (userData) {
				let ip = React.$getSessionData('ipConfig');
				formData.session = [{
					"userID": userData.userID || '',
					"locID": userData.locID || '',
					"groupID": userData.groupID || '',
					"hospID": userData.hospID || '',
					"sessionID": userData.sessionID || '',
					"hostName": ip?.hostName || '',
					"ipv4": ip?.ipv4 || '',
					"ipv6": ip?.ipv6 || '',
					"mac": ip?.mac || '',
				}]
			}
			window.$.ajax({
				type: 'post',                          //请求方式
				url,     //请求地址
				data: JSON.stringify(formData),                         //发送的数据，这里是json对象
				dataType: 'json',                      //数据类型
				// contentType: 'application/json;charset=utf-8',
				async: false,
				success: function (data) {
					success && success(data);
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					// console.log(XMLHttpRequest, textStatus, errorThrown)
					error && error(errorThrown);
				},
				headers: {
					'Accept': 'application/json',
					'Content-Type': 'application/json',
					"Authorization": httpConfig.authorizationToken,
					"Access-Control-Allow-Origin": httpConfig.ipDeault
				},
			});
		}
	}

	insty = () => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""), // 就诊记录主键
			}]
		}
		$http.post('urlDeault', this, {
			code: "03040038",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					if (res.hasDocFlag != 'Y') {
						let messageTime = this.state.userData && this.state.userData.messageTime ? this.state.userData.messageTime : 3;
						Keup.ModalMessage(messageTime, this, '未分配主管医师，禁止录入!', '自动关闭', 'destroy', '确定', 'error')
					}
				}
			}
		})
	}

	// 获取中英文数据
	getChineseAndEnglishData = () => {
		let { userData } = this.state;
		let data = {
			params: [{
				compontName: "CaseInformationPage",
				type: "C",
				reactCode: ['CaseInformationPage']
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					var totalWidth = 0;
					let arr = res.result.C && res.result.C.map((item, index) => {
						return {
							...item,
							key: index,
							widthNum: parseInt(item.width),
							title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
						}
					});
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
					let obj = {
						title: userData.language == 'EN' ? 'Operation' : '操作',
						key: 14,
						align: "center",
						width: '80px',
						fixed: "right",
						widthNum: 80,
						render: (text, record) => (
							<span>
								<Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
								<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
									<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
								</Popconfirm>
							</span>
						),
					};
					filterArr.push(obj);
					for (var i = 0; i < filterArr.length; i++) {
						totalWidth += filterArr[i].widthNum;
					}
					this.setState({
						columns: filterArr,
						totalWidth,
						localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
					})
				}
			}
		})
	}

	onMainColumnRef = ref => {
		this.mainColumnRef = ref;
	}

	//国际化
	setMessage = (name, message, defaultTitle) => {
		return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
	}

	handleDelete = record => {
		console.log(record)
	}

	// 获取板分组科室下默认模板
	getDefaultTemplate = () => {
		let { recordData, userData } = this.state;
		/**
		* @ByShizi: 离开病历界面暂存病历模板信息，回到直接加载离开时的模板
		* 需求 #611
		* Create 2022-08-10
		* */
		let defaultTemplate = sessionStorage.getItem('outEMRDefaultTemplate') && JSON.parse(sessionStorage.getItem('outEMRDefaultTemplate'));
		if (defaultTemplate && defaultTemplate.admID && (defaultTemplate.admID === recordData?.admID)) {
			this.setState({ ...defaultTemplate, spinLoading: true, loadingTitle: '病历模板加载中……' }, () => {
				this.handleLoadingMedicalRecords(defaultTemplate?.treeSelectData, defaultTemplate?.modalRowData, defaultTemplate?.modalRowData?.flag || '');
			})
		} else {
			let data = {
				params: [{
					admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""),
					admLanguage: userData && userData.admLanguage ? userData.admLanguage : "CN",
				}]
			}
			$http.post('urlS', this, {
				code: "06010094",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						let dataAry = res.result.dataAry;
						let defaultMillisecond = res.result && res.result.autoSaveTime ? Number(res.result.autoSaveTime) : 0;
						if (!(dataAry && dataAry.length > 0)) {
							this.setState({ defaultMillisecond })
							return;
						}
						let key = [];
						let treeSelectData = JSON.parse(JSON.stringify(dataAry[0]));
						treeSelectData.ID = treeSelectData.wTemplateCatID;
						/**
						 * @ByShizi: 已写过病历的话默认加载已写过的病历
						 * Create 2023-02-14
						 * */
						if (treeSelectData && 'patEMRRecordID' in treeSelectData && treeSelectData.patEMRRecordID) {
							key.push(treeSelectData.patEMRRecordID);
						} else {
							key.push(treeSelectData.wTemplateCatID);
						}
						this.setState({ selectedKeys: key, defaultMillisecond, spinLoading: true, loadingTitle: "病历模板加载中……" }, () => {
							let obj = JSON.parse(JSON.stringify(dataAry[0]));
							obj.ID = obj.templateID;
							obj.releaseVersion = obj.eMRReleaseVersion; // 版本号
							if (obj && 'patEMRRecordID' in obj && obj.patEMRRecordID) {
								obj.flag = 'patientRecords';
								this.handleLoadingMedicalRecords(treeSelectData, obj, 'patientRecords');
							} else {
								this.setState({ modalRowData: obj }, () => { // 加载病历模板
									this.getModalTemplateData(treeSelectData, "default");
								})
							}
						})
					}
				}
			})
		}
	}

	// 处理tree数据
	filterTreeData = (treeData, type) => {
		let data = treeData && treeData.map(item => {
			// 当为首程并且首程下存在病程时则首程的progressID就为病程ID;
			let progressID = item && item.subCatalog && item.subCatalog.length > 0 && item.subCatalog[0].treeType && item.subCatalog[0].treeType === 'PROGRESS' ? 'first' : '';
			return {
				title: item.descripts,
				key: item.ID,
				progressID: item && item.treeType && item.treeType === 'PROGRESS' ? item.ID : progressID,
				treeType: item && item.treeType ? item.treeType : (item && item.subCatalog ? 'CATALOG' : 'TEMPLATE'),
				...item,
				children: this.filterTreeData(item.subCatalog, type)
			}
		});
		return data;
	}

	// 3.6.1.根据患者获取病历模板分组目录树
	getTreeData = () => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""),
				wTempVer: "Y", // 是否查询导航目录模板版本信息
				patEMRRec: "Y", // 是否查询患者已填写病历信息
				locID: this.props && this.props.locID ? this.props.locID : "", // 患者病历预览界面专用 -- 科室ID
				fGroup: this.props && this.props.fGroup ? this.props.fGroup : "", // 患者病历预览界面专用 -- 职能科室
				fGroupTempByInfo: this.props && this.props.fGroupTempByInfo ? this.props.fGroupTempByInfo : "", // 患者病历预览界面专用
			}]
		}
		$http.post('urlS', this, {
			code: "06050006",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = this.filterTreeData(res.result);
					this.setState({ treeData: arr }, () => {
						this.generateList(this.state.treeData)
					})
				} else {
					this.setState({ treeData: [] })
				}
			}
		})
	}

	renderTreeNodes = data => data.map((item) => {
		const index = item.title.indexOf(this.state.templateName);
		const beforeStr = item.title.substr(0, index);
		const afterStr = item.title.substr(index + this.state.templateName.length);
		const title = index > -1 ? (
			<span>
				{beforeStr}
				<span style={{ color: '#FF7F00' }}>{this.state.templateName}</span>
				{afterStr}
			</span>
		) : <span>{item.title}</span>;
		let type = item.treeType === 'CATALOG' ? 'folder-open' : ((item.treeType === 'TEMPLATE' && !(item.progressID && item.progressID !== 'first')) ? 'folder' : 'file');
		if (item.children) {
			return (
				<TreeNode icon={<Icon type={type} />} title={<span onClick={() => this.handleAnchorPositioning(item)}>{title}</span>} key={item.key} dataRef={item}>
					{this.renderTreeNodes(item.children)}
				</TreeNode>
			);
		}
		return <TreeNode icon={<Icon type={type} />} title={<span onClick={() => this.handleAnchorPositioning(item)}>{title}</span>} key={item.key} dataRef={item} />;
	})

	// 锚点定位
	handleAnchorPositioning = item => {
		let recordID = 'record' + item.ID;
		if (item && item.treeType === 'PROGRESS') {
			this.caseTemplateChild && this.caseTemplateChild.handleAnchorPositioning(recordID);
		}
	}

	getParentKey = (key, tree) => {
		let parentKey;
		for (let i = 0; i < tree.length; i++) {
			const node = tree[i];
			if (node.children) {
				if (node.children.some(item => item.key === key)) {
					parentKey = node.key;
				} else if (this.getParentKey(key, node.children)) {
					parentKey = this.getParentKey(key, node.children);
				}
			}
		}
		return parentKey;
	};

	//以下是Tree展开搜索
	dataList = [];
	generateList = (data) => {
		for (let i = 0; i < data.length; i++) {
			const node = data[i];
			const key = node.key;
			this.dataList.push({ key, title: node.title });

			if (node.children) {
				this.generateList(node.children);
			}
		}
		// 默认进来tree全部加载
		const expandedKeys = this.dataList.map((item) => {
			return this.getParentKey(item.key, this.state.treeData);
		}).filter((item, i, self) => item && self.indexOf(item) === i);
		this.setState({
			expandedKeys,
		});
	};

	handleTemplateNameChange = e => {
		const templateName = e.target.value;
		const expandedKeys = this.dataList.map((item) => {
			if (templateName.length === 0) return null;
			if (item.title.indexOf(templateName) > -1) {
				return this.getParentKey(item.key, this.state.treeData);
			}
			return null;
		}).filter((item, i, self) => item && self.indexOf(item) === i);
		this.setState({
			expandedKeys,
			templateName: e.target.value,
			autoExpandParent: true,
		});
	}

	onExpand = (expandedKeys) => {
		this.setState({
			expandedKeys,
			autoExpandParent: false,
		});
	}

	// 病历模板树选中操作
	onSelect = (keys, event) => {
		// if (!(keys && keys.length > 0)) {
		// 	return;
		// }
		// this.setState({ selectedKeys: keys }, () => {
		// 	if (this.state.selectedKeys && this.state.selectedKeys.length > 0) {
		// 		this.setState({ treeSelectData: event.node.props.dataRef })
		// 	} else {
		// 		this.setState({ treeSelectData: {} })
		// 	}
		// })

		// let { spinLoading } = this.state;
		let { spinLoading } = this.state;
		let selectData = event.node.props.dataRef;
		let treeSelectData = JSON.parse(JSON.stringify(selectData));
		if (!(keys && keys.length > 0)) {
			return;
		}
		if ((selectData && !(selectData.treeType === "TEMPLATE" || (selectData.treeType === "CATALOG" && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
			return;
		}
		// let selectedKeys = []; // 关联选中病历模板
		// selectedKeys.push(treeSelectData.wTempCataID);
		this.setState({ selectedKeys: keys }, () => {
			treeSelectData.ID = treeSelectData.wTempCataID;
			selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
			if (this.state.selectedKeys && this.state.selectedKeys.length > 0 && selectData.treeType === "TEMPLATE") {
				this.getPatienHistoryData(treeSelectData, selectData, "patientRecords");
			} else if (this.state.selectedKeys && this.state.selectedKeys.length > 0 && selectData.treeType === "CATALOG" && selectData.parentID) {
				this.getModalTemplateData(selectData);
			}
		})
	}

	dblclickTreeNodes = (status, record) => {
		let { spinLoading } = this.state;
		let selectData = record.props.dataRef;
		if ((selectData && !(selectData.treeType === "TEMPLATE" || (selectData.treeType === "CATALOG" && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
			return;
		}
		let treeSelectData = JSON.parse(JSON.stringify(selectData));
		let ID = selectData && selectData.ID ? selectData.ID : "";
		let key = [];
		key.push(ID);
		this.setState({ selectedKeys: key }, () => {
			treeSelectData.ID = treeSelectData.wTempCataID;
			selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
			if (selectData && selectData.treeType === "TEMPLATE") {
				this.getPatienHistoryData(treeSelectData, selectData, "patientRecords");
			} else if (selectData && selectData.treeType === "CATALOG") {
				this.getModalTemplateData(selectData);
			}
		})
	}

	showModal = () => {
		this.setState({ visible: true });
	}

	handleOk = () => {
		let messageTrue = false;
		let obj = {};
		let modalTemplateData = JSON.parse(JSON.stringify(this.state.modalTemplateData));
		if (modalTemplateData && modalTemplateData.length > 0) {
			for (let i = 0; i < modalTemplateData.length; i++) {
				if (modalTemplateData[i].checked == true) {
					messageTrue = true
					obj = modalTemplateData[i];
					break;
				} else {
					messageTrue = false
				}
			}
		}
		// console.log(arr)
		if (messageTrue === false) {
			message.error("请选择模板", this.state.userData && this.state.userData.messageTime)
		} else {
			obj.isHanle = this.state.isHanle;
			let treeSelectData = JSON.parse(JSON.stringify(obj));
			treeSelectData.ID = treeSelectData.wTempCataID;
			this.setState({ rowId: "", }, () => {
				this.getPatienHistoryData(treeSelectData, obj, "cancel")
			})
		}
	}

	handleCancel = () => {
		this.setState({ visible: false, templateValue: undefined, spinLoading: false });
	}

	// 3.6.2.根据分组目录获取模板
	getModalTemplateData = Util.debounce((treeSelectData, isHanle) => {
		let { modalRowData, recordData } = this.state;
		let data = {
			params: [{
				groupTemplateID: treeSelectData.ID, // 分组目录ID - 导航目录ID
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""),
				locID: this.props && this.props.locID ? this.props.locID : "", // 患者病历预览界面专用 -- 科室ID
				fGroup: this.props && this.props.fGroup ? this.props.fGroup : "", // 患者病历预览界面专用 -- 职能科室
				fGroupTempByInfo: this.props && this.props.fGroupTempByInfo ? this.props.fGroupTempByInfo : "", // 患者病历预览界面专用
			}]
		}
		$http.post('urlS', this, {
			code: "06050007",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					for (var i = 0; i < res.result.length; i++) {
						if (res.result[i].ID === modalRowData.ID) {
							res.result[i].checked = true;
							modalRowData = res.result[i];
							break;
						}
					}
					let modalTemplateData = res.result.filter(function (item) { return item.releaseVersion });
					// let prSelectedKeys = []; // 患者病历选中操作
					// prSelectedKeys.push(modalRowData.ID)
					this.setState({ modalTemplateData, oldModalTemplateData: modalTemplateData, isHanle: isHanle ? isHanle : "" }, () => {
						if (this.state.isHanle !== "default") {
							if (this.state.modalTemplateData && this.state.modalTemplateData.length > 1) {
								this.showModal();
							} else {
								// 获取患者病历数据
								let obj = this.state.modalTemplateData && this.state.modalTemplateData.length > 0 ? this.state.modalTemplateData[0] : {};
								this.getPatienHistoryData(treeSelectData, obj, "loadTemplate")
							}
						} else {
							// setTimeout(() => {
							// 	this.getPatienHistoryData(treeSelectData, { ...modalRowData, isHanle }, "loadTemplate")
							// }, 300)
							this.setState({ modalRowData }, () => {
								this.getPatienHistoryData(treeSelectData, { ...modalRowData, isHanle }, "loadTemplate")
							})
						}
					})
				} else {
					this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false });
				}
			},
			error: function () {
				this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false });
			}
		})
	})

	// 判断文件内容是否修改
	getModified = () => {
		let isModify = this.caseTemplateChild && this.caseTemplateChild.getModified ? this.caseTemplateChild.getModified() : false;
		return isModify
	}

	// 3.6.8.获取患者病历数据
	getPatienHistoryData = Util.debounce((treeSelectData, obj, flag) => {
		let oldModalRowData = this.state.modalRowData && this.state.modalRowData.ID ? JSON.parse(JSON.stringify(this.state.modalRowData)) : obj; // 历史选择的模板数据
		let isModify = this.getModified();
		let _this = this;
		if (obj.isHanle !== "default" && isModify) {
			confirm({
				title: <div>当前病历 <span style={{ fontWeight: "900" }}>{oldModalRowData.descripts}</span> 已修改，是否需要保存？</div>,
				// content: "当前显示的病历模板为：" + oldModalRowData.descripts,
				okText: "是->保存",
				cancelText: "否->无需保存",
				onOk() {
					// obj.load = true; // 是否加载切换的病历模板
					// _this.handleSave(treeSelectData, obj);
					obj.load = true; // 是否加载切换的病历模板
					obj.flag = flag;
					obj.saveType = "auto";
					_this.setState({ spinLoading: true, loadingTitle: "保存中……" }, () => {
						_this.handleSave(treeSelectData, obj);
					})
				},
				onCancel() {
					_this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
				},
			});

			if (flag === "cancel") {
				this.handleCancel();
			}
		} else {
			_this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
		}
	})

	// 加载病历 - 已写过的病历
	newLoadingMedicalRecords = (treeSelectData, obj, flag) => {
		let { recordData, titleData } = this.state;
		// console.log("oldEMRRecordID", oldModalRowData, oldEMRRecordID);
		let data = {
			params: [{
				patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""),
				// catalogueID: treeSelectData.ID, // 分组目录ID
				// groupTemplateID: obj.ID, // 分组模板ID
				power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ""
			}]
		}
		$http.post('urlS', this, {
			code: "06050008",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					// console.log(res.result) // eMRRecordID 
					let authority = res.result && res.result.authority ? res.result.authority : {};
					let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === "Y" || authority.updateOrNot === "Y")) ? "N" : "Y"); // 是否可操作
					// let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? "N" : "Y") : "N"); // 是否可操作
					obj.flag = flag; // 保存调用类型
					obj.removeLockFlag = authority.removeLockFlag;
					let progressID = obj && obj.progressID ? obj.progressID : ""; // 病程记录ID
					let needUpdateData = res.result && res.result.needUpdateData && res.result.needUpdateData.length ? res.result.needUpdateData : [];
					for (var i = 0; i < needUpdateData.length; i++) {
						needUpdateData[i].key = i + 1;
					}
					this.setState({ // recordDataID -- 病历记录数据ID
						templatePath: res.result && res.result.templatePath ? res.result.templatePath : '', eMRRecordID: res.result.eMRRecordID, treeSelectData,
						modalRowData: obj, spinLoading: false, isUnlocking: this.props.isOperable === "Y" ? true : false, recordDataID: res.result && res.result.recordDataID ? res.result.recordDataID : ""
					}, () => {
						this.state.templatePath ? this.caseTemplateChild?.setElementTextByID(
							this.state.templatePath,
							res.result.dataSource,
							isOperable, "boolFalse",
							titleData && titleData.patSexDesc ? titleData.patSexDesc : "",
							{ ...obj, releaseVersion: obj.releaseVersion },
							obj.templateID,
							progressID,
							needUpdateData
						) : this.caseTemplateChild?.NewFile();
						if (flag === "cancel") {
							this.handleCancel();
						}
						// console.log("oldModalRowData", oldModalRowData, obj)
						// if (obj && obj.isHanle !== "default" && oldModalRowData && oldModalRowData.removeLockFlag === "Y") {
						// 	this.updateMedicalRecordLockStatus(oldModalRowData && oldModalRowData.BSEMRRDParRef ? oldModalRowData.BSEMRRDParRef : oldEMRRecordID); // 解锁
						// }
						authority && authority.noChangeTip ? message.info(authority.noChangeTip) : "";
						// if (isOperable === "N" && this.props && this.props.caseInformationPageTabs !== "N") { // 定时保存病历
						// 	if (timer) {
						// 		clearInterval(timer);
						// 	}
						// 	timer = setInterval(() => {
						// 		this.savePatientMedicalRecord("newLoadingMedicalRecords");
						// 	}, defaultMillisecond ? (defaultMillisecond * 1000) : (60 * 1000)) // 默认一分钟保存一次
						// }
					})
				} else {
					this.setState({ patienHistoryData: [], spinLoading: false })
				}
			},
			error: function () {
				this.setState({ patienHistoryData: [], spinLoading: false })
			}
		})
	}

	handleCaseTemplateRef = ref => {
		this.caseTemplateChild = ref
	}

	// Checkbox的onChange事件
	compileChecked = (item, index, isOK) => {
		let modalTemplateData = [...this.state.modalTemplateData];
		for (var i = 0; i < modalTemplateData.length; i++) {
			let indexChecked = modalTemplateData[index].checked;
			modalTemplateData[i].checked = false;
			modalTemplateData[index].checked = indexChecked;
			if (modalTemplateData[i] === item) {
				modalTemplateData[i].checked = !modalTemplateData[i].checked;
			}
		}
		this.setState({ modalTemplateData }, () => {
			if (isOK === "ok") {
				this.handleOk();
			}
		})
	}

	// 病历加载
	handleLoadingMedicalRecords = (treeSelectData, obj, flag) => {
		this.setState({ spinLoading: true, loadingTitle: "病历加载中……" }, () => {
			if (flag === "patientRecords") {
				// let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID; // 病程记录ID
				// if (obj && obj.addLockFlag === "N") { // 判断病历加载是否需要加锁操作
				this.setState({ isDeleteRecord: true }, () => { // 加载已保存的患者病历模板可以删除
					this.newLoadingMedicalRecords(treeSelectData, obj, flag);
				})
				// } else {
				// 	this.updateMedicalRecordLockStatus(eMRRecordID, treeSelectData, obj, flag);
				// }
			} else {
				this.SaveMedicalRecord(treeSelectData, obj, flag)
			}
		})
	}

	// 3.6.3.保存病历记录
	SaveMedicalRecord = Util.debounce((treeSelectData, obj, flag, selectionXml) => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""),
				cataLogID: treeSelectData.ID, // 分组模板目录ID
				seqNo: "",
				templateID: treeSelectData?.templateID || obj?.ID || '', // 病历模板ID
				sPatRecPower: flag === "courseOfDisease" ? "saveEMRProgress" : undefined
			}]
		}
		$http.post('urlS', this, {
			code: "06050001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let recordID = res && res.ID ? res.ID : "";
					obj.BSEMRRDParRef = recordID;
					if (flag === "courseOfDisease") {
						this.caseTemplateChild && this.caseTemplateChild.insertTheCourseOfDisease && this.caseTemplateChild.insertTheCourseOfDisease(selectionXml, recordID, obj)
					} else if (flag === "sampleDirectory") { // 加载范例病历
						this.setState({ isDeleteRecord: false }, () => {
							this.handleLoadSampleMedicalRecord(treeSelectData, obj, flag)
						})
					} else if (flag === "loadTemplate" || flag === "cancel") { // 加载病历模板
						this.setState({ isDeleteRecord: false }, () => { // 加载的病历模板不能删除
							this.handleLoadingMedicalRecordTemplate(treeSelectData, obj, flag)
						})
					} else {
						this.setState({ isDeleteRecord: true }, () => { // 加载已保存的患者病历模板可以删除
							this.newLoadingMedicalRecords(treeSelectData, obj, flag);
						})
					}
				} else {
					this.caseTemplateChild && this.caseTemplateChild.clearCourseOfDiseaseLoading && this.caseTemplateChild.clearCourseOfDiseaseLoading();
					this.setState({ spinLoading: false });
				}
			},
			error: function () {
				this.caseTemplateChild && this.caseTemplateChild.clearCourseOfDiseaseLoading && this.caseTemplateChild.clearCourseOfDiseaseLoading();
				this.setState({ spinLoading: false });
			}
		})
	})

	// 加载病历模板
	handleLoadingMedicalRecordTemplate = (treeSelectData, obj, flag) => {
		let { recordData, titleData, eMRRecordID, defaultMillisecond, modalRowData } = this.state;
		let oldModalRowData = JSON.parse(JSON.stringify(modalRowData));
		let oldEMRRecordID = eMRRecordID;
		let data = {
			params: [{
				patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""),
				groupTemplateID: treeSelectData?.templateID || obj?.ID || '', // 分组模板ID
				power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ""
			}]
		}
		$http.post('urlS', this, {
			code: "06050016",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					// console.log(res.result) // eMRRecordID 
					let authority = res.result && res.result.authority ? res.result.authority : {};
					let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === "Y" || authority.updateOrNot === "Y")) ? "N" : "Y"); // 是否可操作
					// let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? "N" : "Y") : "N"); // 是否可操作
					obj.flag = flag; // 保存调用类型
					obj.removeLockFlag = authority.removeLockFlag;
					let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
					this.setState({
						templatePath: res.result && res.result.templatePath ? res.result.templatePath : '', eMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID, treeSelectData,
						modalRowData: obj, spinLoading: false, isUnlocking: true
					}, () => {
						this.state.templatePath ? this.caseTemplateChild.setElementTextByID(this.state.templatePath, res.result.dataSource, isOperable, "boolFalse", titleData && titleData.patSexDesc ? titleData.patSexDesc : "", { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID) : this.caseTemplateChild?.NewFile();
						if (flag === "cancel") {
							this.handleCancel();
						}
						// console.log("oldModalRowData", oldModalRowData, obj)
						// if (obj && obj.isHanle !== "default" && oldModalRowData && oldModalRowData.removeLockFlag === "Y") {
						// 	this.updateMedicalRecordLockStatus(oldModalRowData && oldModalRowData.BSEMRRDParRef ? oldModalRowData.BSEMRRDParRef : oldEMRRecordID); // 解锁
						// }
						authority && authority.noChangeTip ? message.info(authority.noChangeTip) : "";
						// if (isOperable === "N" && this.props && this.props.caseInformationPageTabs !== "N") { // 定时保存病历
						// 	if (timer) {
						// 		clearInterval(timer);
						// 	}
						// 	timer = setInterval(() => {
						// 		this.savePatientMedicalRecord("handleLoadingMedicalRecordTemplate");
						// 	}, defaultMillisecond ? (defaultMillisecond * 1000) : (60 * 1000)) // 默认一分钟保存一次
						// }
					})
				} else {
					this.setState({ patientHistoryData: [], spinLoading: false })
				}
			},
			error: function () {
				this.setState({ patientHistoryData: [], spinLoading: false })
			}
		})
	}

	// 3.6.5.保存患者病历数据
	savePatientMedicalRecord = (newWTreeSelectData, record, fn) => {
		let { modalRowData, treeSelectData, titleData } = this.state;
		let oldTreeSelectData = JSON.parse(JSON.stringify(treeSelectData));
		let templateData = this.caseTemplateChild.getTemplateXml("form");
		// console.log('titleData', titleData)
		// if (!(templateData && templateData.status)) { // 保存验证必填项只给提示，允许保存
		// 	return;
		// }
		let data = {
			params: [{
				queID: this.props.editorID === 'OSEWriterControl' ? (titleData?.queID || '') : undefined, // 队列ID
				areaRoomID: this.props.editorID === 'OSEWriterControl' ? (titleData?.areaRoomID || '') : undefined, // 诊室ID
				BSEMRRDParRef: modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID, // 病历记录ID
				recordData: templateData && templateData.xmlStr ? templateData.xmlStr : "", // 病历记录数据 --- 模板xml
				progressRecIDAry: templateData && templateData.allRecordID ? templateData.allRecordID : [], // 病历记录数据 --- 病程记录ID
				progressRecDataSource: templateData?.recordDataSource || [],
				submitOrNot: "N", // submitOrNot
				auditOrNot: "N", // 是否审核标志
				lockStatus: "Y", // 锁定标志
				archivingStatus: "U", // 归档标志
				wCatalogueID: oldTreeSelectData.ID, // 分组目录ID
				versionID: modalRowData && modalRowData.releaseVersion ? modalRowData.releaseVersion : "", // 病历模板ID
				patRecDataSource: this.caseTemplateChild && this.caseTemplateChild.getMedicalRecordFileIDAndValue && this.caseTemplateChild.getMedicalRecordFileIDAndValue(), // 病历所有的输入域以及对应的值
			}]
		}
		// console.log("data", data)
		$http.post('urlS', this, {
			code: "06050004",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ isHanle: "", spinLoading: false, recordDataID: res.result && res.result.recordDataID ? res.result.recordDataID : "" }); // recordDataID -- 病历记录数据ID
					// this.getSavedTemplatesData(); // 获取已保存病历
					this.getTreeData("patientRecords"); // 保存成功之后重新加载患者病历
					this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified("isModifyPermissions") : ""; // 保存成功后修改编辑状态
					if (newWTreeSelectData === "handleLoadingMedicalRecordTemplate" || newWTreeSelectData === "newLoadingMedicalRecords" || newWTreeSelectData === "handleLoadSampleMedicalRecord") { // 自动保存
						return;
					} // BSEMRRDParRef
					let key = [];
					key.push(modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID);
					// this.setState({ prSelectedKeys: key }, () => {
					this.setState({ isDeleteRecord: true }); // 保存之后可以删除
					message.success("保存成功", this.state.userData && this.state.userData.messageTime ? this.state.userData.messageTime : 3);
					if (newWTreeSelectData && newWTreeSelectData.ID) { // 判断是否自动保存的，
						this.setState({ treeSelectData: oldTreeSelectData });
					} else {
						this.setState({ prSelectedKeys: key })
					}
					if (record && record.load) { // 判断是否保存后需要加载新操作的模板，需要的话传入新模板数据
						this.handleLoadingMedicalRecords(newWTreeSelectData, record, record.flag);
					}
					if (fn) {
						fn();
					}
				} else {
					this.setState({ spinLoading: false });
					this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '';
				}
			},
			error: function () {
				this.setState({ spinLoading: false });
				this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '';
			}
		})
	}

	// 更新患者病历记录锁状态
	updateMedicalRecordLockStatus = Util.debounce((eMRRecordID, treeSelectData, obj, flag) => {
		let userData = React.$getSessionData();
		if (!(eMRRecordID && userData && userData.userID)) {
			if (!eMRRecordID) {
				// message.error("模板加载失败")
			}
			return;
		}
		let data = {
			// lockStatus为Y则为加锁
			params: [{
				patEMRRecordID: eMRRecordID,
				lockStatus: flag === "patientRecords" ? "Y" : undefined,
				uEMRRecLockPow: treeSelectData === "forceUnlock" ? "removeOtherLock" : undefined, // 强制解锁标志
			}]
		}
		$http.post('urlS', this, {
			code: "06050015",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					if (flag === "patientRecords") { // 加载患者病历
						this.setState({ isDeleteRecord: true }, () => { // 加载已保存的患者病历模板可以删除
							this.newLoadingMedicalRecords(treeSelectData, obj, flag);
						})
					}
					if (treeSelectData === "forceUnlock") { // 强制解锁
						let { modalRowData } = this.state;
						this.setState({ isDeleteRecord: false }, () => {
							this.getPatienHistoryData(this.state.treeSelectData, modalRowData, modalRowData && modalRowData.flag ? modalRowData.flag : "")
						})
					}
				}
			}
		})
	})

	// 保存
	handleSave = (treeSelectData, record, fn) => {
		if (record && record.saveType === "auto") { // 自动保存不需要加载loading提示
			this.savePatientMedicalRecord(treeSelectData, record, fn);
		} else {
			this.setState({ spinLoading: true, loadingTitle: "保存中" }, () => {
				// this.SaveMedicalRecord(treeSelectData, record, fn);
				this.savePatientMedicalRecord(treeSelectData, record, fn);
			})
		}

	}

	// 查看历史病历时将右侧宽度调宽
	compileVNum = (status) => {
		this.containerWidth = document.getElementById('v_resize_container').offsetWidth
		if (status === "default") {
			this.setState({
				vNum: 1000,
				vNumLimit: this.containerWidth - 1000,
				showValidateResult: "show"
			})
		} else {
			this.setState({
				vNum: this.containerWidth / 2 + 50,
				vNumLimit: this.containerWidth / 2 - 50,
				showValidateResult: "hidden"
			})
		}
	}

	/**
	 * 初始化resize信息
	 */
	initResizeInfo = () => {
		const hEle = document.getElementById('h_resize_container')
		this.resizeOffsetInfo = this.getEleOffset(hEle)
		this.leftHeight = hEle.offsetHeight
		this.containerWidth = document.getElementById('v_resize_container').offsetWidth

		if (hEle.offsetHeight - this.state.hNum < this.state.hNumLimit) {
			this.setState({
				hNum: hEle.offsetHeight - this.state.hNumLimit
			})
		}
		if (this.containerWidth - this.state.vNum < this.state.vNumLimit) {
			this.setState({
				vNum: this.containerWidth - this.state.vNumLimit,
			})
		}
	}

	/**
	 * 获取元素的偏移信息
	 */
	getEleOffset(ele) {
		var clientTop = ele.offsetTop
		var clientLeft = ele.offsetLeft
		let current = ele.offsetParent
		while (current !== null) {
			clientTop += current.offsetTop
			clientLeft += current.offsetLeft
			current = current.offsetParent
		}
		return {
			clientTop,
			clientLeft,
			height: ele.offsetHeight,
			width: ele.offsetWidth
		}
	}

	/**
	 * 只要鼠标松开或者离开区域，那么就停止resize
		*/
	stopResize = () => {
		this.setState({
			isVResize: false
		})
	}

	/**
	 * 拖动垂直调整块
	 */
	vResizeOver = (e) => {
		const { isVResize, vNum, vNumLimit } = this.state
		if (isVResize && vNum >= vNumLimit && (this.containerWidth - vNum >= vNumLimit)) {
			let newValue = e.clientX - this.resizeOffsetInfo.clientLeft
			if (newValue < vNumLimit) {
				newValue = vNumLimit
			}
			if (newValue > this.containerWidth - vNumLimit) {
				newValue = this.containerWidth - vNumLimit
			}
			this.setState({
				vNum: newValue
			})
		}
	}

	/**
	 * 开始拖动垂直调整块
	 */
	vResizeDown = () => {
		this.setState({
			isVResize: true
		})
	}

	/**
	 * 拖动水平调整块
	 */
	hResizeOver = (e) => {
		const { hNum, hNumLimit } = this.state;
		if (hNum >= hNumLimit && (this.resizeOffsetInfo.height - hNum >= hNumLimit)) {
			let newValue = this.resizeOffsetInfo.clientTop + this.resizeOffsetInfo.height - e.clientY
			if (newValue < hNumLimit) {
				newValue = hNumLimit
			}
			if (newValue > this.resizeOffsetInfo.height - hNumLimit) {
				newValue = this.resizeOffsetInfo.height - hNumLimit
			}
			this.setState({
				hNum: newValue
			})
		}
	}

	// 引用
	handleQuote = (str, quoteArr) => {
		this.caseTemplateChild.Spechars(str, quoteArr)
	}

	// 插入知识库xml
	setKnowledgeBaseXMl = (nodeContent, rowData, fn) => {
		this.caseTemplateChild.InsertXmlString(nodeContent, rowData, fn)
	}

	// 新知识库赋值
	knowledgeBaseAssignment = (filedID, value) => {
		this.caseTemplateChild.knowledgeBaseAssignment(filedID, value);
	}

	handleCaseInformationRef = ref => {
		this.caseInformationChild = ref;
	}

	// 供病历公共组件调用获取知识库数据
	getChildKnowledgeBaseTreeData = (fildId) => {
		// console.log("page", fildId, this.state.modalRowData)
		if (this.state.courseID !== fildId) {// 点击同一个病程则不再调用查询知识库方法
			this.setState({ courseID: fildId }, () => {
				this.caseInformationChild.getKnowledgeBaseTreeData(this.state.courseID, this.state.modalRowData);
			})
		}
	}

	// 获取已保存模板
	getSavedTemplatesData = () => {
		let { recordData } = this.state;
		let data = {
			params: [{
				admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ""), // 就诊记录主键
			}]
		}
		$http.post('urlS', this, {
			code: "06010096",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = res.result && res.result.dataAry ? JSON.parse(JSON.stringify(res.result.dataAry)) : [];
					for (var i = 0; i < arr.length; i++) {
						arr[i].ID = arr[i].eMRTemplateID;
					}
					this.setState({ savedTemplatesData: arr })
				}
			}
		})
	}

	// 删除患者病历
	deletePatientHistory = (type, courseID) => { // type = removeCourse courseID -- 病程ID 删除病程
		let { eMRRecordID, recordDataID, modalRowData, treeSelectData } = this.state;
		let allRecordID = this.caseTemplateChild.getTemplateXml("allRecordID");
		if (!eMRRecordID) {
			message.info("暂不支持删除", this.state.userData && this.state.userData.messageTime);
			return;
		}
		let data = {
			params: [{
				eMRRecordID: type === "removeCourse" ? courseID : eMRRecordID, // 病历记录主键
				recordDataID: type === "removeCourse" ? undefined : recordDataID, // 病历记录数据ID
				progressRecIDAry: type === "removeCourse" ? undefined : (allRecordID && allRecordID.length > 0 ? allRecordID : []), // 病程记录ID
			}]
		}
		$http.post('urlS', this, {
			code: "06010097",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success(res.errorMessage, this.state.userData && this.state.userData.messageTime);
					this.getTreeData("patientRecords"); // 保存成功之后重新加载患者病历
					this.setState({ modalRowData: { ...modalRowData, flag: 'loadTemplate' }, treeSelectData: { ...treeSelectData, patEMRRecordID: '' } });
					if (type !== "removeCourse") {
						this.setState({ eMRRecordID: "", isDeleteRecord: false, recordDataID: "", isUnlocking: true }); // 置空可删除ID
						// this.getSavedTemplatesData();
						this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified("noSave") : ""; // 保存成功后修改编辑状态
						if (timer) { // 清除定时保存的定时器
							clearInterval(timer);
						}
					}
				}
			}
		})
	}

	// 双击加载已保存模板
	handleSaveDTemplatesClick = (item) => {
		let key = [];
		let treeSelectData = JSON.parse(JSON.stringify(item));
		treeSelectData.ID = treeSelectData.wTemplateCatID;
		key.push(treeSelectData.eMRTemplateID);
		this.setState({ selectedKeys: key, treeSelectData }, () => {
			let obj = JSON.parse(JSON.stringify(item));
			obj.ID = obj.eMRTemplateID;
			obj.releaseVersion = obj.eMRReleaseVersion, // 版本号
				setTimeout(() => {
					this.getPatienHistoryData(obj);
				}, 300)
		})
	}

	// 另存为范例模板
	handleExampleTemplate = () => {
		this.setState({ exampleVisible: true }, () => {
			setTimeout(() => {
				this.commonTableChild && this.commonTableChild.handleLoading();
			}, 300)
		});
	}

	handleExampleTemplateCancel = () => {
		this.setState({ exampleVisible: false });
	}

	// 模板名称
	handleTemplateNameValueChange = e => {
		this.setState({ templateNameValue: e.target.value });
	}

	commonTableRef = ref => {
		this.commonTableChild = ref;
	}

	//跳转到西药及其他
	goDoctorAdviceStepPage = () => {
		var params = {
			params: [{
				locID: this.state.userData.locID,
				hospID: this.state.userData.hospID,
				groupID: this.state.userData.groupID
			}]
		}
		$http.post('urlDeault', this, {
			code: "03050093",
			data: params,
			success: function (res) {
				if (res.errorCode == '0') {
					for (var i = 0; i < res.result.length; i++) {
						if (res.result[i].code === '03050038') {
							var { upDataComponentSource } = this.props;
							upDataComponentSource && upDataComponentSource(res.result[i]);
							return;
						}
					}
				}
			}
		});
	}

	// 模板名称
	handleTemplateValue = e => {
		this.setState({ templateValue: e.target.value }, () => {
			if (!this.state.templateValue) {
				this.setState({ modalTemplateData: this.state.oldModalTemplateData })
			}
		})
	}

	// 回车筛选模板数据
	handleTemplateValuePressEnter = () => {
		let { templateValue } = this.state;
		let oldModalTemplateData = JSON.parse(JSON.stringify(this.state.oldModalTemplateData));
		var reg = new RegExp(templateValue);
		var arr = [];
		for (var i = 0; i < oldModalTemplateData.length; i++) {
			if (reg.test(oldModalTemplateData[i].descripts)) {
				arr.push(oldModalTemplateData[i]);
			}
		}
		this.setState({ modalTemplateData: arr });
	}

	// 保存插入的病程记录
	handleSaveTheInsertedCourse = (selectionXml, templateID, templateData = {}) => {
		let { treeSelectData } = this.state;
		let obj = { ...templateData };
		obj.ID = templateID;
		this.SaveMedicalRecord(treeSelectData, obj, 'courseOfDisease', selectionXml);
	}

	// 发送验光单
	handleSend = async () => {
		try {
			let { modalRowData, treeSelectData } = this.state;
			let data = {
				params: [{
					wCatalogueID: treeSelectData?.ID || '', // 分组目录ID
					versionID: modalRowData && modalRowData.releaseVersion ? modalRowData.releaseVersion : '', // 病历模板ID
					patEMRRecordID: modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID, // 病历记录ID
				}]
			}
			let res = await React.$asyncPost(this, '17020011', data);
			message.success(res?.errorMessage || '发送成功');
		} catch (error) {
			console.log(error)
		}
	}

	render() {
		let { expandedKeys, selectedKeys, treeData, templateName, autoExpandParent, visible, modalTemplateData, modalRowData, loadingTitle, spinLoading, historyAdmID,
			isDeleteRecord, exampleVisible, templateNameValue, tableData, total, page, loading, totalWidth, columns, showValidateResult, templateValue, isUnlocking
		} = this.state;
		let rowData = {}
		const { getFieldDecorator } = this.props.form;
		const formItemInput = {
			labelCol: { span: 8 },
			wrapperCol: { span: 16 }
		};
		let windowDom = (
			modalTemplateData && modalTemplateData.map((item, index) => {
				return (
					<div key={index} style={{ margin: (index + 1) % 5 == 0 ? '0 0 20px 0' : '0 20px 20px 0' }} onDoubleClick={() => this.compileChecked(item, index, "ok")}>
						<Tooltip title={item.descripts}>
							<div className="check-box">
								<div className="prep-win-desc" style={{ background: item.checked ? '#1890FF' : '#69C0FF', fontSize: "12px" }}>{item.descripts}</div>
								<div className="presc-num" style={{ color: item.checked ? '#1890FF' : '#69C0FF' }}>{item.releaseVersion}</div>
								<span>
									<Checkbox checked={item.checked} onChange={() => this.compileChecked(item, index)} />
								</span>
							</div>
						</Tooltip>
					</div>
				)
			})
		);

		let param = {
			isInsert: 'hidden',
			formView: 'Normal',
			isFont: true,
			isAllElection: true,
			isClearFormat: true,
			isSetTemplateSize: true,
			isSaveAnother: true,
			headerFooterEditable: 'noEditable',
			setChapter: 'show',
			isDelete: isDeleteRecord,
			printDocument: true,
			prTing: false,
			isBindingKnowledgeBase: true,
			showValidateResult,
			comments: true,
			isShear: true,
			isReload: false,
			self: false,
			original: false,
			addRow: true,
			isUnlocking, // 解锁按钮操作状态
			prCont: this.props.prCont && this.props.prCont === 'N' ? false : true,
			isBasicOperation: this.props.isBasicOperation ? this.props.isBasicOperation : false,
			viewEMRFlag: this.props?.viewEMRFlag || 'N',
		}

		let commonTableParam = {
			// 表头配置
			columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total: total,
			// 当前页数
			page: page,
			// 表格的宽度
			x: totalWidth,
			y: 133,
			height: "178px",
			loading: loading
		}

		const vCursor = this.state.isVResize ? 'col-resize' : 'default';
		const vColor = this.state.isVResize ? '#ddd' : 'rgba(240, 242, 245, 1)';

		// let savedTemplatesDom = savedTemplatesData && savedTemplatesData.length > 0 ? savedTemplatesData.map((item, index) => {
		// 	return (
		// 		<span key={index} onDoubleClick={() => this.handleSaveDTemplatesClick(item)}
		// 			style={{
		// 				border: modalRowData && (modalRowData.ID === item.ID) ? "1px solid #40a9ff" : "1px solid #e8e8e8",
		// 				padding: '2px 6px', background: "#fff", cursor: "pointer", marginRight: "12px", borderRadius: "3px",
		// 				color: modalRowData && (modalRowData.ID === item.ID) ? "#40a9ff" : "#000000a6"
		// 			}}
		// 		>
		// 			{item.eMRtemplateDesc}
		// 		</span>
		// 	)
		// }) : <span>{this.setMessage("CaseInformationPageNo_saved_templates", "descripts", "暂无已保存模板")}</span>;
		return (
			<Spin tip={loadingTitle} spinning={spinLoading} delay={300} style={{ height: "100%" }}>
				<div style={{ height: this.props.clpHeader ? this.props.clpHeader : store.getState().tableHeight.y + 158 }} className="case-information-page">
					<div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', display: this.props.clpHeader ? 'none' : 'block' }}></div>
					<div style={{ width: "260px", height: 'calc(100% - 6px)', display: 'inline-block', overflow: 'hidden', paddingRight: '6px', position: 'relative' }}>
						<div style={{ textAlign: "center", height: '34px', lineHeight: '34px', fontWeight: 900, fontSize: "14px", background: "#fafafa", borderBottom: "1px solid #e8e8e8" }}>{this.setMessage("CaseInformationPageMRTemplate", "descripts", "病历目录导航")}</div>
						<div style={{ height: "calc(100% - 34px)", overflow: 'auto' }}>
							<div style={{ width: '100%', padding: "8px 8px 0" }}>
								<Input value={templateName} onChange={this.handleTemplateNameChange} placeholder={this.setMessage("CaseInformationPageTemplate_name_query", "descripts", "请输入模板名称查询")} />
							</div>
							<Tree showIcon
								autoExpandParent={autoExpandParent}
								onExpand={this.onExpand}
								expandedKeys={expandedKeys}
								onSelect={this.onSelect}
								selectedKeys={selectedKeys}
								onDoubleClick={this.dblclickTreeNodes}>
								{this.renderTreeNodes(treeData)}
							</Tree>
						</div>
						<div style={{ position: 'absolute', right: '0', top: '0', width: '6px', background: 'rgba(240, 242, 245, 1)', height: '100%' }}></div>
					</div>
					<div style={{ width: "calc(100% - 260px)", position: 'relative', height: 'calc(100% - 6px)', overflow: "hidden", display: "inline-block" }}
						onMouseUp={this.stopResize} onMouseLeave={this.stopResize}
					>
						<div id='v_resize_container' style={{ position: "absolute", left: 0, top: 0, right: 0, bottom: 0, height: '100%' }} onMouseMove={this.vResizeOver}>
							<div id='h_resize_container' style={{ width: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === "N" ? "100%" : this.state.vNum, cursor: vCursor, height: '100%', float: "left" }} onMouseMove={this.hResizeOver}>
								{/* <div style={{ height: "calc(100% - 32px)" }}> */}
								<div style={{ height: "100%" }}>
									<ElectronicCaseTemplate
										param={param}
										onRef={this.handleCaseTemplateRef}
										handleSend={this.handleSend}
										handleSave={this.handleSave}
										handleDelete={this.deletePatientHistory}
										getKnowledgeBaseTreeData={this.getChildKnowledgeBaseTreeData}
										handleReload={this.handleOk}
										// handleExampleTemplate={this.handleExampleTemplate} // 另存为范例模板
										handleOnReload={modalRowData && modalRowData.ID ? () => this.getPatienHistoryData(modalRowData) : ""}
										editorID={this.props.editorID ? this.props.editorID : "CIPWriterControl"}
										handleSaveTheInsertedCourse={this.handleSaveTheInsertedCourse} // 保存插入的病程记录
										updateMedicalRecordLockStatus={() => this.updateMedicalRecordLockStatus(modalRowData && modalRowData.patEMRRecordID ? modalRowData.patEMRRecordID : eMRRecordID, "forceUnlock")}
									/>
								</div>
								{/* <div style={{ height: "32px", lineHeight: "32px", width: "100%", background: "#fafafa", padding: "0 12px" }}>
								{savedTemplatesDom}
							</div> */}
							</div>
							<div style={{ left: this.state.vNum, backgroundColor: vColor, display: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === "N" ? "none" : "block" }} draggable={false} onMouseDown={this.vResizeDown} className='v-resize' />
							<div style={{ marginLeft: this.state.vNum + 6, cursor: vCursor, height: '100%', display: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === "N" ? "none" : "block" }}>
								<CaseInformationPageTabs
									historyAdmID={historyAdmID}
									handleQuote={this.handleQuote} setKnowledgeBaseXMl={this.setKnowledgeBaseXMl} onRef={this.handleCaseInformationRef}
									modalRowData={this.state.modalRowData} treeSelectData={this.state.treeSelectData} compileVNum={this.compileVNum}
									knowledgeBaseAssignment={this.knowledgeBaseAssignment}
								/>
							</div>
						</div>
					</div>
					<Modal
						title="病历模板"
						visible={visible}
						onOk={this.handleOk}
						onCancel={this.handleCancel}
						style={{ minWidth: '680px' }}
					>
						<div style={{ display: "flex", alignItems: "center", padding: "24px 12px", paddingTop: 0 }}>
							病历模板：<Input allowClear placeholder="请输入检索内容（Enter）" style={{ width: "250px" }} value={templateValue} onChange={this.handleTemplateValue} onPressEnter={this.handleTemplateValuePressEnter} />
							<Button style={{ marginLeft: "12px" }} type="primary" onClick={this.handleTemplateValuePressEnter}>查询</Button>
						</div>
						<div style={{ maxHeight: "60vh", minHeight: "30vh", overflow: "auto" }}>
							<div className="ad-window li-window" style={{ padding: '0 12px' }}>
								{windowDom}
							</div>
						</div>
					</Modal>
					<Modal
						title="另存为范例模板"
						visible={exampleVisible}
						onCancel={this.handleExampleTemplateCancel}
						footer={null}
						style={{ minWidth: '900px' }}
						className="clear-modalandcard-style"
					>
						<div>
							<Row>
								<Col span={8}>
									<div style={{ paddingRight: '6px', position: 'relative' }}>
										<Card
											size="small"
											title={<div className="card-title-left-icon"><div></div>数据列表</div>}
										>
											<div style={{ height: "500px", overflow: "auto" }}>
												<div>
													<Input value={templateNameValue} onChange={this.handleTemplateNameValueChange} placeholder="请输入模板名称查询" style={{ width: "150px" }} />
													<span style={{ margin: "0 8px", color: "#1999db" }} className="span"><Icon type="plus" />添加</span>
													<span className="span"><Icon type="edit" />编辑</span>
												</div>
												<div style={{ marginTop: "12px" }}>
													暂无数据
												</div>
											</div>
										</Card>
										<div style={{ width: '6px', background: '#fff', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
									</div>
								</Col>
								<Col span={16}>
									<Card
										size="small"
										title={<div className="card-title-left-icon"><div></div>已保存模板列表</div>}
									>
										<div style={{ height: "216px", overflow: "auto" }}>
											<PubilcTablePagination param={commonTableParam} handelThis={this} onRef={this.commonTableRef} />
										</div>
									</Card>
									<div style={{ height: '6px', background: '#fff', width: '100%' }}></div>
									<Card
										size="small"
										title={<div className="card-title-left-icon"><div></div>添加范例模板</div>}
									>
										<div style={{ height: "216px", overflow: "auto" }}>
											<Form >
												<Row>
													<Col span={12}>
														<Form.Item label="所属病历模板" {...formItemInput}>
															{getFieldDecorator('herbalFormID', {
																initialValue: rowData.herbalFormID ? rowData.herbalFormID : undefined,
															})(
																<Input disabled />
															)}
														</Form.Item>
													</Col>
													<Col span={12}>
														<Form.Item label="模板分类" {...formItemInput}>
															{getFieldDecorator('durQty', {
																initialValue: rowData.durQty ? rowData.durQty : undefined,
															})(
																<Input type="number" className="input-number" />
															)}
														</Form.Item>
													</Col>
												</Row>
												<Row>
													<Col span={12}>
														<Form.Item label="模板名称" {...formItemInput}>
															{getFieldDecorator('herbalFormID', {
																initialValue: rowData.herbalFormID ? rowData.herbalFormID : undefined,
																rules: [{ required: true, message: "请输入" }]
															})(
																<Input />
															)}
														</Form.Item>
													</Col>
													<Col span={12}>
														<Form.Item label="生效日期" {...formItemInput}>
															{getFieldDecorator('durQty', {
																initialValue: rowData && rowData.startDate ? Moment(rowData.startDate) : Moment(),
																rules: [{ required: true, message: "请选择" }]
															})(
																<DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />
															)}
														</Form.Item>
													</Col>
												</Row>
												<Row>
													<Col span={12}>
														<Form.Item label="失效日期" {...formItemInput}>
															{getFieldDecorator('herbalFormID', {
																initialValue: rowData && rowData.endDate ? Moment(rowData.endDate) : null,
															})(
																<DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />
															)}
														</Form.Item>
													</Col>
												</Row>
												<Row style={{ textAlign: "center", marginTop: "12px" }}>
													<Button style={{ marginRight: "12px" }}>取消</Button>
													<Button type="primary">确定</Button>
												</Row>
											</Form>
										</div>
									</Card>
								</Col>
							</Row>
						</div>
					</Modal>
					<ColumnAuthoritysModel
						clientWidth='800px'
						compontName='CaseInformationPage'
						configType="C"
						onRef={this.onMainColumnRef}
						reloadData={this.getChineseAndEnglishData}
					/>
				</div>
			</Spin>
		)
	}
};
const CaseInformationPageForm = Form.create()(CaseInformationPage);
export default CaseInformationPageForm;