<template>
 <view class="word-view-page" :style="{backgroundImage: 'url(' + courseBjFun() + ')'}">
  <view class="icon-title-navBar-box">
   <view @click="handleBack" class="nav-bar-icon"></view>
   <text class="nav-bar-title">学习</text>
  </view>
  <view class="ezy-tab-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"
		:is-playing="isAudioPlaying" v-if="item.id == data.activeId" :key="item.id">
	   </mainCardVue>
	  </template>
  </view>
  <view class="word-view-bottom">
   <view class="collect-btn" v-if="userCode != 'Visitor'" @click="handleShouCang">
    <icon :class="{active: data.collectFlag}"></icon>
    <view>收藏</view>
   </view>
   <view class="bottom-btn-box">
    <view class="word-view-btn" @click="prevWord" v-if="!isFirst&&isLearnRecord!=0">上一词</view>
    <view class="word-view-btn" @click="nextWord" v-if="!isLast&&isLearnRecord!=0">下一词</view>
    <view class="word-view-btn" v-if="isLast&&isLearnRecord!=0" @click="handleComplete">完成</view>
   </view>
  </view>
 </view>
</template>

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

 const userCode = getUserIdentity();

 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', (code) => {
  isAudioPlaying.value = true
 })

 uni.$on('danci-audio-ended', () => {
  isAudioPlaying.value = false
 })

 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({
  jieId: 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(({
  jieId,
  wordId,
  subjectId,
  levelId,
  typeId,
  tipFlag,
  isLearnStatus,
  youkeZhangId
 }) => {
  data.jieId = jieId;
  isLearnRecord.value = jieId;
  data.activeId = wordId;
  data.isLearnStatus = isLearnStatus;
  data.subjectId = subjectId;
  data.levelId = levelId;
  data.typeId = typeId;
  data.tipFlag = tipFlag;
  data.youkeZhangId = youkeZhangId;
  // 获取单词列表数据
  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) {
    if (userCode !== 'Visitor') {
      uni.redirectTo({
        url: `/pages/newEnglish/index?jieId=${data.jieId}&wordId=${data.wordList[index + 1].id }`
      })
    } else {
      uni.redirectTo({
        url: `/pages/newEnglish/index?jieId=${data.jieId}&wordId=${data.wordList[index + 1].id }&levelId=${data.levelId}&typeId=${data.typeId}&subjectId=${data.subjectId}&tipFlag=${data.tipFlag}&youkeZhangId=${data.youkeZhangId}`
      })
    }
  }
 }

 function prevWord() {
  const index = data.wordList.findIndex(item => item.id == data.activeId);
  if (index > 0) {
    if (userCode !== 'Visitor') {
      uni.redirectTo({
        url: `/pages/newEnglish/index?jieId=${data.jieId}&wordId=${data.wordList[index - 1].id }`
      })
    } else {
      uni.redirectTo({
        url: `/pages/newEnglish/index?jieId=${data.jieId}&wordId=${data.wordList[index - 1].id }&levelId=${data.levelId}&typeId=${data.typeId}&subjectId=${data.subjectId}&tipFlag=${data.tipFlag}&youkeZhangId=${data.youkeZhangId}`
      })
    }
  }
 }

 function handleBack() {
  // 返回单词列表
  if (userCode !== 'Visitor') {
   if (data.jieId == 0) {
    uni.redirectTo({
      url: `/pages/my/learnRecord?jieId=${data.jieId}&isLearnStatus=${data.isLearnStatus}&levelId=${data.levelId}&typeId=${data.typeId}&subjectId=${data.subjectId}&tipFlag=${data.tipFlag}&youkeZhangId=${data.youkeZhangId}`
    })
   } else {
    uni.redirectTo({
     url: `/pages/wordList/wordList?jieId=${data.jieId}`
    })
   }
  } else {
   const youkePageData = JSON.stringify({
    subjectId: data.subjectId,
    levelId: data.levelId,
    typeId: data.typeId,
    tipFlag: data.tipFlag,
    youkeZhangId: data.youkeZhangId,
    jieId: data.jieId
   })
   uni.redirectTo({
    url: `/pages/wordList/wordList?youkePageData=${youkePageData}`
   })
  }
 }

 function handleComplete() {
  // 返回岛
  if (userCode !== 'Visitor') {
    let jieInfo = cacheManager.getUnitInfo('zhangInfo', data.jieId);
    if (jieInfo.lastFlag == 1) {
      // 更新岛状态
      cacheManager.updateObject('zhangInfo', {
        curZid: jieInfo.nextZid
      })
    }

   uni.redirectTo({
    url: `/pages/study/index`
   })
  } else {
   uni.redirectTo({
    url: `/pages/study/index?levelId=${data.levelId}&typeId=${data.typeId}&subjectId=${data.subjectId}&tipFlag=${data.tipFlag}&youkeZhangId=${data.youkeZhangId}&jieId=${data.jieId}`
   })
  }
 }

 function handleShouCang() {
  if (data.collectFlag == 1) {
   httpApi.getWordCancel({
    wordId: data.activeId
   }).then(res => {
    uni.showToast({
     title: '操作成功'
    })
    data.collectFlag = 0;
   })
  } else {
   httpApi.getWordShouCang({
    wordId: data.activeId
   }).then(res => {
    uni.showToast({
     title: '操作成功'
    })
    data.collectFlag = 1;
   })
  }
 }

 function initWordInfo() {

  if (userCode !== 'Visitor') {
   httpApi.getWordInfo({
    jieId: data.jieId,
    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维数组
    }
    // console.log('res.data',res.data)
    handleCacheAudio()
   autoPlayAudio()

   })
  } else {
   httpApi.getCommonWordInfo({
    jieId: data.jieId,
    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()
    autoPlayAudio()
   })
  }
 }
 // 新增自动播放功能
 const autoPlayAudio = async () => {
  // 等待数据加载完成
  await nextTick();

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

 function goXiangjie() {

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

 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'
   });
  }
 }
</script>

<style>

</style>