<template>
	<!-- 填空题 -->
	<view class="fill-area" v-model="questionData">
		<view class="question_title">
			<text class="question_number">
				{{ questionNumberEndIsBracket(questionData.property.question_number) }}
			</text>
			<text class="question_stem" v-html="sanitizeHTML(questionData.stem)"
				:ref="'richText-1-1'+questionData.question_id"
				@longpress="previewByRichTextImg(-1,-1,questionData.question_id)"></text>
		</view>
		<view class="description"
			v-if="isEnable(questionData.property.is_enable_description)&&questionData.description.length > 0"
			v-html="sanitizeHTML(questionData.description)" :ref="'richText-2-2'+questionData.question_id"
			@longpress="previewByRichTextImg(-2,-2,questionData.question_id)">
		</view>
		<view class="word-select-fill"
			v-if="isEnable(questionData.property.is_enable_word_select_fill)&&questionData.word_select_fill.length > 0">
			<text v-for="(text, i) in wordSelectFillList" :key="i" class="word-select-fill-item"
				:style="{ color: text_color_list[i] }" @click="selectedDescription(text,i)">
				{{ text }}
			</text>
		</view>
		<view class="model-essay-area" v-if="questionChanged">
			<view class="model-essay" v-for="(item,i) in questionData.model_essay" :key="i">
				<template v-for="(li, j) in item">
					<text v-if="li.type === 'text'" :key="j" v-html="sanitizeHTML(li.content)"></text>
					<input v-if="li.type === 'input'" :key="j" v-model="li.content" @blur="saveUserAnswer(li.mark)"
						:style="{ width: Math.max(160, li.content.length * 24 * 2) + 'rpx' }"
						:class="[...computedAnswerClass(li.mark)]"
						:disabled="answer_control[questionData.question_id].isReadOnly" />
					<input v-show="computedAnswerText(li.mark).length > 0" :key="`answer-${j}`" class="right-answer"
						:value="computedAnswerText(li.mark)" :disabled="true"
						:style="{ width: Math.max(160, computedAnswerText(li.mark).length * 24 * 2) + 'rpx' }" />
					</text>
				</template>
			</view>
		</view>
		<view class="reference" v-if="isViewReference&&answer_control[questionData.question_id].isViewRightAnswer">
			<text class="reference-title">参考答案</text>
			<text class="reference-answer">{{questionData.reference_answer}}</text>
		</view>
		<view class="reference" v-if="isViewAnalysis&&answer_control[questionData.question_id].isViewRightAnswer">
			<text class="reference-title">解析</text>
			<text class="reference-answer" v-html="sanitizeHTML(questionData.analysis)"
				:ref="'richText-3-3'+questionData.question_id"
				@longpress="previewByRichTextImg(-3,-3,questionData.question_id)">
			</text>
		</view>
	</view>
</template>
<script>
	import {
		questionData,
		sanitizeHTML,
		isEnable,
		answer_control,
		addTone,
	} from '@/pages/answer_question/common/data/common.js';
	import AnswerControlMixin from '@/pages/answer_question/common/data/AnswerControlMixin.js';
	export default {
		name: "fill-question",
		mixins: [AnswerControlMixin],
		props: {
			questionData: questionData
		},
		data() {
			return {
				sanitizeHTML,
				isEnable,
				answer_control,
				addTone,
				select_text_mark: '',
				text_color_list: [],
			};
		},
		created() {},
		watch: {
			'questionData.question_id': {
				handler(val) {
					this.setUserAnswer();
				},
				immediate: true,
				deep: true
			},
			questionData: {
				handler(val) {
					this.$forceUpdate();
				},
				immediate: true,
				deep: true
			},
		},
		computed: {
			wordSelectFillList() {
				return this.questionData.word_select_fill.split(/\s+/);
			},
			questionChanged: function() {
				this.setUserAnswer();
				return true;
			},
			isViewReference: function() {
				//非选词填空,有参考答案
				return !isEnable(this.questionData.property.is_enable_word_select_fill);
			},
			isViewAnalysis: function() {
				return isEnable(this.questionData.property.is_enable_analysis);
			}
		},
		methods: {
			selectedDescription(text, index) {
				if (!this.select_text_mark) return;
				var _inputArr = this.questionData.model_essay.map(p => {
					return p.find(x => x.mark == this.select_text_mark)
				});
				if (!_inputArr || _inputArr.length == 0) return;
				_inputArr.find(p => p).content = text;
				this.text_color_list.forEach((color, m) => {
					this.$set(this.text_color_list, m, '#000000');
				});
				this.$set(this.text_color_list, index, '#306eff');
				this.saveUserAnswer(this.select_text_mark);
			},
			//填写答案后保存答案
			saveUserAnswer(mark) {
				var that = this;
				that.select_text_mark = mark;
				var questionId = that.questionData.question_id;
				this.questionData.model_essay.forEach(p => {
					p.filter(m => m.type === 'input').forEach(x => {
						if (!x.mark) return false;
						that.handleTone(mark, x.content);
						var index = that.questionData.user_answer[questionId].answer_list.findIndex(n => n.mark == x.mark)
						if (index > -1)
							that.questionData.user_answer[questionId].answer_list.splice(index, 1);
						that.questionData.user_answer[questionId].answer_list.push({
							mark: x.mark,
							value: x.content
						})
					})
				})

				this.questionData.user_answer[questionId].isEdit = true;
				var ansed = this.questionData.user_answer[questionId].answer_list;
				this.questionData.user_answer[questionId].is_fill_answer = ansed.filter(p => p.value).length > 0;
				this.questionData.user_answer[questionId].content = JSON.stringify(ansed);
				// this.questionData.user_answer[questionId].answer_list = ansed;
				this.$set(this.questionData.user_answer[questionId], 'answer_list', ansed);

				this.$emit("setSubAnswer", this.questionData.user_answer[questionId], questionId);
			},
			//加声调
			handleTone(mark, value) {
				if (!/^[a-zA-Z0-9\s]+$/.test(value)) return;
				var _inputArr = this.questionData.model_essay.map(p => {
					return p.find(x => x.mark == this.select_text_mark)
				});
				if (!_inputArr || _inputArr.length == 0) return;
				_inputArr.find(p => p).content = value
					.trim()
					.split(/\s+/)
					.map((item) => {
						return this.handleToneValue(item);
					})
					.map((item) =>
						item.map(({
							number,
							con
						}) => (number && con ? addTone(Number(number), con) : number || con || '')),
					)
					.filter((item) => item.length > 0)
					.join(' ');
			},
			handleToneValue(valItem) {
				let numList = [];
				if (/[A-Za-zü]+\d/g.test(valItem)) {
					valItem.split('').forEach((item, i) => {
						if (/\d/.test(item)) {
							let numIndex = numList.length === 0 ? 0 : numList[numList.length - 1].index;
							let con = valItem.substring(numIndex, i).replace(/\d/g, '');
							numList.push({
								number: item,
								con,
							});
						}
					});
				} else {
					numList = [];
				}
				return numList.length === 0 ? [{
					con: valItem
				}] : numList;
			},
			setUserAnswer: function() {
				var that = this;
				var callback = function() {
					var userAnswer = [];
					var questionId = that.questionData.question_id;
					var _ua = that.questionData.user_answer[questionId];
					if (_ua && _ua.answer_list && _ua.answer_list.length > 0)
						userAnswer = _ua.answer_list;

					if (userAnswer.length == 0) return;

					that.questionData.model_essay.forEach(p => {
						p.forEach(x => {
							if (!x.mark) return false;
							var en = userAnswer.find(y => y.mark == x.mark)
							if (!en) return false;
							x.content = en.value;
						})
					})
				}
				if (that.questionData.isSubSub) {
					callback();
				} else {
					this.$emit("getUserAnswer", this.questionData.question_id, callback);
				}
			},
			computedAnswerClass(mark) {
				var question_id = this.questionData.question_id;
				var cur = this.commonComputedAnswerControl(question_id);
				if ((!cur.isJudgeAnswer && !cur.isViewRightAnswer) || this.isViewReference) {
					return '';
				}
				let classList = [];
				let selectOption = this.questionData.user_answer[question_id].answer_list.find((item) => item.mark ===
					mark); // 是否已选中的选项
				let answerOption = this.questionData.answer.answer_list.find((item) => item.mark === mark); // 是否正确的选项
				if (!selectOption) return '';
				let selectValue = selectOption.value;
				let answerValue = answerOption.value;
				let type = answerOption.type;

				let isRight =
					(type === 'only_one' && selectValue === answerValue) ||
					(type === 'any_one' && answerValue.split('/').includes(selectValue));

				if (cur.isJudgeAnswer) {
					isRight ? classList.push('right') : classList.push('wrong');
				}

				if (cur.isViewRightAnswer && !isRight) {
					classList.push('show-right-answer');
				}
				return classList;
			},
			computedAnswerText(mark) {
				if (!mark) return '';
				var question_id = this.questionData.question_id;
				var cur = this.commonComputedAnswerControl(question_id);
				if (!cur.isViewRightAnswer || this.isViewReference) return '';
				let selectOption = this.questionData.user_answer[question_id].answer_list.find((item) => item.mark ===
					mark); // 是否已选中的选项
				let answerOption = this.questionData.answer.answer_list.find((item) => item.mark === mark); // 是否正确的选项
				if (!selectOption) {
					return `（${answerOption.value}）`;
				};
				let selectValue = selectOption.value;
				let answerValue = answerOption.value;
				let type = answerOption.type;
				let isRight =
					(type === 'only_one' && selectValue === answerValue) ||
					(type === 'any_one' && answerValue.split('/').includes(selectValue));
				if (isRight) return '';
				return `（${answerValue}）`;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.fill-area {
		.word-select-fill {
			display: flex;
			column-gap: 16rpx;
			row-gap: 16rpx;

			.word-select-fill-item {
				padding: 12rpx 16rpx;
				background-color: #E9EDF7;
				font-size: 32rpx;
				border-radius: 8rpx;
			}
		}

		.model-essay-area {
			margin: 32rpx 0;
			line-height: 64rpx;
			font-size: $font-size-serial;
			color: #1D2129;

			.model-essay {
				/deep/ uni-input {
					display: inline-block;
					border-bottom: 1px solid #1D2129;
					text-align: center;
					margin: 0 8rpx;
					margin-top: -8rpx;
					height: 72rpx;
					vertical-align: middle;
					font-size: $font-size-serial;

					&.right {
						color: $right-color;
					}

					&.wrong {
						color: $error-color;
					}
				}

				.right-answer {
					margin-left: -8rpx;
				}
			}
		}

		.reference {
			margin: 32rpx 0;
			background-color: $uni-bg-color-grey;
			padding: 24rpx;
			font-size: 28rpx;

			.reference-title {
				display: block;
				line-height: 64rpx;
				color: #4E5969;
			}

			.reference-answer {
				color: #1D2129;
				line-height: 48rpx;
			}
		}
	}
</style>