<template>
	<div class="fill-in-the-blank">
		<!-- 显示填空后的文本 -->
		<div class="formatted-text" v-html="formattedText"></div>
		<!-- 提供与占位符数量相匹配的输入框 -->
		<template v-for="(placeholder, index) in placeholders" :key="index">
			<FillItem :value="question.reply[index]" :ref="`popup${index}Ref`" :index="index" @blur="onBlur"></FillItem>
		</template>
	</div>
</template>

<script>
  import FillItem from "./FillItem.vue";

	export default {
    components: {
      FillItem
    },
		props: {
			placeholders: { // 占位符
				type: Array,
				required: true
			},
			question: {
				type: Object,
			},
			showError: {
				type: Boolean,
				default: false
			}
		},
		methods: {
			setResult(data) {
				const {index,result} = data;
				this.question.reply[index] = result;
			}
		}
	}
	
</script>

<script module="TK" lang="renderjs">
	export default {
		props: {
			placeholders: { // 占位符
				type: Array,
				required: true
			},
			question: {
				type: Object,
			},
			showError: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				
			};
		},
		computed: {
			// 计算属性，用于生成填空后的文本
			formattedText() {
				let result = this.question.name;
				this.placeholders.forEach((placeholder, index) => {
					// 使用正则表达式全局替换占位符
					const regex = new RegExp(`\\${placeholder}`, 'g');
					result = result.replace(regex,
						`<input id="t_${this.question.stId}_${index}" readonly data-index="${index}" value="${this.question.reply[index]}" />`);
				});
				//  追加监听事件
				this.$nextTick(() => {
					this.initListener();
				})
				return result;
			},
		},
		methods: {
			onBlur(data) {
				const {index,result} = data;
				this.question.reply[index] = result;
				this.$ownerInstance.callMethod('setResult', data)
			},
			updateFn(e) {
				const str = `popup${e.target.dataset.index}Ref`;
				console.log(this.$refs[str],str)
				this.$refs[str][0].showPopup();
			},
			initListener() {
				this.question.result.forEach((item,index) => {
					document.getElementById(`t_${this.question.stId}_${index}`).addEventListener('focus', (e) => this.updateFn(e))
				})
			},
		},
	}
</script>

<style scoped>
	.fill-in-the-blank {
		width: 100%;
	}

	.formatted-text {
		margin-bottom: 10px;
		font-size: 16px;
		line-height: 1.5;
	}

	.inputs-container {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
	}

	.input-box {
		padding: 5px;
		width: 150px;
		/* 可根据需要调整宽度 */
		border: 1px solid #ccc;
		border-radius: 4px;
	}
</style>