<template>
	<view v-if="question" class="ezy-yingyu-danxuan-box">
		<!-- 标题区域 -->
		<view class="yingyu-danxuan-title"></view>
		<view v-html="data.name">
		</view>
		<!-- 选项区域 -->
		<view v-for="(item,index) in data.contents" class="yingyu-danxuan-option-box" :key="index">
			<text class="option-change">{{item.number}}</text>
			<text class="option-question">{{item.neirong}}</text>
			<i class="yingyu-canplay-img" @click="audioCreat(item,index)"></i>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		watch
	} from 'vue';
	import {
		useQuestionTools
	} from "../useQuestionTools"

	import textReplaceIconVue from './textReplaceIcon.vue'

	const {
		getLetterByIndex
	} = useQuestionTools();

	const props = defineProps({
		question: {
			type: Object,
		},
		showError: {
			type: Boolean,
			default: false
		},
		placeholders: { // 占位符
			type: Array,
			required: true
		},
		code: {
			type: String,
		}
	})
	const data = reactive({
		name: '', //题干数据
		contents: [], // 选项数据
	})
	watch(() => props.question, (val) => formatData(val), {
		immediate: true
	})

	function formatData(val) {

		if (val) {
			data.name = val.name;
			data.contents = val.optList.map((item, index) => {

				return {
					neirong: item.neirong,
					audio: item.audio,
					number: getLetterByIndex(index)
				}
			})
		}
	}
	let audioContext = null;
	let isPlaying = false;
	let currentIndex = -1;


function initAudioContext() {
  if (!audioContext) {
    audioContext = uni.createInnerAudioContext();
    
    // 监听音频播放状态
    audioContext.onPlay(() => {
      isPlaying = true;
      console.log('音频开始播放');
    });
    
    audioContext.onPause(() => {
      isPlaying = false;
      console.log('音频暂停播放');
    });
    
    audioContext.onStop(() => {
      isPlaying = false;
      console.log('音频停止播放');
    });
    
    audioContext.onEnded(() => {
      isPlaying = false;
      console.log('音频播放结束');
    });
  }
}
function playAudio(src) {
  if (!audioContext) {
    initAudioContext();
  }
  audioContext.src = src;
  audioContext.play();
}
function audioCreat(item, index) {
  // 如果 index 变化了，或者当前没有音频在播放，就播放新音频
  if (index !== currentIndex || !isPlaying) {
    // 如果之前有音频在播放，先暂停
    if (isPlaying) {
      audioContext.pause();
    }
    // 更新当前索引和播放状态
    currentIndex = index;
    playAudio(item.audio);
  } else {
    // 如果 index 没变化且音频正在播放，就暂停音频
    if (isPlaying) {
      audioContext.pause();
    } else {
      // 如果 index 没变化但音频没播放，就播放音频
      playAudio(item.audio);
    }
  }
}
</script>