<template>
  <view class="word-view-page">
    <view class="icon-title-navBar-box">
      <view @click="handleBack" class="nav-bar-icon"></view>
      <text class="nav-bar-title">学习</text>
    </view>
    <view class="word-view-border">
      <template v-for="item in data.wordList">
        <mainCardVue :active-word="data.activeWord" :pageData="data" :active-words="activeWords"
                     @play-audio="handlePlayAudio" @goXiangjie="goXiangjie" @swiper-change="handleSwiperChange"
					 @stop-audio="handleStopAudio"
                     :is-playing="isAudioPlaying" v-if="item.id == data.activeId" :key="item.id">
        </mainCardVue>
      </template>
    </view>
    <view class="word-view-bottom">
      <view class="bottom-btn-box">
        <ezyActiveVue class="ezy-btn-active word-view-btn" @click="prevWord" v-if="!isFirst&&isLearnRecord!=0">上一词</ezyActiveVue>
		<view v-else></view>
        <ezyActiveVue class="ezy-btn-active word-view-btn" @click="nextWord" v-if="!isLast&&isLearnRecord!=0">下一词</ezyActiveVue>
        <ezyActiveVue class="ezy-btn-active word-view-btn" v-if="isLast&&isLearnRecord!=0" @click="handleComplete">完成</ezyActiveVue>
      </view>
    </view>
  </view>
</template>

<script setup>
import mainCardVue from "./components/mainCard.vue";
import {
  ref,
  reactive,
  computed,
  nextTick,
  onUnmounted
} from "vue";
import {
  onLoad
} from "@dcloudio/uni-app";
import * as httpApi from "@/api/chaojidanci.js"
import {
  useAudioCache,
  audioPlayer
} from "./components/useAudio.js"
import cacheManager from "@/utils/cacheManager";
import ezyActiveVue from "@/components/ezyActive/ezyActive.vue";

const {
  cacheAudio,
  clearAudioCache
} = useAudioCache();

const AudioP = new audioPlayer();
const isLearnRecord = ref(null)
const isLearnStatus = ref(null)
const isAudioPlaying = ref(false) // 音频播放状态
// 监听音频播放事件
uni.$on('danci-audio-play', updateAudioPlayingTrue)
uni.$on('danci-audio-ended', updateAudioPlayingFalse)

onUnmounted(() => {
  uni.$off('danci-audio-play', updateAudioPlayingTrue)
  uni.$off('danci-audio-ended', updateAudioPlayingFalse)
})

function updateAudioPlayingFalse() {
  isAudioPlaying.value = false
}

function updateAudioPlayingTrue() {
  isAudioPlaying.value = true
}

function handleSwiperChange(index) {
  return false
  // 客户暂时不要
  if (isAudioPlaying.value) return; // 如果正在播放，不允许切换

  // 无论切换到哪个页面，都播放单词的主发音（yinpin）
  if (data.activeWord && data.activeWord.yinpin) {
    handlePlayAudio({
      url: data.activeWord.yinpin,
      code: 'swiper-auto-play'
    });
  }
}

function courseBjFun() {
  return 'static/images/course/course-cjdc-bj.png'
}

function chunkArray(arr, chunkSize) {
  const result = [];
  for (let i = 0; i < arr.length; i += chunkSize) {
    result.push(arr.slice(i, i + chunkSize));
  }
  return result;
}

const data = reactive({
  danyuanId: null, // 节/单元ID
  activeId: null, // 当前单词
  wordList: [], // 单词列表
  arrayList: [], // 整合数据
  activeWord: null, // 单词详情数据
  collectFlag: 0, // 收藏状态
  subjectId: null, // 学科ID
  levelId: null, // 等级
  typeId: null, // 类型
  tipFlag: null, // 提示
  youkeZhangId: null, // 章ID
  isLearnStatus: null, // 学习记录状态
})

onLoad(({
          danyuanId,
          wordId,
          subjectId,
          levelId,
          typeId,
          tipFlag,
          isLearnStatus,
        }) => {
  data.danyuanId = danyuanId;
  isLearnRecord.value = danyuanId;
  data.activeId = wordId;
  data.isLearnStatus = isLearnStatus;
  data.subjectId = subjectId;
  data.levelId = levelId;
  data.typeId = typeId;
  data.tipFlag = tipFlag;
  // 获取单词列表数据
  initWordInfo();
  // 清理过期文件
  clearAudioCache();
})

// 是否是最后一题
const isLast = computed(() => {
  if (!data.wordList.length) {
    return false
  }
  return data.activeId == data.wordList[data.wordList.length - 1].id;
})
const isFirst = computed(() => {
  if (!data.wordList.length) {
    return false
  }
  return data.activeId == data.wordList[0].id;
})
const activeWords = computed(() => {

  if (!data.activeId) {
    return null
  }
  return data.arrayList.find(item => item.some(cit => cit.id == data.activeId))
})

function nextWord() {
  const index = data.wordList.findIndex(item => item.id == data.activeId);
  if (index < data.wordList.length - 1) {
    uni.redirectTo({
      url: `/pages/chaojidanci/newEnglish/index?danyuanId=${data.danyuanId}&wordId=${data.wordList[index + 1].id}`
    })
  }
}

function prevWord() {
  const index = data.wordList.findIndex(item => item.id == data.activeId);
  if (index > 0) {
    uni.redirectTo({
      url: `/pages/chaojidanci/newEnglish/index?danyuanId=${data.danyuanId}&wordId=${data.wordList[index - 1].id}`
    })
  }
}

function handleBack() {
  // 返回单词列表
  uni.navigateBack()
}

function handleComplete() {
  // 返回岛
  uni.switchTab({
    url: `/pages/chanpinneirong/index`
  })
}

function initWordInfo() {
  httpApi.getWordInfo({
    danyuanId: data.danyuanId,
    wordId: data.activeId
  }).then(res => {
    data.activeWord = res.data;
    data.wordList = res.data.danciList; // 单词组
    data.collectFlag = res.data.collectFlag; // 收藏状态
    if (data.wordList.length) {
      data.arrayList = chunkArray(data.wordList, 5); // 将1维单词数组转换为2维数组
    }
    handleCacheAudio()
  })
}

// 新增自动播放功能
const autoPlayAudio = async () => {
  // 等待数据加载完成
  await nextTick();

  // 检查是否有单词发音数据
  if (data.activeWord && data.activeWord.yinpin) {
    // 延迟500ms确保音频已缓存
    setTimeout(() => {
      handlePlayAudio({
        url: data.activeWord.yinpin,
        code: 'auto-play' // 特殊标记，区分自动播放
      });
    }, 500);
  }
};

function goXiangjie() {

  uni.redirectTo({
    url: `/pages/chaojidanci/newEnglish/components/xiangjie?levelId=${data.levelId}&typeId=${data.typeId}&subjectId=${data.subjectId}&tipFlag=${data.tipFlag}&wordId=${data.activeId}&youkeZhangId=${data.youkeZhangId}&danyuanId=${data.danyuanId}`
  })
}

function handleCacheAudio() {

  const arr = []
  // yinpin
  arr.push(data.activeWord.yinpin);
  // yinjie
  data.activeWord.yinjie.forEach(item => {
    arr.push(item.yinpin)
  })
  // pindu
  data.activeWord.pindu.forEach(item => {
    arr.push(item.yinpin)
  })
  // 缓存音频
  arr.map(item => cacheAudio(item));
  // console.log('arr',arr)
}

async function handlePlayAudio({
                                 url,
                                 code
                               }) {
  console.log('播放', url)
  console.log('播放', code)
  const cachedPath = await cacheAudio(url);
  if (cachedPath && cachedPath.includes('.mp3')) {
    // console.log('地址：', cachedPath)
    AudioP.play(cachedPath, code);
  } else {
    uni.showToast({
      title: '音频加载失败',
      icon: 'none'
    });
  }
}

function handleStopAudio() {
  AudioP.stop();
  isAudioPlaying.value = false;
  uni.$emit('danci-audio-ended');
}
</script>

<style>

</style>