// 历史病历
import React from 'react';
import { message, Icon } from 'antd';
import { $http } from 'containers/config/https';
import './style/index.less';

let initHandleInit = 0;

export default class DetailMedicalRecordTemplate extends React.Component {
	constructor() {
		super();
		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: [],
		};
	}

	componentDidMount() {
		let { userData } = this.state;
		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 = () => {
		// 获得控件容器元素
		if (!(window && window.BindingDCWriterClientControl)) { // 初始化加载病历模板
			// console.log('initHandleInit', initHandleInit, ctl)
			initHandleInit++;
			if (initHandleInit < 5) {
				setTimeout(() => {
					this.handleInit()
				}, 300);
			}
		}
		try {
			var ctl = document.getElementById('detailWriterControl');
			var _this = this;
			// 绑定控件
			window.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.setContenteditable();
				!_this.state.isClear ? _this.clearLoadCache(_this.state.fileName) : ''; // 清除加载的版本
			}
		} catch {
			this.setState({ templateErrorMes: '病历模板加载失败，请重新进入该页面' })
		}
	}

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

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

	// 将页眉设置为不可编辑
	setContenteditable = () => {
		var ctl = document.getElementById(this.editorID);
		var doc = ctl?.GetContentDocument();
		// console.log(doc)
		$(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'); // 输入框是否可见，由于版本问题，模板那边有些输入域设置了不可见，前端统一处理为可见！
		}
	}

	// 根据ID附上对映的值
	setElementTextByID = (path, data) => {
		this.AjaxLoad(path, false);
		this.setState({ insertTemplateArr: data }, () => {
			setTimeout(() => {
				this.setInputValue();
			}, 300)
		})
	}

	setInputValue = () => {
		var ctl = document.getElementById('detailWriterControl');
		let arr = this.state.insertTemplateArr && this.state.insertTemplateArr.length > 0 ? this.state.insertTemplateArr : [];
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].displayValue && arr[i].updateFlag === 'Y') {
				var result = ctl.SetElementTextByID(arr[i].fieldID, arr[i].displayValue);
			}
		}
	}

	// 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('detailWriterControl');
		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。')
		}
	}

	render() {
		let { templateErrorMes } = this.state;
		return (
			<div style={{ height: '100%', overflow: 'hidden', position: 'relative' }} className="layui-body electronic-case-template">
				<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
					// style={{width: '800px'}}
					id="detailWriterControl"
					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="Underline"
					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>}
			</div>
		)
	}
}
