<template>
  <view class="container">
    <!-- 歌词显示区域 -->
    <view class="lyrics-container">
      <view class="lyrics-content">
        <!-- 当前句子显示 -->
        <view class="current-sentence">
          <text class="lyric-line active">
            {{ currentSentence ? currentSentence.FinalSentence : "" }}
          </text>
        </view>

        <!-- 句子指示器 -->
        <view class="sentence-indicator">
          <text class="sentence-text">
            {{ currentSentenceIndex + 1 }}/{{ totalSentences }}
          </text>
        </view>
      </view>
    </view>

    <!-- 播放控制区域 -->
    <view class="player-controls">
      <!-- 控制按钮区域（进度条上方） -->
      <view class="control-icons" v-if="false">
        <view class="control-icon">
          <text class="icon-text">⋯</text>
        </view>
        <view class="control-icon-group">
          <view class="control-icon">
            <text class="icon-text">♡</text>
          </view>
          <view class="control-icon">
            <text class="icon-text">🔍</text>
          </view>
        </view>
      </view>

      <!-- 进度条区域 -->
      <view class="progress-section">
        <text class="time-text">{{ 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="time-text">{{ formatTime(duration) }}</text>
      </view>
      <!-- 句子控制按钮 -->
      <view class="sentence-controls">
        <view
          class="control-btn"
          @click="prevSentence"
          :disabled="currentSentenceIndex === 0"
        >
          <text class="control-icon-text">◀</text>
        </view>
        <view class="sentence-info">
          <text class="sentence-info-text"
            >{{ currentSentenceIndex + 1 }}/{{ totalSentences }}</text
          >
        </view>
        <view
          class="control-btn"
          @click="nextSentence"
          :disabled="currentSentenceIndex >= totalSentences - 1"
        >
          <text class="control-icon-text">▶</text>
        </view>
      </view>

      <!-- 底部控制按钮 -->
      <view class="bottom-controls">
        <view class="control-btn">
          <text class="control-icon-text">⟲</text>
        </view>
        <view class="control-btn" @click="prevChapter">
          <text class="control-icon-text">⏮</text>
        </view>
        <view class="control-btn play-btn" @click="togglePlay">
          <text class="control-icon-text">{{ playing ? "⏸" : "▶" }}</text>
        </view>
        <view class="control-btn" @click="nextChapter">
          <text class="control-icon-text">⏭</text>
        </view>
        <view class="control-btn">
          <text class="control-icon-text">☰</text>
        </view>
      </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,
      // 句子相关数据
      currentSentenceIndex: 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);
    },
    // 句子相关计算属性
    totalSentences() {
      return this.currentChapter.sentences.length;
    },
    currentSentence() {
      return this.currentChapter.sentences[this.currentSentenceIndex] || null;
    },
  },
  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.currentSentenceIndex = 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) {
        this.activeSentenceIndex = targetIndex;
        this.currentSentenceIndex = targetIndex;
      }
    },
    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为额外边距
    },
    // 句子控制方法
    prevSentence() {
      if (this.currentSentenceIndex > 0) {
        this.currentSentenceIndex--;
        this.activeSentenceIndex = this.currentSentenceIndex;
        // 跳转到当前句子的开始时间
        const sentence =
          this.currentChapter.sentences[this.currentSentenceIndex];
        if (sentence && this.$refs.audioPlayer) {
          this.$refs.audioPlayer.seek(sentence.startTimeInSeconds);
        }
      }
    },
    nextSentence() {
      if (this.currentSentenceIndex < this.totalSentences - 1) {
        this.currentSentenceIndex++;
        this.activeSentenceIndex = this.currentSentenceIndex;
        // 跳转到当前句子的开始时间
        const sentence =
          this.currentChapter.sentences[this.currentSentenceIndex];
        if (sentence && this.$refs.audioPlayer) {
          this.$refs.audioPlayer.seek(sentence.startTimeInSeconds);
        }
      }
    },
  },
};
</script>

<style>
.container {
  height: 100vh;
  background: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  position: relative;
  display: flex;
  flex-direction: column;
}

/* 顶部标签样式 */
.top-label {
  display: flex;
  justify-content: center;
  padding: 40rpx 0 20rpx 0;
}

.label-content {
  background: #e8e8e8;
  border: 2rpx solid #d0d0d0;
  border-radius: 40rpx;
  padding: 16rpx 32rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.label-number {
  width: 32rpx;
  height: 32rpx;
  background: #666;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24rpx;
  font-weight: 600;
}

.label-text {
  color: #666;
  font-size: 28rpx;
  font-weight: 500;
}

/* 歌词容器样式 */
.lyrics-container {
  flex: 1;
  padding: 0 60rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.lyrics-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
}

.current-sentence {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.lyric-line {
  display: block;
  text-align: center;
  font-size: 36rpx;
  color: #333;
  line-height: 1.8;
  margin: 0;
  transition: all 0.3s ease;
  padding: 20rpx;
  font-weight: 600;
}

.lyric-line.active {
  color: #333;
  font-weight: 600;
  font-size: 36rpx;
}

.sentence-indicator {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  background: rgba(0, 0, 0, 0.1);
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.sentence-text {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

/* 播放控制区域 */
.player-controls {
  background: white;
  padding: 40rpx 60rpx 60rpx 60rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

/* 控制图标区域 */
.control-icons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.control-icon {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f0f0f0;
}

.control-icon-group {
  display: flex;
  gap: 40rpx;
}

.icon-text {
  font-size: 32rpx;
  color: #666;
}

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

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

.progress-container {
  flex: 1;
  position: relative;
}

.progress-bar {
  height: 8rpx;
  background: #e0e0e0;
  border-radius: 4rpx;
  position: relative;
  cursor: pointer;
}

.progress {
  height: 100%;
  background: #333;
  border-radius: 4rpx;
  transition: width 0.2s ease;
}

.progress-thumb {
  position: absolute;
  top: 50%;
  width: 24rpx;
  height: 24rpx;
  background: #333;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  cursor: pointer;
}

/* 无损标识 */
.quality-label {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}

.quality-text {
  font-size: 24rpx;
  color: #999;
}

/* 句子控制按钮 */
.sentence-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40rpx;
  margin-bottom: 30rpx;
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
}

.sentence-info {
  background: #f8f8f8;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  min-width: 120rpx;
  text-align: center;
}

.sentence-info-text {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

/* 底部控制按钮 */
.bottom-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 60rpx;
}

.control-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: transparent;
  cursor: pointer;
  transition: all 0.2s ease;
}

.control-btn.play-btn {
  background: #333;
  color: white;
}

.control-icon-text {
  font-size: 32rpx;
  color: #666;
  line-height: 1;
}

.control-btn.play-btn .control-icon-text {
  color: white;
  font-size: 36rpx;
}

.control-btn:active {
  transform: scale(0.95);
}

.control-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.control-btn:disabled:active {
  transform: none;
}
</style>
