text: /**
   * 歌词相关
   */
  import { getLyric } from '@/api'
  import { computed, watch, ref, getCurrentInstance } from 'vue'
  import { useStore } from 'vuex'
  
  export default function useLyrics () {
    const store = useStore()
    const currentLyric = ref(null)
    const currentLineNum = ref(0)
    const lyricScrollRef = ref(null)
    const lyricListRef = ref(null)
    const { parent } = getCurrentInstance()
    const playingLyric = ref(null)
  
    const currentSong = computed(() => store.getters.currentSong)
  
    watch(currentSong, async newSong => {
      const { lyric } = await getLyric(newSong)
  
      // 把歌词提交到store里，为了重新进入该组件时还能再次渲染
      store.commit('addSongLyric', { song: newSong, lyric })
  
      if (currentSong.value.lyric !== lyric) return
  
      currentLyric.value = handleLyric(lyric)
    })
  
    watch(
      () => parent.ctx.currentTime,
      newTime => {
        handleActiveLyric(newTime)
      }
    )
  
    function handleLyric (lyric) {
      const lyricArr = []
      let lyrics = lyric.split('\n')
      // 定义正则表达式提取[00:00.000]
      const timeReg = /\[\d*:\d*\.\d*\]/g
      // 定义正则表达式提取 [00
      const minReg = /\[\d*/i
      // 定义正则表达式提取 :00.000
      const secondReg = /\:\d*/i
  
      lyrics.forEach((item, index) => {
        const text = item.replace(timeReg, '').trim()
        let timeStr = item.match(timeReg)
  
        if (!timeStr) return
        timeStr = timeStr[0] // 00:01.930
        const minStr = timeStr.match(minReg)[0].substr(1)
        const secondStr = timeStr.match(secondReg)[0].substr(1)
        let time = parseInt(minStr) * 60 + Math.ceil(secondStr) // 把时间转换成与currentTime相同的类型，方便待会实现滚动效果
  
        if (text) {
          lyricArr.push({ time, text })
        }
      })
  
      return lyricArr
    }
  
    // 歌词滚动时让高亮歌词始终在中间
    function handleActiveLyric (time) {
      const timeLine = parseInt(time)
      const currentLyricVal = currentLyric.value
      const scrollComp = lyricScrollRef.value
      const listEl = lyricListRef.value
  
      currentLyricVal.forEach((item, index) => {
        if (timeLine === item.time) {
          currentLineNum.value = index
          playingLyric.value = item.text
  
          if (currentLineNum.value > 5) {
            const lineEl = listEl.children[currentLineNum.value - 6]
  
            scrollComp.scroll.scrollToElement(lineEl, 1000)
          } else {
            scrollComp.scroll.scrollTo(0, 0, 1000)
          }
        }
      })
    }
  
    return {
      currentLyric,
      currentLineNum,
      playingLyric,
      lyricScrollRef,
      lyricListRef
    }
  }
  