<template>
  <view class="container">
    <!-- 顶部标题栏 -->
    <!-- 主要内容区域 -->
    <!-- 文本显示区域 -->
    <scroll-view
      class="content"
      :show-scrollbar="false"
      enhanced
      scroll-y
      :scroll-top="scrollTop"
      scroll-with-animation
      :style="{ height: scrollViewHeight + 'px' }"
    >
      <view class="content-wrapper">
        <view class="article-content">
          <text
            v-for="(sentence, index) in currentChapter.sentences"
            :key="index"
            :id="`sentence-${index}`"
            class="sentence"
            :class="{ active: index === activeSentenceIndex }"
          >
            {{ sentence.FinalSentence }}
          </text>
        </view>
      </view>
    </scroll-view>
    <!-- 底部控制栏 -->
    <view class="controls">
      <!-- 章节信息栏 -->
      <view class="chapter-info-bar">
        <text class="chapter-title">{{ currentChapter.title }}</text>
        <text class="chapter-count">
          {{ currentChapterIndex + 1 }}/{{ chapters.length }}
        </text>
      </view>

      <!-- 进度条区域 -->
      <view class="progress-section">
        <text class="current-time">{{ formatTime(currentTime) }}</text>
        <view class="progress-container">
          <view class="progress-bar" @click="seek">
            <view class="progress" :style="{ width: progress + '%' }"></view>
            <view
              class="progress-thumb"
              :style="{ left: progress + '%' }"
            ></view>
          </view>
        </view>
        <text class="duration">{{ formatTime(duration) }}</text>
      </view>

      <!-- 控制按钮区域 -->
      <view class="control-buttons">
        <!-- 上一章按钮 -->
        <button
          class="control-btn prev-btn"
          @click="prevChapter"
          :disabled="currentChapterIndex === 0"
        >
          <text class="control-icon">⏮</text>
        </button>

        <!-- 播放/暂停按钮 -->
        <button class="play-btn" @click="togglePlay">
          <text class="play-icon">{{ playing ? "⏸️" : "▶️" }}</text>
        </button>

        <!-- 下一章按钮 -->
        <button
          class="control-btn next-btn"
          @click="nextChapter"
          :disabled="currentChapterIndex === chapters.length - 1"
        >
          <text class="control-icon">⏭</text>
        </button>
      </view>
    </view>

    <AudioPlayer
      ref="audioPlayer"
      :src="currentChapter.audioUrl"
      @timeupdate="onTimeUpdate"
      @ended="onEnded"
    ></AudioPlayer>
  </view>
</template>

<script>
// 由于uniapp不支持直接使用audio元素，我们使用innerAudioContext
import AudioPlayer from "../components/AudioPlayer.vue";
const msg = require("../components/msg.json");
console.log(msg);
export default {
  components: {
    AudioPlayer,
  },
  data() {
    return {
      chapters: [
        {
          title: "元界修真传",
          audioUrl:
            "https://des.js-dyyj.com/data/2025/09/15/ecd0671f-ba8b-4b69-bb07-1a1d8b4bbfd0.MP3",
          // 句子级别的时间同步数据，从msg.json的ResultDetail数组获取
          sentences:
            require("../components/msg.json")?.Response?.Data?.ResultDetail ||
            [],
          content:
            require("../components/msg.json")?.Response?.Data?.Result || "",
        },
      ],
      currentChapterIndex: 0,
      playing: false,
      currentTime: 0,
      duration: 0,
      activeSentenceIndex: -1,
      scrollTop: 0,
      scrollViewHeight: 0,
    };
  },
  mounted() {
    this.syncAudioState();
    this.calculateScrollViewHeight();
  },
  onShow() {
    // 页面显示时同步音频状态
    this.syncAudioState();
  },
  onHide() {
    // 页面隐藏时保持音频播放状态
    // 背景音频会自动继续播放
  },
  computed: {
    currentChapter() {
      const chapter = this.chapters[this.currentChapterIndex];
      // 使用句子级别的时间同步数据
      const sentences = chapter.sentences.map((sentence) => {
        return {
          ...sentence,
          startTimeInSeconds: sentence.StartMs / 1000, // 将毫秒转换为秒
          endTimeInSeconds: sentence.EndMs / 1000, // 将毫秒转换为秒
        };
      });
      return {
        ...chapter,
        sentences: sentences,
      };
    },
    progress() {
      return (this.currentTime / this.duration) * 100 || 0;
    },
    currentTimeFormatted() {
      return this.formatTime(this.currentTime);
    },
    durationFormatted() {
      return this.formatTime(this.duration);
    },
  },
  methods: {
    togglePlay() {
      if (this.playing) {
        this.$refs.audioPlayer.pause();
        this.playing = false;
      } else {
        this.$refs.audioPlayer.play();
        this.playing = true;
      }
    },
    prevChapter() {
      if (this.currentChapterIndex > 0) {
        this.currentChapterIndex--;
        this.resetPlayback();
      }
    },
    nextChapter() {
      if (this.currentChapterIndex < this.chapters.length - 1) {
        this.currentChapterIndex++;
        this.resetPlayback();
      }
    },
    resetPlayback() {
      this.playing = false;
      this.currentTime = 0;
      this.duration = 0;
      this.activeSentenceIndex = -1;
      this.scrollTop = 0;

      // 更新背景音频信息
      const currentChapter = this.chapters[this.currentChapterIndex];
      if (
        this.$refs.audioPlayer &&
        this.$refs.audioPlayer.backgroundAudioManager
      ) {
        const bgAudio = this.$refs.audioPlayer.backgroundAudioManager;
        bgAudio.title = currentChapter.title;
        bgAudio.epname = `第${this.currentChapterIndex + 1}章`;
        bgAudio.src = currentChapter.audioUrl;
        // 确保音频从头开始播放
        bgAudio.currentTime = 0;
        // 如果音频播放器有seek方法，也调用它来确保重置
        if (this.$refs.audioPlayer.seek) {
          this.$refs.audioPlayer.seek(0);
        }
      }
    },
    onTimeUpdate(e) {
      this.currentTime = e.currentTime;
      this.duration = e.duration;

      // 同步播放状态
      this.playing = !e.paused;

      // 句子级别的高亮同步
      this.updateSentenceHighlight(this.currentTime);
    },
    onEnded() {
      this.playing = false;
      // 自动播放下一章节
      if (this.currentChapterIndex < this.chapters.length - 1) {
        this.nextChapter();
        setTimeout(() => {
          this.$refs.audioPlayer.play();
          this.playing = true;
        }, 500);
      }
    },
    seek(e) {
      // 使用uni.createSelectorQuery获取进度条信息
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".progress-bar")
        .boundingClientRect((rect) => {
          if (rect) {
            const clickX = e.detail.x - rect.left;
            const progressPercent = clickX / rect.width;
            const seekTime = progressPercent * this.duration;

            if (seekTime >= 0 && seekTime <= this.duration) {
              this.$refs.audioPlayer.seek(seekTime);
              
              // 手动拖动后同步句子高亮和滚动位置
              this.updateSentenceHighlight(seekTime);
            }
          }
        })
        .exec();
    },
    updateSentenceHighlight(currentTimeSeconds) {
      // 根据指定时间找到对应的句子并更新高亮和滚动位置
      const sentences = this.currentChapter.sentences;
      let targetIndex = -1;
      
      // 精确匹配：找到当前时间对应的句子
      for (let i = 0; i < sentences.length; i++) {
        const sentence = sentences[i];
        if (
          currentTimeSeconds >= sentence.startTimeInSeconds &&
          currentTimeSeconds <= sentence.endTimeInSeconds
        ) {
          targetIndex = i;
          break;
        }
      }
      
      // 如果没有精确匹配，尝试找到最接近的句子
      if (targetIndex === -1 && sentences.length > 0) {
        // 找到时间最接近的句子，而不是简单的比例估算
        let minDistance = Infinity;
        for (let i = 0; i < sentences.length; i++) {
          const sentence = sentences[i];
          const sentenceMiddle = (sentence.startTimeInSeconds + sentence.endTimeInSeconds) / 2;
          const distance = Math.abs(currentTimeSeconds - sentenceMiddle);
          if (distance < minDistance) {
            minDistance = distance;
            targetIndex = i;
          }
        }
      }
      
      // 只有当索引真正发生变化时才更新
      if (targetIndex >= 0 && targetIndex !== this.activeSentenceIndex) {
        const previousIndex = this.activeSentenceIndex;
        this.activeSentenceIndex = targetIndex;
        
        // 使用$nextTick确保DOM更新后再计算滚动位置
        this.$nextTick(() => {
          this.scrollToSentence(targetIndex);
        });
      }
    },
    scrollToSentence(index) {
      // 动态获取句子位置并滚动到可视区域
      const query = uni.createSelectorQuery().in(this);
      
      // 获取目标句子的位置信息
      query.select(`#sentence-${index}`).boundingClientRect();
      // 获取滚动容器的位置信息
      query.select('.article-content').boundingClientRect();
      
      query.exec((res) => {
        if (res && res[0] && res[1]) {
          const sentenceRect = res[0];
          const containerRect = res[1];
          
          // 计算句子相对于容器顶部的位置
          const sentenceTop = sentenceRect.top - containerRect.top;
          
          // 计算滚动位置，让句子显示在可视区域中央
          const scrollPosition = Math.max(
            0,
            sentenceTop - this.scrollViewHeight / 2 + sentenceRect.height / 2
          );
          
          // 更新滚动位置
          this.scrollTop = scrollPosition;
        } else {
          // 如果无法获取元素位置，使用估算方式
          const estimatedHeight = 60;
          const scrollPosition = Math.max(
            0,
            index * estimatedHeight - this.scrollViewHeight / 2
          );
          this.scrollTop = scrollPosition;
        }
      });
    },
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, "0")}:${secs
        .toString()
        .padStart(2, "0")}`;
    },
    syncAudioState() {
      // 同步背景音频状态到界面
      if (
        this.$refs.audioPlayer &&
        this.$refs.audioPlayer.backgroundAudioManager
      ) {
        const bgAudio = this.$refs.audioPlayer.backgroundAudioManager;

        // 检查当前是否有音频在播放
        if (bgAudio.src) {
          // 同步播放状态 - 注意：paused为true表示暂停，false表示播放
          this.playing = !bgAudio.paused;

          // 同步时间信息
          this.currentTime = bgAudio.currentTime || 0;
          this.duration = bgAudio.duration || 0;

          // 如果有音频在播放，启动时间更新
          if (this.playing) {
            this.$refs.audioPlayer.startTimeUpdate();
          }
        } else {
          // 没有音频源时重置状态
          this.playing = false;
          this.currentTime = 0;
          this.duration = 0;
        }
      }
    },
    calculateScrollViewHeight() {
      // 获取系统信息
      const systemInfo = uni.getSystemInfoSync();
      const windowHeight = systemInfo.windowHeight;

      // 计算控制栏高度（大约300rpx转换为px）
      const controlsHeight = 300 * (systemInfo.windowWidth / 750);

      // 计算内容区域可用高度
      this.scrollViewHeight = windowHeight - controlsHeight - 60; // 60px为额外边距
    },
  },
};
</script>

<style>
.container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  padding: 30rpx;
  position: relative;
}

/* 顶部标题栏样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 48rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-bottom: 2rpx solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4rpx 40rpx rgba(0, 0, 0, 0.1);
}

.header-content {
  flex: 1;
}

.title {
  font-size: 48rpx;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 8rpx;
}

.subtitle {
  font-size: 32rpx;
  color: #718096;
  font-weight: 500;
}

.chapter-info {
  background: linear-gradient(135deg, #667eea, #764ba2);
  padding: 16rpx 32rpx;
  border-radius: 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.chapter-count {
  color: white;
  font-size: 28rpx;
  font-weight: 600;
}

.content {
  width: 690rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20rpx);
  border-radius: 32rpx;
  margin: 0 auto;
  margin-bottom: 20rpx;
}

.content-wrapper {
  padding: 48rpx;
}

.article-content {
  line-height: 1.8;
  font-size: 32rpx;
  color: #2d3748;
  text-align: justify;
}

.sentence {
  display: block;
  padding: 20rpx;
  margin: 10rpx 0;
  border-radius: 12rpx;
  line-height: 1.8;
  transition: all 0.3s ease;
}

.sentence.active {
  background-color: rgba(255, 215, 0, 0.2);
  font-weight: 600;
  box-shadow: 0 4rpx 12rpx rgba(255, 215, 0, 0.3);
  transform: translateX(10rpx);
}

/* 底部控制栏样式 */
.controls {
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(40rpx);
  border-top: 2rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 -16rpx 64rpx rgba(0, 0, 0, 0.12),
    0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
  border-radius: 48rpx 48rpx 0 0;
  padding: 32rpx 40rpx 40rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

/* 章节信息栏 */
.chapter-info-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8rpx;
}

.chapter-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #2d3748;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 16rpx;
}

.chapter-count {
  font-size: 24rpx;
  color: #718096;
  font-weight: 500;
  background: rgba(139, 92, 246, 0.1);
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
}

/* 进度条区域 */
.progress-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.current-time,
.duration {
  font-size: 24rpx;
  color: #718096;
  font-weight: 500;
  font-family: "Courier New", monospace;
  min-width: 80rpx;
  text-align: center;
}

/* 控制按钮区域 */
.control-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 32rpx;
}

/* 播放按钮 */
.play-btn {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  border: none;
  background: linear-gradient(135deg, #8b5cf6, #a855f7);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 12rpx 40rpx rgba(139, 92, 246, 0.4),
    0 6rpx 20rpx rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: hidden;
  z-index: 2;
}

/* 控制按钮（上一章/下一章） */
.control-btn {
  width: 88rpx;
  height: 88rpx;
  border-radius: 50%;
  border: none;
  background: rgba(139, 92, 246, 0.08);
  color: #8b5cf6;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 16rpx rgba(139, 92, 246, 0.15);
  backdrop-filter: blur(20rpx);
  position: relative;
  overflow: hidden;
}

.play-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.2),
    rgba(255, 255, 255, 0.05)
  );
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.play-btn:hover {
  transform: scale(1.08);
  box-shadow: 0 18rpx 56rpx rgba(139, 92, 246, 0.5),
    0 9rpx 28rpx rgba(0, 0, 0, 0.2);
}

.play-btn:hover::before {
  opacity: 1;
}

.play-btn:active {
  transform: scale(0.96);
  transition: transform 0.1s ease;
}

/* 进度条容器 */
.progress-container {
  flex: 1;
  position: relative;
}

.progress-bar {
  height: 12rpx;
  background: rgba(139, 92, 246, 0.12);
  border-radius: 6rpx;
  position: relative;
  cursor: pointer;
  overflow: hidden;
  backdrop-filter: blur(20rpx);
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #8b5cf6 0%, #a855f7 50%, #c084fc 100%);
  border-radius: 6rpx;
  transition: width 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 16rpx rgba(139, 92, 246, 0.3);
  position: relative;
}

.progress::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    90deg,
    rgba(255, 255, 255, 0.3) 0%,
    rgba(255, 255, 255, 0.1) 100%
  );
  border-radius: 6rpx;
}

.progress-thumb {
  position: absolute;
  top: 50%;
  width: 28rpx;
  height: 28rpx;
  background: white;
  border: 4rpx solid #8b5cf6;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 6rpx 20rpx rgba(139, 92, 246, 0.4),
    0 3rpx 6rpx rgba(0, 0, 0, 0.1);
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
}

.progress-thumb:hover {
  transform: translate(-50%, -50%) scale(1.2);
  box-shadow: 0 8rpx 24rpx rgba(139, 92, 246, 0.5),
    0 4rpx 8rpx rgba(0, 0, 0, 0.15);
}

/* 控制按钮交互效果 */
.control-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    135deg,
    rgba(139, 92, 246, 0.1),
    rgba(168, 85, 247, 0.05)
  );
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.control-btn:hover {
  background: rgba(139, 92, 246, 0.15);
  transform: scale(1.1);
  box-shadow: 0 8rpx 32rpx rgba(139, 92, 246, 0.25);
}

.control-btn:hover::before {
  opacity: 1;
}

.control-btn:active {
  transform: scale(0.95);
  transition: transform 0.1s ease;
}

.control-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 2rpx 6rpx rgba(139, 92, 246, 0.1);
}

.control-btn:disabled:hover {
  background: rgba(139, 92, 246, 0.08);
  transform: none;
  box-shadow: 0 2rpx 6rpx rgba(139, 92, 246, 0.1);
}

.control-btn:disabled::before {
  opacity: 0;
}

/* 控制图标样式 */
.control-icon {
  font-size: 32rpx;
  line-height: 1;
  filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
}

.play-icon {
  font-size: 42rpx;
  line-height: 1;
  margin-left: 3rpx;
  filter: drop-shadow(0 3rpx 6rpx rgba(0, 0, 0, 0.2));
}
</style>
