// 病程弹窗
import React from 'react';
import { message, Icon, Modal, Input, Button } from 'antd';
import { $http } from 'containers/config/https';
import { httpConfig } from 'containers/config/httpConfig';
import './style/index.less';
import PubilcTablePagination from './PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
let initCtl = 0;

export default class CourseOfDiseaseTemplate extends React.Component {
	constructor(props) {
		super(props);
		var EMRIP = window.location && (window.location.host.indexOf('localhost') !== -1 || window.location.host.indexOf('127.0.0.1') !== -1) ? 'https://172.16.1.6/EMR' : (window.location.protocol + '//' + window.location.host + '/EMR');
		var userData = JSON.parse(sessionStorage.getItem('userData'));
		this.state = {
			userData,
			templateErrorMes: '',
			EMRIP,
			localeProvider: [],
			insertTemplateArr: [],
			selectRowData: {},
			dropDownSearch: false, // 下拉搜索
			modalTableData: [],
			columns: [],
			modalTotal: 0,
			modalPage: 1,
			modalPageSize: 10,
			selectDesc: undefined
		};
		this.editorID = this.props && 'editorID' in this.props ? this.props.editorID : 'myWriterControl';
		this.columns = [
			{ title: '代码', dataIndex: 'code', key: '2', width: '100px', align: 'center' },
			{ title: '描述', dataIndex: 'descripts', key: '3', width: '200px', align: 'center' },
		]
	}

	componentDidMount() {
		let { userData } = this.state;
		this.props.onRef && this.props.onRef(this);
		userData.language == 'EN' ? this.getChineseAndEnglishData() : '';
		Promise.all([this.importService(), this.importJquery()])
			.then(() => {
				setTimeout(() => {
					this.handleInit()
				}, 800)
			})
	}

	importJquery = () => {
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.async = true;
		script.id = 'emr-jquery';
		script.src = `${this.state.EMRIP}/jquery/jquery-1.7.2.min.js`; // www.dcwriter.cn、172..18.13.23:62535
		document.head.appendChild(script);
	}

	importService = () => {
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.async = true;
		script.id = 'emr-service';
		script.src = `${this.state.EMRIP}/DemoDocumentImageService.aspx?js=1`;
		document.head.appendChild(script);
	}

	// 获取中英文数据
	getChineseAndEnglishData = () => {
		let { userData } = this.state;
		let data = {
			params: [{
				compontName: 'ElectronicCaseTemplate',
				reactCode: ['ElectronicCaseTemplate']
			}]
		}
		$http.post('urlDeault', this, {
			code: '01040073',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					this.setState({
						localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
					})
				}
			}
		})
	}

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

	handleInit = () => {
		// 获得控件容器元素
		try {
			var ctl = document.getElementById(this.editorID);
			var _this = this;
			// 绑定控件
			BindingDCWriterClientControl(ctl);
			ctl.Options.autoZoom = false;

			ctl.Options.FormView = 'Normal';
			ctl.Options.FreeSelection = 'true';//表单模式下，自由选择
			ctl.Options.HeaderFooterEditable = 'false'
			ctl.DocumentOptions.ViewOptions.ShowCellNoneBorder = false; // 是否可以删除表格边框
			// 隐藏获取焦点时输入域边框问题
			ctl.Options.CustomCSSString += "*{outline:none;}";

			// 设置控件属性
			ctl.DocumentOptions.ViewOptions.ShowInputFieldStateTag = false;
			ctl.DocumentOptions.BehaviorOptions.AcceptDataFormats = 'Text';
			ctl.DocumentOptions.ViewOptions.FieldInvalidateValueBackColor = 'Yellow';
			ctl.DocumentOptions.ViewOptions.FieldFocusedBackColorValue = '#fff'; // 光标所在背景色
			ctl.DocumentOptions.ViewOptions.FieldHoverBackColorValue = '#fff';
			ctl.DocumentOptions.ViewOptions.FieldBackColorValue = '#fff'; // 文本输入域的默认背景颜色
			// 用Tab键在各个输入域之间切换
			ctl.DocumentOptions.BehaviorOptions.MoveFocusHotKey = 'Tab';
			ctl.DocumentOptions.ViewOptions.EnableEncryptView = true;
			ctl.DocumentOptions.ViewOptions.PrintBackgroundText = false;
			ctl.DocumentOptions.ViewOptions.PreserveBackgroundTextWhenPrint = false;
			//ctl.Options.FormView = 'Normal';
			// ctl.ToolbarForPrintPreview = document.getElementById('btrPrintPreview');
			// 创建编辑器框架
			ctl.BuildFrame(function () {

			});

			ctl.DocumentLoad = function () {
				_this.setInputValue();
				!_this.state.isClear ? _this.clearLoadCache(_this.state.fileName) : ''; // 清除加载的版本
				_this.setContenteditable(); // 页眉不可操作

				// 动态下拉列表
				ctl.EventQueryListItems = function (eventObject) {
					console.log('动态下拉列表', eventObject)
					// CS做的模板跟BS做的模板不一样
					let domId = eventObject && eventObject.ListSourceName ? eventObject.ListSourceName : eventObject.ControlName;
					let num = '1';
					let obj = {};
					for (var i = 0; i < _this.state.insertTemplateArr.length; i++) {// 自定义数据
						if (domId == _this.state.insertTemplateArr[i].fieldID) {
							obj = _this.state.insertTemplateArr[i];
							num = '1'
							break;
						} else {
							for (var j = 0; j < _this.props.customDataTableData.length; j++) {// 自定义数据
								if (domId == _this.props.customDataTableData[j].code) {
									obj = _this.props.customDataTableData[j];
									num = '2'
									break;
								}
							}
						}
					}
					// console.log(num, obj, eventObject.Element.innerText);
					let modalTitle = eventObject.Element && eventObject.Element.innerText ? eventObject.Element.innerText : '动态下拉选择';
					let selectRowData = { ...obj, modalTitle }
					if (selectRowData && selectRowData.baseDataSet && selectRowData.baseDataSet === 'Y') { // 判断动态下拉是否需要弹窗选择
						_this.getModalColumns(selectRowData && selectRowData.baseDataColumn ? selectRowData.baseDataColumn : '');
						_this.setState({ dropDownSearch: true, selectRowData }, () => {
							_this.handleQuery();
						})
					} else {
						_this.getCustomDataValue(num, obj, eventObject);
					}
				}

				//鼠标单击事件
				ctl.ondocumentclick = function (eventObject) {
					var node = ctl.CurrnetElement();// 获得元素的ID值
					var initID = '';
					while (node != null) {
						initID = node.id;
						if (initID != null && initID.length > 0) {
							break;
						}
						node = node.parentNode;
					}
					// if (param && param.formView === 'Normal' && initID.substring(0, 6) === 'course') { // 当为表单模式并且该区域为病程时
					// if (param && param.formView === 'Normal' && initID) { // 当为表单模式并且该区域为病程时
					if (initID) { // 当为表单模式并且该区域为病程时
						// let strLength = initID && initID.length ? initID.length : 0;
						// console.log('Electronic')
						_this.props.getKnowledgeBaseTreeData && _this.props.getKnowledgeBaseTreeData(initID);  // 获取该病程的知识库数据
					}
					if (initID == '345') {
						var oldText = ctl.GetElementTextByID(initID);//当前文本
						_this.setState({ isShowCustomPopUps: true, initID })
						if (newText != null && newText.length > 0) {
							var result = ctl.SetElementTextByID(initID, newText);//赋值
						}
					}
				}
			}
		} catch (error) {
			console.log(error)
			this.setState({ templateErrorMes: '病历模板加载失败，请重新进入该页面' })
		}
	}

	// 新建
	NewFile = () => {
		this.AjaxLoad('FileTemplate\\XYSTemplate\\mzdefault.xml', true);
	}

	// 服务端加载文档
	AjaxLoad = (fileName, isClear, record, index, callBack) => {
		try {
			var ctl = document.getElementById(this.editorID);
			ctl.preserveScrollPosition = true; // 加载文档时尽量保留页面滚动位置。
			let result = ctl.LoadDocumentFromFile(fileName, null);
			if (!result) {
				message.error(`加载文件 ${fileName} 失败。`);
				setTimeout(() => {
					callBack && callBack(record, index, 'N');
				}, 500)
			} else {
				this.setState({ fileName, isClear }, () => {
					setTimeout(() => {
						callBack && callBack(record, index, 'Y');
					}, 500)
				})
			}
		} catch {
			this.setState({ templateErrorMes: '病历模板加载失败，请重新加载' }, () => {
				setTimeout(() => {
					callBack && callBack(record, index, 'N');
				}, 500)
			})
		}
	}

	// 根据ID附上对映的值
	setElementTextByID = (path, data, record, index, callBack) => {
		var ctl = document.getElementById(this.editorID);
		if (!(ctl && ctl.GetContentDocument)) {
			initCtl++;
			if (initCtl < 10) {
				setTimeout(() => {
					this.setElementTextByID(path, data, record, index, callBack)
				}, 300);
			} else {
				callBack && callBack(record, index, 'N');
			}
			return;
		}
		this.setState({ insertTemplateArr: data }, () => {
			this.AjaxLoad(path, false, record, index, callBack);
			initCtl = 0; // 重置初始值
		})
	}

	// 将页眉设置为不可编辑
	setContenteditable = () => {
		var ctl = document.getElementById(this.editorID);
		var doc = ctl?.GetContentDocument();
		$(doc).find("[dctype=\"XTextDocumentHeaderElement\"],[dctype=\"XTextDocumentFooterElement\"]").attr("contenteditable", false);
		// 输入域框可见
		var inputs = $(doc).find("[dctype='XTextInputFieldElement']");//JQUERY
		for (var i = 0; i < inputs.length; i++) {
			inputs[i].setAttribute('dc_bordervisible', 'Visible'); // 输入框是否可见，由于版本问题，模板那边有些输入域设置了不可见，前端统一处理为可见！
		}
	}

	setInputValue = () => {
		try {
			const ctl = document.getElementById(this.editorID);
			if (ctl && ctl.SetElementTextByID) {
				const recordsArr = ctl && ctl.GetCourseRecords && ctl.GetCourseRecords();
				let arr = this.state.insertTemplateArr && this.state.insertTemplateArr.length > 0 ? this.state.insertTemplateArr : [];
				for (var i = 0; i < arr.length; i++) {
					let displayValue = arr[i]?.displayValue || '';
					let fieldID = arr[i]?.fieldID || '';
					let recordID = arr[i]?.recordID || '';
					if (arr[i] && fieldID && arr[i].updateFlag === "Y" && displayValue !== undefined && displayValue !== '') {
						// console.log(arr[i])
						if (fieldID && (fieldID.slice(0, 5) === "table")) { // 表格渲染
							this.handleTableAssignment(fieldID, displayValue);
							continue;
						} else if (fieldID && (fieldID.slice(0, 8) === 'radioBox' || fieldID.slice(0, 8) === 'checkbox')) { // 单选框/多选设置默认值
							ctl.SetElementCheckedByID(fieldID, displayValue === 'Y' ? true : false);
							continue;
						} else {
							if (recordID && recordsArr && recordsArr.length > 0) {
								for (let j = 0; j < recordsArr.length; j++) {
									let currentElementID = recordsArr[j] && recordsArr[j].ElementID ? recordsArr[j].ElementID : '';
									currentElementID = currentElementID.indexOf('record') > -1 || currentElementID.indexOf('paging') > -1 ? currentElementID.slice(6) : currentElementID;
									if (currentElementID && currentElementID === recordID) {
										ctl.SetElementTextByID(fieldID, displayValue, recordsArr[j].ElementID);
										break;
									}
								}
							} else {
								ctl.SetElementTextByID(fieldID, displayValue);
								continue;
							}
						}
					}
				}
			}
		} catch (error) {
			console.log(error);
		}
	}

	// 3.3.22.清除模板版本加载缓存
	clearLoadCache = (fileName) => {
		if (!fileName) return;
		let data = {
			params: [{
				patch: fileName
			}]
		}
		$http.post('urlS', this, {
			code: "06020026",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					console.log("清除缓存成功")
				}
			}
		})
	}

	// 编辑
	handleCompile = num => {
		var ctl = document.getElementById(this.editorID);
		switch (num) {
			case 1:
				ctl.Undo(); // 撤销
				break;
			case 2:
				ctl.Redo(); // 重做
				break;
			case 3:
				ctl.DCExecuteCommand('Copy', true, null); // 复制
				break;
			case 4:
				ctl.DCExecuteCommand('Cut', true, null); // 剪切
				break;
			case 5:
				message.info("粘贴操作和常用的富文本编辑中的粘贴操作相同，快捷键是Ctrl+V。")
				break;
			case 6:
				ctl.BeginFormatBrush(); // 格式刷
				break;
			case 7:
				message.info("全选操作和常用的富文本编辑中的全选操作相同，快捷键是Ctrl+A。")
				break;
			case 8:
				ctl.DCExecuteCommand('ToupperCase', true, null); // 字母转成大写
				break;
			case 9:
				ctl.DCExecuteCommand('TolowerCase', true, null); // 字母转成小写
				break;
			default:
				message.info("删除操作和常用的富文本编辑中的删除操作相同，快捷键是Delete或BackSpace。")
		}
	}

	// 根据id获取病程的xml串
	GetCourseRecordXML = (type) => {
		let ctl = document.getElementById(this.editorID);
		let allCourseOfDisease = ctl && ctl.GetCourseRecords ? ctl.GetCourseRecords() : [];
		let recordDataSource = [];
		for (let i = 0; i < allCourseOfDisease.length; i++) {
			let id = allCourseOfDisease[i]?.ElementID || '';
			if (id) {
				let recordID = id.substring(6);
				if (type === 'inputArr') {
					let fieldList = [];
					let doc = ctl && ctl.GetContentDocument().getElementById(id);
					let inputs = $(doc).find("[dctype='XTextInputFieldElement']"); // JQUERY
					for (let i = 0; i < inputs.length; i++) {
						let index = i;
						let fieldID = inputs.eq(index).attr('id');
						let value = ctl.GetElementTextByID(fieldID, id); // 获取病程中的内容
						if (value) {
							fieldList.push({
								fieldID,
								value
							})
						}
					}
					recordDataSource.push({
						recordID,
						dataSource: fieldList,
					})
				} else {
					recordDataSource.push(recordID)
				}
			}
		}
		return recordDataSource;
	}

	// 获取模板xml
	getTemplateXml = (flag, record, index) => {
		var ctl = document.getElementById(this.editorID);
		if (!ctl) {
			setTimeout(() => {
				callBack && callBack(record, index, 'N');
			}, 500)
			return;
		}
		var courseOfDisease = ctl && ctl.GetContentDocument && ctl.GetContentDocument().getElementById('newtitle'); // 检测该模板是否存在新建病程
		let status = false;
		let allRecordID = courseOfDisease ? this.GetCourseRecordXML() : []; // 获取所有病程ID
		if (flag === 'form') { // 表单模式需要走验证
			status = true;
		} else if (flag === 'release') { // 模板发布时去除病程样式
			this.clearCourseDiseaseStyle();
		} else if (flag == 'allRecordID') { // 返回病程ID
			return allRecordID
		}
		var xmlStr = ctl.SaveDocumentToString('XML');
		let dataSource = this.getInputField();
		let recordDataSource = this.GetCourseRecordXML('inputArr');
		let obj = {
			xmlStr,
			dataSource,
			status,
			allRecordID,
			recordDataSource,
			isEmptyTemplate: this.handleDetermineTemplateContent()
		}
		return obj;
	}

	// 判断是否为空模板
	handleDetermineTemplateContent = () => {
		let ctl = document.getElementById(this.editorID);
		let WCDoc = ctl.GetContentDocument();
		let WCBodyChildP = WCDoc.getElementById('divDocumentBody_0')?.getElementsByTagName('p') || '';
		let isEmptyTemplate = 'Y';
		// console.log('WCBodyChildP', WCBodyChildP);
		// console.log('WCBodyChildP[0].innerHTML', WCBodyChildP && WCBodyChildP.length > 0 ? (WCBodyChildP[0]?.innerHTML || '') : '')
		if (!(WCBodyChildP && ((WCBodyChildP.length === 1 && 'innerHTML' in WCBodyChildP[0] && (WCBodyChildP[0].innerHTML === '<br>' || WCBodyChildP[0].innerHTML === `<br dcignore=\"1\" >` || WCBodyChildP[0].innerHTML.length < 50)) || WCBodyChildP.length < 1))) {
			isEmptyTemplate = 'N';
		}
		return isEmptyTemplate;
	}

	// 清除病程样式
	clearCourseDiseaseStyle = () => {
		var ctl = document.getElementById(this.editorID);
		var doc = ctl.GetContentDocument();
		$(doc).find("[dctype=\"XTextSubDocumentElement\"]").removeAttr("style");
	}

	// 获取输入域 --- 过滤删除的元素
	getInputField = () => {
		let { insertTemplateArr } = this.state;
		let arr = [];
		if (!(insertTemplateArr && insertTemplateArr.length > 0)) {
			return arr;
		}
		var ctl = document.getElementById(this.editorID);
		var doc = ctl.GetContentDocument();
		var inputs = $(doc).find("[dctype='XTextInputFieldElement']");//JQUERY
		var fieldList = [];
		for (var i = 0; i < inputs.length; i++) {
			fieldList.push(inputs.eq(i).attr('id'))
		}
		for (var i = 0; i < insertTemplateArr.length; i++) {
			for (var j = 0; j < fieldList.length; j++) {
				if (insertTemplateArr[i].fieldID === fieldList[j]) {
					arr.push(insertTemplateArr[i])
				}
			}
		}
		return arr;
	}

	// 新知识库赋值
	knowledgeBaseAssignment = (fieldID, value) => {
		var ctl = document.getElementById(this.editorID);
		if (ctl && ctl.SetElementTextByID) {
			var result = ctl.SetElementTextByID(fieldID, value);
			console.log(result)
		}
	}

	// 插入xml字符串
	InsertXmlString = (nodeContent, rowData, fn) => {
		var ctl = document.getElementById(this.editorID);
		if (ctl && ctl.SetElementTextByID) {
			var result = ctl.InsertXmlString(nodeContent, false, null);
			// console.log(result, fn)
			if (fn) {
				fn();
			}
		}
	}

	// 获取自定义数据值
	getCustomDataValue = (flag, othCode, eventObject) => {
		this.jqAjax(flag, othCode, (res) => { // 成功的回调
			let arr = JSON.parse(JSON.stringify(res.result));
			arr && arr.map((item => {
				return eventObject.AddResultItemByTextValue(item.descripts, item.ID);
			}))
		}, (error) => {
			console.log(error)
		})
	}

	jqAjax = (flag, othCode, success, error) => {
		let url = httpConfig.ipDeault + httpConfig.urlAddress;
		let json = {
			params: [{
				ID: flag === "2" ? othCode.ID : undefined
			}]
		}
		let formData = Object.assign({}, json);
		let { userData } = window.sessionStorage
		formData.code = flag === "2" ? "06010044" : othCode.serviceCode;
		if (userData) {
			let user = JSON.parse(userData)
			let ip = React.$getSessionData('ipConfig');
			formData.session = [{
				"userID": user.userID || '',
				"locID": user.locID || '',
				"groupID": user.groupID || '',
				"hospID": user.hospID || '',
				"sessionID": user.sessionID || '',
				"hostName": ip?.hostName || '',
				"ipv4": ip?.ipv4 || '',
				"ipv6": ip?.ipv6 || '',
				"mac": ip?.mac || '',
			}]
		}
		$.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
			},
		});
	}

	// 获取基础数据字典弹窗表头数据
	getModalColumns = (compontName) => {
		if (!compontName) {
			this.setState({ columns: [] });
			return;
		}
		let { userData } = this.state;
		let data = {
			params: [{
				compontName,
				type: "C",
				reactCode: [compontName]
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					// console.log(res)
					let columnsData = res.result.C && res.result.C.map((item, index) => {
						return {
							...item,
							key: index,
							// title: userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title,
							title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
						}
					});
					this.setState({
						columns: columnsData,
					})
				}
			}
		})
	}

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

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

	// 查询
	handleQuery = () => {
		let { selectRowData } = this.state;
		if (selectRowData && selectRowData.serviceCode) {
			this.setState({ modalPage: 1 }, () => {
				this.getTableData();
			})
		}
	}

	getTableData = () => {
		let { selectDesc, selectRowData, modalPage, modalPageSize, recordData } = this.state;
		this.setState({ modalLoading: true })
		let data = {
			params: [{
				searchWords: selectDesc,
				admID: recordData && recordData.admID ? recordData.admID : "",
			}],
			pagination: [{
				pageSize: modalPageSize,
				currentPage: modalPage
			}]
		}
		setTimeout(() => {
			var gunDong = document.getElementById("gun-dong");
			if (gunDong) {
				gunDong.scrollTop = 0;
			}
		}, 100)
		$http.post('urlDeault', this, {
			code: selectRowData.serviceCode,
			data: data,
			success: (res) => {
				this.modalRef && this.modalRef.handleLoading && this.modalRef.handleLoading();
				this.setState({ modalLoading: false })
				if (+res.errorCode === 0) {
					let modalTableData = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
					for (var i = 0; i < modalTableData.length; i++) {
						modalTableData[i].key = i + 1
					}
					this.setState({ modalTableData, modalTotal: res.result && res.result.totalCount ? res.result.totalCount : 0 });
				} else {
					this.setState({ modalTableData: [], modalTotal: 0 });
				}
			},
			error: () => {
				this.modalRef && this.modalRef.handleLoading && this.modalRef.handleLoading();
				this.setState({ modalTableData: [], modalTotal: 0 });
			}
		})
	}

	onModalRef = ref => {
		this.modalRef = ref;
	}

	// 操作行
	onClickRowPublic = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.modalRowId === '') {
					// 保存行数据以及ID
					this.setState({ modalRowId: record.key, modalRowData: record })
				} else {
					if (this.state.modalRowId !== record.key) {
						this.setState({ modalRowId: record.key, modalRowData: record })
					}
				}
			},
			onDoubleClick: () => {
				this.setState({ modalRowId: record.key, modalRowData: record }, () => {
					this.handleDropDownSearchOk()
				})
			}
		}
	}

	// 选中行操作 --- 发药列表
	setRowClassNamePublic = (record) => {
		return record.key === this.state.modalRowId ? 'clickRowStyle' : "";
	}

	// 获取当前输入域的下一个输入域ID
	getNextFieldID = (fieldID, type) => {
		let fieldData = this.getMedicalRecordFileIDAndValue(fieldID);
		let nextFieldID = [];
		if (fieldData && fieldData.length > 0) {
			for (var i = 0; i < fieldData.length; i++) {
				if ((fieldData[i].fieldID === fieldID) || (fieldID === 'all')) {
					nextFieldID.push(fieldData[i + 1] && fieldData[i + 1].fieldID ? fieldData[i + 1].fieldID : fieldID);
				}
			}
		}
		if (type === "arr") {
			return nextFieldID
		} else {
			return nextFieldID && nextFieldID.length > 0 ? nextFieldID[0] : fieldID;
		}
	}

	// 获取当前病历模板所有的输入域ID以及对应的value
	getMedicalRecordFileIDAndValue = (type) => {
		let IDCollection = this.state.IDCollection && this.state.IDCollection.length > 0 ? this.state.IDCollection : [];
		// console.log(IDCollection)
		var ctl = document.getElementById(this.editorID);
		var doc = ctl && ctl.GetContentDocument();
		var inputs = $(doc).find("[dctype='XTextInputFieldElement']");//JQUERY
		var fieldList = [];
		for (let i = 0; i < inputs.length; i++) {
			let index = i;
			// let fieldID = "";
			// let value = "";
			let fieldID = inputs.eq(index).attr("id");
			let value = fieldID ? (ctl && ctl.GetElementTextByID && ctl.GetElementTextByID(fieldID)) : "";
			let keyObject = {
				fieldID,
				// value: inputs.eq(index).text() ? inputs.eq(index).text().replace("[", "").replace("]", "") : ""
				value,
				valueID: undefined
			}
			// 根据fieldID取出弹窗选择的数据对应的valueID
			for (var j = 0; j < IDCollection.length; j++) {
				if (fieldID === IDCollection[j].fieldID) {
					keyObject.valueID = IDCollection[j].valueID
				}
			}
			// keyObject[fieldID] = value;
			if (value || (type === 'all')) {
				fieldList.push(keyObject)
			}
		}
		return fieldList;
	}

	// 确认
	handleDropDownSearchOk = () => {
		try {
			let { selectRowData, modalRowData } = this.state;
			var ctl = document.getElementById(this.editorID);
			let oldFieldID = "";
			if (selectRowData && selectRowData.linkItem && selectRowData.linkItem.length && selectRowData.linkItem.length > 0) { // 给相关绑定的输入域赋值
				for (var i = 0; i < selectRowData.linkItem.length; i++) {
					ctl.SetElementTextByID(selectRowData.linkItem[i].fieldID, modalRowData[selectRowData.linkItem[i].linkResCode]);
					oldFieldID = selectRowData.linkItem[i].fieldID;
				}
			} else {
				var result = ctl.SetElementTextByID(selectRowData.fieldID, modalRowData && modalRowData.descripts ? modalRowData.descripts : "");
				oldFieldID = selectRowData?.fieldID || '';
			}

			if (selectRowData && selectRowData.fieldID) {
				this.handleDropDownSearchCancel();
				let nextFieldID = this.getNextFieldID(oldFieldID);
				console.log(oldFieldID, nextFieldID)
				setTimeout(() => {
					let nextFieldDOM = ctl.GetContentDocument().getElementById(nextFieldID);
					$(nextFieldDOM).focus();
				}, 300);
			}
		} catch (error) {
			this.handleDropDownSearchCancel();
		}
	}

	// 关闭搜索选择弹窗
	handleDropDownSearchCancel = () => {
		this.setState({ dropDownSearch: false }, () => {
			this.setState({ modalRowId: "", modalRowData: {}, selectCode: undefined, selectDesc: undefined, })
		})
	}

	// 获取描述
	getSelectDescValue = (e) => {
		this.setState({ selectDesc: e.target.value })
	}

	// 键盘操作名称模态框数据
	handlePublicModalTableOnKeydown = (e) => {
		var e = window.event || e;
		let scroll_height = 32;
		let id = '';
		let oneArr = this.state.modalTableData && this.state.modalTableData.length > 0 ? this.state.modalTableData : [];
		switch (e.keyCode) {
			case 13:
				if (this.state.modalRowId) {
					let obj = {}
					for (var i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.modalRowId) {
							obj = i > 0 ? oneArr[i] : oneArr[0];
							break;
						}
					}
					this.setState({ modalRowId: obj.key, modalRowData: obj }, () => {
						this.handleDropDownSearchOk()
					})
				} else {
					message.info("请选择需要操作的数据。")
				}
				break;
			case 38: //上
				if (this.state.modalRowId) {
					for (var i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.modalRowId) {
							id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
							break;
						}
					}
					this.setState({ modalRowId: id })
					setTimeout(() => {
						var gunDong = document.getElementById("gun-dong");
						if (gunDong) {
							gunDong.scrollTop = gunDong.scrollTop - scroll_height;
						}
					}, 100)
				} else {
					this.setState({ modalRowId: oneArr[0].key })
				}
				break;
			case 40: //下
				if (this.state.modalRowId) {
					for (let i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.modalRowId) {
							id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
							break;
						}
					}
					this.setState({ modalRowId: id })
					setTimeout(() => {
						var gunDong = document.getElementById("gun-dong");
						if (gunDong) {
							gunDong.scrollTop = gunDong.scrollTop + scroll_height;
						}
					}, 100)
				} else {
					this.setState({ modalRowId: oneArr[0].key })
				}
				break;
		}
	};

	render() {
		let { templateErrorMes, selectRowData, selectDesc, dropDownSearch, columns, modalTableData, modalTotal, modalPage, modalLoading } = this.state;
		// 组件所需参数
		const tableParam = {
			// 表头配置
			columns: columns && columns.length > 0 ? columns : this.columns,
			// 表格数据
			data: modalTableData,
			// 数据总条数
			total: modalTotal,
			// 当前页数
			page: modalPage,
			pageSize: "20",
			// 表格的宽度
			x: 500,
			y: 255,
			height: '300px',
			isOnRow: true,
			rowClassName: true,
			loading: modalLoading,
			TableClassName: 'modal-select',
		};

		return (
			<div className="layui-body electronic-case-template" style={{ height: "100%", overflow: "hidden", position: 'relative' }}>
				{this.props.operationFlag !== 'N' ? (
					<div className="operation-span">
						<span onClick={() => this.handleCompile(1)}>
							<Icon type="reload" style={{ transform: "rotateY(-180deg)" }} />
							{this.setMessage("ElectronicCaseTemplateRevoke", "descripts", "撤销")}
						</span>
						<span onClick={() => this.handleCompile(2)} title={this.setMessage("ElectronicCaseTemplateRedo", "message", "重复上一步操作")}>
							<Icon type="reload" />
							{this.setMessage("ElectronicCaseTemplateRedo", "descripts", "重做")}
						</span>
						<span onClick={() => this.handleCompile(3)}>
							<Icon type="copy" />
							{this.setMessage("ElectronicCaseTemplateCopy", "descripts", "复制")}
						</span>
						<span onClick={() => this.handleCompile(4)}>
							<Icon type="scissor" />
							{this.setMessage("ElectronicCaseTemplateCut", "descripts", "剪切")}
						</span>
						<span onClick={() => this.handleCompile(5)}>
							<Icon type="snippets" />
							{this.setMessage("ElectronicCaseTemplatePaste", "descripts", "粘贴")}
						</span>
						<span onClick={this.props.handleReload}>
							<Icon type="sync" />
							{this.setMessage("ElectronicCaseTemplateReload", "descripts", "重新加载")}
						</span>
					</div>
				) : ''}
				{templateErrorMes ? <div style={{ color: "red", paddingTop: "12px", fontSize: "14px" }}>{templateErrorMes}</div> : <div
					id={this.props?.editorID || 'myWriterControl'}
					style={{ height: "calc(100% - 32px)" }}
					contentrendermode="NormalHtmlEditable" // 代表页面模式，比如：编辑模式：NormalHtmlEditable，打印预览模式：PagePreviewHtml。
					referencepathfordebug="ctlReference"
					workspacebackcolorstring="#B1CAEB" // 设置背景颜色
					// workspacebackgroundimage="Workspace-Background.png" // 设置背景图片
					servicepageurl={`${this.state.EMRIP}/DemoDocumentImageService.aspx`} // 是指向第一步建立的ASP.NET的WEB页面的路径，可以使用网络路径。
					useclassattribute="true"
					heightcompress="true"
					backgroundtextoutputmode="None"
					imagedataembedinhtml="true"
					serversleepfordebug="0"
					allowcopy="true"
					// HeaderFooterEditable={params&&params.formView === "Normal" ? "fasle" : "true"} // 页眉页尾是否可操作
					supportactivex="false"
					pixelpagespacing="5"
					clientcontextmenutype="Custom" // 设置右键菜单，要把值设为Custom才行
					usedcwriterminijs="True"
					autozoom2="true"
					customcssstring="
                ::-webkit-scrollbar {width: 10px;height: 10px;}
                ::-webkit-scrollbar-thumb {border-radius: 5px;
                    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);background: #349dee; }
                ::-webkit-scrollbar-track {-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
                    border-radius: 0;background: #eaedf1;}"
					showdebuginfo="false"
					registercodeindex="0"
				></div>}
				<Modal
					title="动态下拉列表选择"
					visible={dropDownSearch}
					onOk={this.handleDropDownSearchOk}
					style={{ minWidth: '600px', minHeight: '300px' }}
					onCancel={this.handleDropDownSearchCancel}
				>
					<div style={{ width: "100%", height: '370px' }}>
						<div style={{ marginBottom: "12px" }}>
							{/* 代码：<Input
								title="输入内容后可回车检索"
								placeholder="请输入( Enter )"
								value={selectCode}
								style={{ width: '150px', marginRight: "12px" }}
								onChange={this.getSelectCodeValue}
								onPressEnter={this.handleQuery}
							/> */}
							描述：<Input
								title="输入内容后可回车检索"
								placeholder="请输入( Enter )"
								value={selectDesc}
								style={{ width: '250px', marginRight: "12px" }}
								onChange={this.getSelectDescValue}
								onPressEnter={this.handleQuery}
							/>
							<Button type="primary" onClick={this.handleQuery}>查询</Button>
						</div>
						<div
							tabIndex={1}
							onKeyDown={this.handlePublicModalTableOnKeydown}
							style={{ outline: 'none' }}
						>
							<PubilcTablePagination param={tableParam}
								handelThis={this} onRef={this.onModalRef}
								onClickRowPublic={this.onClickRowPublic}
								setRowClassNamePublic={this.setRowClassNamePublic}
								id="gun-dong"
							/>
						</div>
					</div>
				</Modal>
				<ColumnAuthoritysModel
					clientWidth='800px'
					compontName={selectRowData && selectRowData.baseDataColumn ? selectRowData.baseDataColumn : 'ElectronicCaseTemplate'}
					configType="C"
					onRef={this.onMainColumnRef}
					reloadData={selectRowData && selectRowData.baseDataColumn ? () => this.getModalColumns(selectRowData.baseDataColumn) : this.getChineseAndEnglishData}
				/>
			</div>
		)
	}
}
