<template>
	<div class="base-editor-wrap">
		<div :id="ids + 'btn'" class="base-editor-tools" v-show="isShowTools">
<!-- 		<div :id="ids + 'btn'" class="base-editor-tools" v-show="isShowTools" @mouseenter="isShowTools = true" @mouseleave="isShowTools = false"> -->
			<span class="select-model" @click="onSelectModal" v-if="type !== '0'">编辑</span>
			<span class="select-model btn-delete" @click="onDeleteBlock" v-if="!isAutoCreate">删除</span>
		</div>
		<p class="margin-block"></p>
		<!-- <div @mouseenter="isShowTools = true" @mouseleave="isShowTools = false"> -->
		<div >
			<div :id="ids" class="sheet-Editor" ></div>
			<div v-for="(item,index) in fixArr" :id="ids + 'fix' + index" class="sheet-Editor"></div>
		</div>

		<Modal v-model="isShowSelectModel" title="设置内容格式" width="600px" @on-ok="doSelectModel">
			<div>
				<RadioGroup v-model="curModel">
					<Radio label="1">简答题</Radio>
					<Radio label="2">作文(英)</Radio>
					<Radio label="3">作文(语)</Radio>
				</RadioGroup>
				<div style="margin-top: 20px;" v-if="curModel === '2'">
					<span style="margin-right: 15px;">行数</span>
					<InputNumber :max="10" :min="1" v-model="lineCount"></InputNumber>
				</div>
				<div style="margin-top: 20px;" v-if="curModel === '3'">
					<span style="margin-right: 15px;">字数</span>
					<InputNumber :max="10000" :min="100" v-model="wordCount"></InputNumber>
				</div>
			</div>
		</Modal>
	</div>
</template>

<script>
	import E from "wangeditor";
	import {
		PAPER_W,
		PAPER_H,
		SVG_BORDER_PROP,
		SVG_BORDER_MB,
		CONTENT_MT,
		CONTENT_ML,
		ANCHORPROP,
		CONTENT_START_X,
		CONTENT_START_Y,
		INFO_W,
		INFO_H,
		INFO_ITEM_GAP,
		INFO_ITEM_MARGIN,
		ID_LENGTH,
		INFO_LEFT_X,
		INFO_LEFT_W,
		ID_TITLE_H,
		ID_TITLE_Y,
		NUMBER_CELL_H,
		NUMBER_ITEM_W,
		NUMBER_ITEM_H,
		NUMBER_ITEM_MT,
		NUMBER_ITEM_ML,
	} from "../../utils/sheetConfig.js";
	export default {
		props: {
			ids: {
				type: String,
				default: "",
			},
			items: {
				type: Array,
				default: () => [],
			},
			type: {
				type: String,
				default: "",
			},
		},
		data() {
			return {
				preTop:0,
				fixArr:[],
				pArr:[],
				isShowTools:false,
				lineCount: 1,
				wordCount: 300,
				curModel: '1',
				isShowSelectModel: false,
				myEditor: null,
				myFixEditor: null,
				completeItems: [],
				isNewPage: false,
				pageCount: 1,
				curEditorSetting: null,
				curItemId:null
			};
		},
		methods: {
			/* 显示切换模式窗口 */
			onSelectModal() {
				this.isShowSelectModel = true
			},

			/* 删除当前富文本块 */
			onDeleteBlock() {
				console.log(this.curItemId)
				if(this.type === '1'){
					this.$store.commit('deleteItem',this.curItemId)
					this.$parent.subjectiveItems.splice(this.$parent.subjectiveItems.map(i => i.id).indexOf(this.curItemId),1)
				}
				document.getElementById(this.ids).remove()
				document.getElementById(this.ids + 'btn').remove()
				this.myEditor.destroy()
				this.myEditor = null
				this.$EventBus.$emit('doRefresh')
				this.$EventBus.$emit('deleteItem',this.type)
			},

			/* 切换富文本显示模式（简答题、语文作文、英语作文）*/
			doSelectModel() {
				console.log(this.curModel)
				let editor = this.myEditor
				editor.txt.clear()
				let allItemIds = this.$store.state.answerSheet.paperItem.item.map(i => i.id)
				let orderStr = '<p><span style="display:inline-block">' + (allItemIds.indexOf(this.curPropItem[0].id) + 1) +
					"（" + (this.curPropItem[0].score + "分）") + '</span></p>'
				let newContent = ''	
				if (this.curModel === '2') {
					let lineCount = this.lineCount
					let allHtml = ''
					let singleStr = '<span class="underline" style="display:inline;line-height:35px">' + new Array(182).fill("&nbsp;").join("") + "</span>";
					for(let i = 0 ; i < lineCount ; i++){
						allHtml += '<p>' + singleStr+ '</p>'
					}
					editor.config.height = lineCount * 35 + 40
					newContent = orderStr + allHtml
				} else if (this.curModel === '3') {
					let wordCount = this.wordCount
					let singleStr = '<span class="cell-item"></span>';
					let lines = wordCount / 18
					let allHtml = ''
					for(let i = 0 ; i < lines; i++){
						allHtml += '<p>' + singleStr.repeat(18) + '</p>'
					}
					editor.config.height = lines * 40 + 60
					newContent = orderStr + '<p><br></p>' + allHtml
				} else {
					newContent = orderStr
				}
				this.$store.commit('setEditorHeight', {
					id: this.ids,
					height: editor.config.height,
					content:newContent
				})
				setTimeout(() => {
					this.$EventBus.$emit('doRefresh')
				})
			},

			// 渲染当前富文本
			doRenderEditor(items) {
				switch (this.type) {
					case "0":
						this.doInsertComplete(items);
						break;
					case "1":
						this.doInsertSubjective(items);
						break;
					default:
						break;
				}
			},
			// 填空题型富文本框
			doInsertComplete(items) {
				let underLineSpaceCount = 45;
				let allItemIds = this.$store.state.answerSheet.paperItem.item.map(i => i.id)
				this.fixArr = []
				this.$nextTick(() => {
					this.myEditor.txt.html('<span></span>')
				})
				let totalStr = '' // 填空题总体富文本
				let lineBlankCount = 0 //总空格数
				let lineStr = '' //每一行的富文本
				// 遍历所有填空题 生成对应题目的空格
				items.forEach((item, index) => {
					item.blankCount = item.blankCount || 1
					let addStr = this.isAutoCreate ? (allItemIds.indexOf(item.id) + 1) : item.order + "";
					for (let blankIndex = 0; blankIndex < item.blankCount; blankIndex++) {
						addStr =
							addStr +
							'<span class="underline">' +
							new Array(underLineSpaceCount).fill("&nbsp;").join("") +
							"</span>";
						lineBlankCount += item.blankCount
					}
					// 如果空格数量默认渲染状态下到3 则需要换行
					if(lineBlankCount % 3 !== 0){
						lineStr += `<span class='complete-item'>${addStr}</span>`
						// 如果是最后一排 则直接渲染 不需要排满
						if(index === items.length - 1){
							lineStr = '<p>' + lineStr + '</p>'
							totalStr += lineStr
						}
					}else{
						lineStr += `<span class='complete-item'>${addStr}</span>`
						lineStr = '<p>' + lineStr + '</p>'
						totalStr += lineStr
						lineStr = ''
						lineBlankCount = 0
					}
				});
				this.$nextTick(() => {
					this.myEditor.txt.append(totalStr);
					this.myEditor.config.height = this.myEditor.$textElem.elems[0].clientHeight
					let scrollDom = this.$parent.$parent.$parent.$parent.$parent.$refs["evScroll"]
					if (!scrollDom) return
					setTimeout(() => {
						let editorDom = this.myEditor.$textElem.elems[0]
						this.pArr = Array.from(editorDom.getElementsByTagName('p'))
						let scrollDis = scrollDom.getPosition().scrollTop
						let Y = editorDom.getBoundingClientRect().top + scrollDis - 90;
						let paperH = PAPER_H;
						let lastBottomGap = 20;
						let curEditorY = Y > paperH ? +((Y % paperH).toFixed(4)) : Y;
						let curEditorH = editorDom.clientHeight;
						let leftHeight = paperH - curEditorY - lastBottomGap - SVG_BORDER_MB;
						let fixHeight = curEditorH - leftHeight + 20
						if ( curEditorY + curEditorH + lastBottomGap + SVG_BORDER_MB > PAPER_H) {
							// 如果剩余高度不满足渲染 并且需要补充的区域 则需要进行跨页处理
							if (leftHeight > 100) {
								this.$store.commit("addPage");
								let heightArr = []
								this.myEditor.config.height = leftHeight + 20;
								heightArr.push(leftHeight)
								// 如果渲染的客观题高度在这个区间 才需要在下一页添加补充作答区域 其余全部按照正常 跨页处理不需要补充作答区域
								let fixCount = Math.ceil(fixHeight / SVG_BORDER_PROP.height)
								console.log("需要处理跨页，数量为" + fixCount);
								console.log("剩余渲染高度" + fixHeight);
								for(let i = 0;i < fixCount;i++){
									this.fixArr.push(0)
										let curFixHeight = fixHeight > SVG_BORDER_PROP.height  ? SVG_BORDER_PROP.height - 30 : fixHeight
										heightArr.push(curFixHeight)
										fixHeight = fixHeight - SVG_BORDER_PROP.height
									if(i > 0) {
										console.log('fix添加页码')
										this.$store.commit("addPage");
									}
								}
								this.$nextTick(() => {
									let splitHtmlArr = this.getSplitHtml(this.pArr,heightArr)
									splitHtmlArr.forEach((curEditorContent,editorIndex) => {
										console.log('填空题富文本的分割高度',heightArr)
										console.log('填空题富文本的分割',splitHtmlArr)
										
										let editorHeight = curEditorContent.html === '' ? heightArr[editorIndex] : heightArr[editorIndex]
										// let curEditorContent = this.getSplitHtml(this.pArr,curEditorHeight)
										if(editorIndex !== 0){
											this.initFixEditor(this.ids + 'fix' + (editorIndex - 1), editorHeight, curEditorContent.html)
										}else{
											this.myEditor.txt.clear();
											this.myEditor.txt.html('<span></span>')
											this.myEditor.txt.append(curEditorContent.html);
										}
									})
								})
							} else {
								// 跨页处理不需要补充作答区域
								this.$store.commit("addPage");
								document.getElementById(this.ids).style.marginTop = (PAPER_H - curEditorY + lastBottomGap + SVG_BORDER_PROP.y) + "px";
								document.getElementById(this.ids + 'btn').style.top = (PAPER_H - curEditorY + lastBottomGap + SVG_BORDER_PROP.y + 20) + "px";
							}
						}else {
							document.getElementById(this.ids + 'btn').style.top =  "20px";
						}
					})
				});
			},

			// 渲染问答题
			doInsertSubjective(items) {
				this.$nextTick(() => {
					let scrollDom = this.$parent.$parent.$parent.$parent.$parent.$refs["evScroll"]
					if (!scrollDom) return
					let editorDom = this.myEditor.$textElem.elems[0]
					let scrollDis = scrollDom.getPosition().scrollTop
					let allItemIds = this.$store.state.answerSheet.paperItem.item.map(i => i.id)
					let subjectiveItem = items[0];
					// 拿到当前题目序号
					let itemOrder = this.isAutoCreate ? allItemIds.indexOf(subjectiveItem.id) + 1 : subjectiveItem.order;
					this.curItemId = subjectiveItem.id
					// 拿到默认序号富文本内容
					let addStr = '<p>' +  itemOrder + "（" + (subjectiveItem.score + "分）") + '</p>'; // 渲染题号
					
					// 默认简答题内容
					let defaultBrCounts = 1; // 问答题默认回答区域空行数量
					let brHtml = new Array(defaultBrCounts).fill("<p><br></p>").join("");
					this.myEditor.txt.html('<span></span>')
					
					// 如果vuex有保存 之前的文本内容 则渲染 否则按照默认只显示题号
					let curSetting = this.hasEditorSetting(this.ids)
					if (curSetting && curSetting.content) {
						this.myEditor.txt.append(curSetting.content);
					}else{
						this.myEditor.txt.append(addStr + brHtml);
					}
					
					// 如果自定义插入的是作文题 则进行对应题型渲染
					console.log('插入的主观题',subjectiveItem)
					if(subjectiveItem.maxWords > 0){
						this.myEditor.txt.clear()
						addStr = '<p>' +  itemOrder + "、 作文（" + (subjectiveItem.score + "分）") + '</p>'; 
						let newContent = ''	
						let wordCount = subjectiveItem.maxWords
						let singleStr = '<span class="cell-item"></span>';
						let lines = wordCount / 18
						let allHtml = ''
						for(let i = 0 ; i < lines; i++){
							allHtml += '<p>' + singleStr.repeat(18) + '</p>'
						}
						this.myEditor.config.height = lines * 40 + 60
						newContent = addStr + '<p><br></p>' + allHtml
						this.myEditor.txt.html(newContent);
					}else if(subjectiveItem.maxLines > 0){
						this.myEditor.txt.clear()
						addStr = '<p>' +  itemOrder + "、 作文（" + (subjectiveItem.score + "分）") + '</p>'; 
						let newContent = ''
						let lineCount = subjectiveItem.maxLines
						let allHtml = ''
						let singleStr = '<span class="underline" style="display:inline;line-height:35px">' + new Array(182).fill("&nbsp;").join("") + "</span>";
						for(let i = 0 ; i < lineCount ; i++){
							allHtml += '<p>' + singleStr+ '</p>'
						}
						this.myEditor.config.height = lineCount * 35 + 50
						newContent = addStr + allHtml
						this.myEditor.txt.html(newContent);
					}
					
					this.pArr = Array.from(editorDom.getElementsByTagName('p'))
					let scrollHeight = editorDom.scrollHeight
					setTimeout(() => {
						let isNewPage = this.$store.state.answerSheet.isNewPage;
						let lastBottomGap = 20;
						let rectTop = editorDom.getBoundingClientRect().top
						let Y = rectTop + scrollDis - 90;
						let paperH = PAPER_H;
						let curEditorY = Y > paperH ? +((Y % paperH).toFixed(4)) : Y;
						let curEditorH = editorDom.clientHeight; // 默认200px
						console.log(itemOrder, 'rectTop', rectTop);
						console.log(itemOrder, 'scrollDis', scrollDis);
						console.log(itemOrder, '当前Y', Y);
						let leftHeight = paperH - curEditorY - lastBottomGap - SVG_BORDER_MB;
						console.log(itemOrder, '高度', curEditorH)
						console.log(itemOrder, 'LEFT高度', leftHeight)
						let fixHeight = curEditorH - leftHeight + 20
						console.log(itemOrder, '需要fix的高度', fixHeight)
						// 如果 渲染当前富文本的时候 需要渲染的高度超过当前页的剩余高度 则需要进行加页处理
						if (curEditorY + curEditorH + lastBottomGap + SVG_BORDER_MB > PAPER_H) {
							// console.log(itemOrder, Y , curEditorY , curEditorH , '超出了')
							// 如果剩余高度满足渲染一部分区域 并且需要补充的区域 则需要进行跨页处理
							if (leftHeight > 100) {
								this.$store.commit("addPage");
								console.log(itemOrder, '需要增加页码')
								let heightArr = []
								this.myEditor.config.height = leftHeight + 20;
								heightArr.push(leftHeight)
								// 如果渲染的客观题高度在这个区间 才需要在下一页添加补充作答区域 其余全部按照正常 跨页处理不需要补充作答区域
								let fixCount = Math.ceil(fixHeight / SVG_BORDER_PROP.height)
								console.log(itemOrder + "需要处理跨页，数量为" + fixCount);
								console.log(itemOrder + "剩余渲染高度" + fixHeight);
								for(let i = 0;i < fixCount;i++){
									this.fixArr.push(0)
										let curFixHeight = fixHeight > SVG_BORDER_PROP.height  ? SVG_BORDER_PROP.height - 30 : fixHeight
										heightArr.push(curFixHeight)
										fixHeight = fixHeight - SVG_BORDER_PROP.height
									if(i > 0) {
										console.log('fix添加页码')
										this.$store.commit("addPage");
									}
								}
								this.$nextTick(() => {
									let splitHtmlArr = this.getSplitHtml(this.pArr,heightArr)
									splitHtmlArr.forEach((curEditorContent,editorIndex) => {
										console.log('富文本的分割高度',heightArr)
										console.log('富文本的分割',splitHtmlArr)
										
										let editorHeight = curEditorContent.html === '' ? heightArr[editorIndex] : heightArr[editorIndex]
										// let curEditorContent = this.getSplitHtml(this.pArr,curEditorHeight)
										if(editorIndex !== 0){
											this.initFixEditor(this.ids + 'fix' + (editorIndex - 1), editorHeight, curEditorContent.html)
										}else{
											this.myEditor.txt.clear();
											this.myEditor.txt.html('<span></span>')
											this.myEditor.txt.append(curEditorContent.html);
										}
									})
								})
							} else {
								// 跨页处理不需要补充作答区域
								this.$store.commit("addPage");
								console.log(itemOrder, '需要增加页码')
								document.getElementById(this.ids).style.marginTop = (PAPER_H - curEditorY + lastBottomGap + SVG_BORDER_PROP.y) + "px";
								document.getElementById(this.ids + 'btn').style.top = (PAPER_H - curEditorY + lastBottomGap + SVG_BORDER_PROP.y + 20) + "px";
							}
						} else {
							document.getElementById(this.ids + 'btn').style.top =  "20px";
						}
						this.$root.$children[0].spinShow = false;
						
						
					}, 0);
					
					
				});
			},
			
			// 跨页内容分割处理
			getSplitHtml(pArr,heightArr){
				let result = []
				heightArr.forEach(height => {
					let fillHtml = ''
					let fillHeight = 0
					let delEles = []
					pArr.forEach((pElement,index) => {
						fillHeight += (pElement.getBoundingClientRect().height + 2)
						// console.log(height)
						// console.log(fillHeight)
						if(fillHeight < height){
							// console.log('纳入',pElement.innerHTML)
							fillHtml += this.nodeToString(pElement)
							delEles.push(index)
						}
					})
					result.push({
						html:fillHtml,
						height:fillHeight
					})
					pArr = pArr.filter((i,index) => !delEles.includes(index))
				})
				return result
			},
			
			// 将NODE转换成字符串
			nodeToString ( node ) {  
			    //createElement()返回一个Element对象
			   var tmpNode = document.createElement( "div" ); 
			   //appendChild()  参数Node对象   返回Node对象  Element方法
			   //cloneNode()  参数布尔类型  返回Node对象   Element方法
			   tmpNode.appendChild( node.cloneNode( true ) );  
			   var str = tmpNode.innerHTML;  
			   tmpNode = node = null; // prevent memory leaks in IE  
			   return str;  
			  } ,
			
			define({
				editor,
				prop,
				change,
				validate
			}) {
				if (typeof validate != "function") {
					validate = function(value) {
						return {
							valid: true, // 验证的结果。true: 验证通过；false: 验证失败。
							data: value, // 处理后的值，不需要处理直接返回即可
						};
					};
				}
				let temp = editor.config[prop];
				Object.defineProperty(editor.config, prop, {
					enumerable: true,
					configurable: true,
					get: function() {
						return temp;
					},
					set: function(value) {
						const {
							valid,
							data
						} = validate(value);
						if (valid && data !== temp) {
							temp = data;
							change(temp);
						}
						return temp;
					},
				});
			},

			// 拖拽改变编辑器的高度
			dragReSize(editor,curId) {
				let that = this
				// 将一个 HTML 字符串转换为由 wangEditor.$（一个类 jQuery 的东东） 包裹的实例对象
				const reel = E.$(
					'<div style="position: absolute;bottom: 0;left: 0;width: 100%;background-color: none;cursor: n-resize;border-top: 3px solid transparent;"></div>'
				);
				// 将这个实例添加到 wangEditor 的编辑区容器中
				editor.$textContainerElem.append(reel); // 添加鼠标事件
				reel.on("mousedown", function mousedown(down) {
					let last = down; // 鼠标移动，更新 wangEditor 实例中的 height 配置项
					function mousemove(move) {
						editor.config.height += move.clientY - last.clientY;
						last = move;
					} // 在鼠标弹起事件中移除事件监听
					function mouseup() {
						document.removeEventListener("mousemove", mousemove);
						document.removeEventListener("mouseup", mouseup);
						let editorDom = that.myEditor.$textElem.elems[0]
						that.preTop = editorDom.getBoundingClientRect().top
						// 如果是补充区域 则需要把高度计算到主区域 进行重新渲染
						if(curId.includes('fix')){
							let mainEditorId = curId.split('fix')[0]
							let totalHeight = 0
							that.fixArr.forEach((i,index) => {
								totalHeight += document.getElementById(mainEditorId + 'fix' + index).clientHeight
							})
							totalHeight +=  document.getElementById(mainEditorId).clientHeight
							that.$store.commit('setEditorHeight', {
								id: mainEditorId,
								height: totalHeight,
							})
							that.$store.commit('setEditorHeight', {
								id: curId,
								height: editor.config.height,
								content:editor.txt.html()
							})
						}else{
							that.$store.commit('setEditorHeight', {
								id: curId,
								height: editor.config.height,
								content:editor.txt.html()
							})
						}
						let scrollDom = that.$parent.$parent.$parent.$parent.$parent.$refs["evScroll"]
						localStorage.setItem('scrollDis',scrollDom.getPosition().scrollTop)
						
						that.$EventBus.$emit('doRefresh')
					}
					// 将鼠标事件绑定到 document 上
					document.addEventListener("mousemove", mousemove);
					document.addEventListener("mouseup", mouseup);
				});
			},

			equalAltitude({
				editor,
				max,
				min
			}) {
				editor.config.onchange = function() {
					const last = Array.prototype.slice.call(
						editor.$textElem.elems[0].children,
						-1
					)[0];
					if (last) {
						const height = last.offsetTop + last.clientHeight;
						// editor.config.height = editor.config.height = height < min ? min : height > max ? max : height
					}
				};
			},
			
			encodeHtml(str){
			    var encodedStr = "" ;
			    if (str=="") return encodedStr ;
			    else {
			        for (var i = 0 ; i < str.length ; i ++){
			            encodedStr += "&#" + str.substring(i, i + 1).charCodeAt().toString(10) + ";" ;
			        }
			    }
			    return encodedStr ;
			},
			/* 初始化当前富文本编辑器 */
			initEditor(curId, isFix) {
				const editor = new E("#" + curId);
				editor.config.height = this.type === "0" ? "" : 200;

				this.define({
					editor: editor,
					prop: "height",
					change(value) {
						editor.$textContainerElem.css("height", `${value}px`);
					},
					validate(value) {
						const data = parseFloat(value);
						return {
							valid: !isNaN(data), // 数据校验：设置的值只能为数字
							data: data, // 此处返回的是被处理后的数据
						};
					},
				});
				// 因为动态更新编辑器高度涉及到 wangEditor 的 onchange 回调，
				// 而 onchange 必须在 create 前的配置才有效，所以放在 create 前。
				this.equalAltitude({
					editor: editor
				});

				editor.config.menus = [
					"bold",
					"fontSize",
					"fontName",
					"italic",
					"underline",
					"strikeThrough",
					"image",
					"indent",
					"lineHeight",
					"foreColor",
					"backColor",
					"undo",
				];

				editor.config.onfocus = (html) => {
					document
						.getElementById(curId)
						.getElementsByClassName("w-e-toolbar")[0].style.display = "flex";
					if (!isFix) {
						this.isShowTools = true
					}
				};

				editor.config.onblur = (html) => {
					let scrollHeight = editor.$textElem.elems[0].scrollHeight
					let editorHeight = editor.$textElem.elems[0].clientHeight
					console.log(scrollHeight)
					console.log(editorHeight)
					if(scrollHeight > editorHeight){
						editor.config.height = scrollHeight > 200 ? scrollHeight : 200
						this.$EventBus.$emit('doRefresh')
					}
					
					document.getElementById(curId) && (document.getElementById(curId).getElementsByClassName(
						"w-e-toolbar")[0].style.display = "none");
					this.$store.commit('setEditorHeight', {
						id: this.ids,
						height: editor.config.height,
						content: html
					})
					if (!isFix) {
						this.isShowTools = false
					}
				};
				editor.config.focus = false;
				editor.config.showFullScreen = false;
				editor.config.placeholder = "";
				editor.config.uploadImgShowBase64 = true
				let curSetting = this.hasEditorSetting(curId)
				if (curSetting && Object.keys(curSetting).length) {
					console.log('从vuex读取的数据', curId, curSetting.height)
					editor.config.height = curSetting.height
				}
				editor.create();
				this.dragReSize(editor,curId);
				if (!isFix) {
					this.myEditor = editor;
				} else {
					this.myFixEditor = editor;
				}
			},
			
			/* 初始化补充富文本编辑器 */
			initFixEditor(curId,height,content){
				console.log('补充编辑器',height)
				const editor = new E("#" + curId);
				editor.config.height = height;
				editor.config.menus = [
					"bold",
					"fontSize",
					"fontName",
					"italic",
					"underline",
					"strikeThrough",
					"image",
					"indent",
					"lineHeight",
					"foreColor",
					"backColor",
					"undo",
				];
				this.define({
					editor: editor,
					prop: "height",
					change(value) {
						editor.$textContainerElem.css("height", `${value}px`);
					},
					validate(value) {
						const data = parseFloat(value);
						return {
							valid: !isNaN(data), // 数据校验：设置的值只能为数字
							data: data, // 此处返回的是被处理后的数据
						};
					},
				});
				// 因为动态更新编辑器高度涉及到 wangEditor 的 onchange 回调，
				// 而 onchange 必须在 create 前的配置才有效，所以放在 create 前。
				this.equalAltitude({
					editor: editor
				});
				editor.config.onfocus = (html) => {
					document
						.getElementById(curId)
						.getElementsByClassName("w-e-toolbar")[0].style.display = "flex";
				};
				editor.config.onblur = (html) => {
					let scrollHeight = editor.$textElem.elems[0].scrollHeight
					console.log(editor.config.height)
					console.log(scrollHeight)
					if(scrollHeight > editor.config.height){
						editor.config.height = scrollHeight > 200 ? scrollHeight : 200
						// this.$EventBus.$emit('doRefresh')
					}
					document.getElementById(curId) && (document.getElementById(curId).getElementsByClassName(
						"w-e-toolbar")[0].style.display = "none");
					this.$store.commit('setEditorHeight', {
						id: curId,
						height: editor.config.height,
						content: html
					})
				};
				document.getElementById(curId).style.marginTop = (SVG_BORDER_MB) * 2  + "px";
				editor.config.focus = false;
				editor.config.showFullScreen = false;
				editor.config.placeholder = "";
				editor.config.uploadImgShowBase64 = true
				editor.create();
				editor.txt.html('<span></span>')
				editor.txt.append(content)
				this.dragReSize(editor,curId);
			},
		},
		mounted() {
			this.initEditor(this.ids);
		},
		computed: {
			// 是否需要展示跨页展示的富文本框
			isShowFixEditor() {
				return (ids) => {
					let allItemIds = this.$store.state.answerSheet.paperItem.item.map(i => i.id)
					let itemOrder = allItemIds.indexOf(this.curPropItem[0].id) + 1;
					return this.$store.state.answerSheet.needFixArr.includes(+itemOrder);
				};
			},
			// 是否有vuex设定高度值
			hasEditorSetting() {
				return ids => {
					return this.$store.state.answerSheet.editorInfos[ids]
				}
			},
			// 是否为根据试卷自动生成的答题卡
			isAutoCreate(){
				return this.$store.state.answerSheet.isAutoCreate
			}
		},
		watch: {
			items: {
				handler(n, o) {
					if (n.length) {
						console.log(n)
						let objectiveArr = ["complete"];
						this.completeItems = n.filter((item) =>
							objectiveArr.includes(item.type)
						);
						this.curPropItem = this.type === "0" ? this.completeItems : n;
						this.doRenderEditor(this.curPropItem);
						if(this.type !== "0"){
							// setTimeout(() => {
							// 	if(n[0].maxWords > 0){
							// 		console.log('语文作文',n.maxWords)
							// 		this.wordCount = n[0].maxWords
							// 		this.curModel = '3'
							// 		this.doSelectModel()
							// 	}else if(n[0].maxLines > 0){
							// 		console.log('英语作文',n.maxLines)
							// 		this.lineCount = n[0].maxLines
							// 		this.curModel = '2'
							// 		this.doSelectModel()
							// 	}
							// },3000)
						}
					}
				},
				immediate: true,
			},
		},
	};
</script>

<style lang="less">
	.base-editor-wrap {
		position: relative;

		.margin-block {
			content: '';
			display: block;
			width: 100%;
			height: 10px;
			background: transparent;
		}

		.base-editor-tools {
			position: absolute;
			right: 90px;
			top: 20px;
			z-index: 9999;
			// display: none;
		}

		.select-model {
			font-size: 12px;
			background-color: #00a43a;
			color: #fff;
			margin-right: 5px;
			padding: 4px 10px;
			border-radius: 4px;
			cursor: pointer;
		}

		.btn-delete {
			background-color: orangered;
		}
	}


	.sheet-Editor {
		position: relative;
		width: 590px;
		margin: 0 auto;
		border: 1.2px solid #000 !important;

		.cell-item {
			display: inline-block;
			width: 32.4px;
			height: 32.4px;
			border: 1px solid;
			margin-right: -1px;
			pointer-events: none;
			cursor: none;
		}

	}

	.sheet-Editor .w-e-toolbar {
		display: none;
		position: absolute;
		top: -32px;
		left: -1px;
		width: 590px;
		border: 1px solid #000 !important;
		border-bottom: none !important;
	}

	.sheet-Editor .w-e-text-container {
		border: none !important;
		z-index: 1 !important;
		// height: auto !important;
		// min-height: 100px !important;
	}

	.sheet-Editor .w-e-text {
		padding: 10px;
		font-size: 12px;
		font-family: "Times New Roman", "宋体";
		overflow: auto !important;
		
		&::-webkit-scrollbar{
			display: none;
		}
		
		// p::after{
		// 	content: '↩\A';
		// 	white-space: pre-wrap;
		// 	color: #aaa;
		// 	position: absolute;
		// }
	}

	.sheet-Editor .w-e-toolbar .w-e-menu {
		width: 30px;
		height: 30px;
	}

	.outerBox {
		border: 1px solid #000;
		width: 590px;
		height: 100px;
		margin: 0 auto 20px auto;
	}

	.sheet-Editor .underline {
		/* text-decoration: underline; */
		border-bottom: 1px solid #333;
		margin: 10px;
		display: inline-block;
	}

	.sheet-Editor .complete-item {
		margin: 0 4px;
		display: inline-block;
	}
</style>
