<template>
	<view class="word-dictation-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>
		<scroll-view v-if="isShow" class="words-box" scroll-x :scroll-into-view="tabCurrent">
			<view v-for="(item, index) in questionData.option_list" :key="index" @click="swichMenu(index)"
				:id="'tabNum'+index" :class="['words-item',currentTab===index ? 'menu-topic-active' : '']">
				<view class="dictation-box">
					<text class="serial">{{computedQuestionNumber(index,questionData.option_number_show_mode)}}</text>
					<!-- <text>{{item.pinyin}}</text> -->
					<AudioPlay v-if="item.audio_file_id" :file-id="item.audio_file_id" :isPlaying="item.isPlaying" />
				</view>
			</view>
		</scroll-view>
		<view class="title-split"></view>
		<!-- 内容 -->
		<swiper v-if="isShowC" class="swiper-box" :current="currentTab" disable-touch
			:style="`height: ${contentRealHeight}px`">
			<swiper-item class="swiper-topic-list" v-for="(item, index) in questionData.option_list" :key="index">
				<view class="swiper-topic-area">
					<view class="dictation-content-box" v-for="(itemI,indexI) in item.pinyin_item_list" :key="indexI">
						<text class="pinyin-text">{{item.pinyin.trim().split(' ')[indexI]}}</text>
						<view class="hanzi-writer-area"
							@click="showHanziWritePop('dictation',questionData.question_id+'_'+item.mark+indexI,item.mark,item.pinyin.trim().split(' ')[indexI],indexI)">
							<SvgIcon class="character-target-bg" icon-class="hanzi-writer-bg" :size="72" />
							<img class="hanzi-writer-img" :ref="'con_'+questionData.question_id+'_'+item.mark+indexI"
								:src="imgList[item.mark+indexI]" />
						</view>
					</view>
				</view>
				<view class="reference" v-if="answer_control[questionData.question_id].isViewRightAnswer">
					<text class="reference-title">参考答案</text>
					<view class="pinyin-box">
						<text class="pinyin-text" v-for="(itemI,indexI) in item.pinyin_item_list"
							:key="indexI">{{item.pinyin.trim().split(' ')[indexI]}}</text>
					</view>
					<view class="strock-chinese-box">
						<Strockplayredline v-for="(word,indexW) in item.hz_strokes_list" :key="indexW" strokeColor="#000000"
							:class="['strock-chinese']" :play-storkes="true" :book-text="word.hz"
							:target-view="questionData.question_id+'_' + index +'_'+ indexW" :book-strokes="word.strokes" />
					</view>
				</view>
			</swiper-item>
		</swiper>
		<uni-popup ref="parentPopup" :mask-click="true">
			<view class="popup-box">
				<FreeWrite :class="['con-box']" :canvasId="'pop_'+canvas_id" :mark="item_mark" :answerIndex="answer_index"
					@saveStrock="saveStrock" :userAnswerList="returnUserAnswerList" :pinyin="pinyin_item"
					:disabled="answer_control[questionData.question_id].isReadOnly" />
			</view>
		</uni-popup>
		<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,
		computedQuestionNumber,
		answer_control,
	} from '@/pages/answer_question/common/data/common.js';
	import {
		GetFileStoreInfo,
		GetStaticResources,
		GetFileURLMap
	} from '@/api/api.js';
	import FreeWrite from '@/components/FreeWrite/FreeWrite.vue';
	import AudioPlay from '@/components/AudioPlay/AudioPlay.vue';
	import AnswerControlMixin from '@/pages/answer_question/common/data/AnswerControlMixin.js';
	export default {
		name: "word-dictation-question",
		mixins: [AnswerControlMixin],
		components: {
			FreeWrite,
			AudioPlay
		},
		props: {
			questionData: questionData,
		},
		data() {
			return {
				isEnable,
				sanitizeHTML,
				computedQuestionNumber,
				answer_control,
				currentTab: 0, //当前标签
				prevTab: 0, //上一次点击的标签
				tabCurrent: 'tabNum0', //当前标签对应页
				currentPager: 0, //当前书写汉字格
				hanzi_color: '#404040', // 描红汉字底色
				answer_list: {
					write_model: {},
				}, // 用户答题数据
				isShow: true,
				isShowC: true,
				userAnswerList: [],
				returnUserAnswerList: [], //用
				strokesList: {}, //用于临时存储笔画

				imgList: [],
				canvas_id: '',
				item_mark: '',
				pinyin_item: '',
				answer_index: 0,
				hasPlay: false,
				hz_content: '',
				hz_strokes: '',
				py_audio_file_id: '',
				strokeColorList: [],

				contentRealHeight: 0, //答题内容区域高度
			};
		},
		watch: {
			'questionData.question_id': {
				handler(val, oldVal) {
					var that = this;
					that.commonComputedAnswerControl(val);
					that.isShow = false;
					that.isShowC = false;
					that.currentTab = 0;
					that.prevTab = 0;
					that.currentPager = 0;
					that.tabCurrent = 'tabNum0';
					that.userAnswerList = [];
					// that.questionData.option_list.forEach(p => {
					// 	var strokes_content_list = [];
					// 	p.pinyin_item_list.forEach(m => {
					// 		strokes_content_list.push();
					// 	})
					// 	that.userAnswerList.push({
					// 		mark: p.mark,
					// 		strokes_content_list: strokes_content_list
					// 	});
					// })
					// console.log(that.userAnswerList);
					that.imgList = [];
					that.strokesList = {};
					if (val !== oldVal) {
						var cb = function() {
							that.handleData();
						};
						that.setUserAnswer(cb);
					}
				},
				immediate: true,
				deep: true,
			},
		},
		mounted() {
			uni.$on('_closePopup', this.closePopup);
			uni.$on('setOtherAudioPlaying', this.otherAudioPlaying);

			uni.getSystemInfo({
				success: (res) => {
					this.contentRealHeight = res.windowHeight - 340;
				}
			});
		},
		onUnload() {
			uni.$off('_closePopup', this.closePopup);
			uni.$off('setOtherAudioPlaying', this.otherAudioPlaying);
		},
		computed: {
			isViewAnalysis: function() {
				return isEnable(this.questionData.property.is_enable_analysis);
			}
		},
		methods: {
			// 初始化数据
			handleData() {
				var that = this;
				setTimeout(function() {
					that.isShow = true;
				}, 0)
				setTimeout(function() {
					that.isShowC = true;
				}, 10)

				var answer_list = [];
				this.questionData.option_list.forEach(p => {
					p.isPlaying = false;
				});
			},
			//播放当前音频的时候暂停其他音频
			otherAudioPlaying(audio_file_id, playing) {
				this.questionData.option_list.forEach(p => {
					p.isPlaying = false;
					if (p.audio_file_id == audio_file_id) {
						p.isPlaying = true;
					}
				});
				this.$forceUpdate();
			},
			//切换汉字
			swichMenu(id) {
				this.currentPager = 0;
				this.currentTab = id;
				this.tabCurrent = 'tabNum' + id;
			},
			//切换当前汉字田字格数
			prevIndex(i) {
				if (i === 0) return;
				this.currentPager--;
			},
			nextIndex(i, total) {
				if (i === total - 1) return;
				this.currentPager++;
			},
			saveStrock(mark, data, img, answerIndex) {
				if (!mark) return;
				var en = this.questionData.option_list.find(p => p.mark == mark);
				if (en == null) return;
				var learn_type = this.questionData.property.learn_type;
				var oldAnswer = this.userAnswerList.find(p => p.mark == mark);
				var hasAnswer = false;
				if (!oldAnswer) {
					oldAnswer = {
						mark: mark,
						strokes_content_list: []
					};
					var answerCount = this.questionData.property.tian_number;
					for (var i = 0; i < answerCount; i++) {
						oldAnswer.strokes_content_list[i] = '';
					}

				} else {
					hasAnswer = true;
					oldAnswer.strokes_content_list[answerIndex] = '';
				}

				if (data) {
					var curHZ = this.strokesList[mark] || {};
					var curList = curHZ[answerIndex] || [];
					curList.push(data);
					curHZ[answerIndex] = curList;
					this.strokesList[mark] = curHZ;
					var strokes_content = {
						hz: en.content.split('')[answerIndex % en.pinyin_item_list.length],
						strokes_content: JSON.stringify(curList[0]),
						strokes_image: img
					};
					oldAnswer.strokes_content_list[answerIndex] = JSON.stringify(strokes_content);
					if (!hasAnswer)
						this.userAnswerList.push(oldAnswer);
				}
				// console.log(this.userAnswerList);
				this.returnUserAnswerList = this.userAnswerList;
				var questionId = this.questionData.question_id;
				this.questionData.user_answer[questionId].isEdit = this.userAnswerList.length > 0;
				this.questionData.user_answer[questionId].answer_list = this.userAnswerList;
				const id = 'con_' + this.questionData.question_id + '_' + mark + answerIndex;
				const element = this.$refs[id];
				if (img) {
					this.$forceUpdate();
					this.$refs.parentPopup.close();
					this.imgList[mark + answerIndex] = img;
					element[0].setAttribute('src', img);
					element[0].style = "display:block";
				} else {
					element[0].setAttribute('src', '');
					element[0].style = "display:none";
				}
				// console.log('保存的', this.imgList);
			},
			setUserAnswer: function(cb) {
				// console.log('设置的', this.imgList);
				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;
					that.returnUserAnswerList = userAnswer;
					userAnswer.forEach(p => {
						if (p.strokes_content_list) {
							p.strokes_content_list.forEach((item, i) => {
								if (item == null || item.length <= 0) return;
								that.imgList[p.mark + i] = JSON.parse(item).strokes_image;
							})
						}
					});
					if (cb && typeof cb === 'function') {
						cb();
					}
				}
				this.$emit("getUserAnswer", this.questionData.question_id, callback);
			},

			//书写汉字弹窗
			showHanziWritePop(type, canvas_id, item_mark, pinyin_item, answer_index) {
				this.$refs.parentPopup.open('center');
				this.answer_index = answer_index;
				if ('write' == type) {
					canvas_id = canvas_id + this.answer_index;
				}
				this.canvas_id = canvas_id;
				this.item_mark = item_mark;
				this.pinyin_item = pinyin_item;
			},
			//关闭弹窗
			closePopup() {
				this.$refs.parentPopup.close();
			},
		},
	}
</script>
<style lang="scss" scoped>
	.word-dictation-area {
		.words-box {
			margin: 32rpx 0;

			/deep/ .uni-scroll-view-content {
				display: flex;
				column-gap: 32rpx;
			}

			.words-item {
				opacity: 0.2;

				.dictation-box {
					white-space: nowrap;
					color: #ffffff;
					background-color: $uni-color-main;
					display: flex;
					align-items: center;
					column-gap: 10rpx;
					padding: 16rpx 32rpx;
					border-radius: 40rpx;

					.serial {
						margin-top: -2rpx;
					}
				}

			}

			.menu-topic-active {
				opacity: 1;
			}
		}

		.title-split {
			height: 20rpx;
			position: relative;
			width: 109.5%;
			left: -5%;
			background: $uni-bg-color-grey;
			box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1) inset;
		}

		.swiper-box {
			margin-top: 32rpx;
			width: 100%;
			padding: 4rpx;

			.swiper-topic-area {
				width: 100%;
				display: flex;
				column-gap: 16rpx;
				row-gap: 16rpx;
				flex-wrap: wrap;

				.paint-content-box {
					display: flex;
					align-items: center;
					column-gap: 16rpx;
					row-gap: 16rpx;

					.paint-content-area {
						width: 72px;
						height: 72px;
						display: flex;
						align-items: center;
						justify-content: center;
						border: 1px solid #E81B1B;
					}
				}

				.dictation-content-box {
					display: flex;
					flex-direction: column;
					flex-wrap: wrap;
					align-items: center;
					row-gap: 16rpx;
					column-gap: 16rpx;

					.hanzi-writer-area {
						position: relative;

						.character-target-bg {
							// color: #DEDEDE;
							border: 1px solid #E81B1B;
						}

						.hanzi-writer-img {
							width: 72px;
							height: 72px;
							position: absolute;
							top: 1px;
							left: 1px;
							border: 0;
						}

						.hanzi-writer-img {
							z-index: 1;
						}
					}

					.play-handwriting-btn {
						width: 72px;
						height: 26px;
						background-color: #F6F6F6;
						border-radius: 6rpx;
						font-size: 24rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						column-gap: 16rpx;
					}
				}
			}


			.reference {
				margin: 32rpx 0;
				background-color: $uni-bg-color-grey;
				padding: 24rpx;
				display: flex;
				flex-direction: column;

				.reference-title {
					color: #4E5969;
					font-size: 28rpx;
					margin-bottom: 16rpx;
				}

				.pinyin-box {
					display: flex;
					column-gap: 16rpx;
					margin-bottom: 8rpx;

					.pinyin-text {
						width: 64px;
						text-align: center;
					}
				}

				.strock-chinese-box {
					display: flex;
					column-gap: 16rpx;

					.strock-chinese {
						border: 1px solid #e81b1b;
					}
				}

			}

		}

		.popup-box {
			padding: 24rpx;
			border-radius: 16rpx;
			background-color: #ffffff;

			.close-box {
				display: flex;
				justify-content: right;
			}
		}

		.reference {
			background-color: #f9f8f9;
			padding: 24rpx;

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

			.reference-answer {
				color: #1D2129;
				line-height: 48rpx;
				font-size: 14pt;
			}
		}
	}

	.audio-wrapper {
		margin: 0;

		/deep/ .audio-play {
			width: 16px !important;
			height: 16px !important;
		}

		/deep/ .voice-play {
			width: 16px !important;
			height: 16px !important;
		}
	}
</style>
<style>
	/deep/ uni-swiper {
		/* height: calc(100vh - 570rpx) !important; */
	}
</style>