import { useAudio } from '@/hooks'

export const handleAccents = (url: string, type: string) => {
  if (!url) return
  const { accent, file } = JSON.parse(url)[0] || {}
  return type === 'accent' ? accent : file
}

export const playMp3 = (data: anyObj, url: string, _bool = true) => {
  if (!url) return
  data.isplay = true
  useAudio({
    url: _bool ? handleAccents(url, 'file') : url,
    autoplay: true,
    onEnded: () => {
      data.isplay = false
    },
  })
}

// 播放英音
export const playbr = (data: anyObj, url: string, _bool = true) => {
  if (!url) return
  data.isplaybr = true
  useAudio({
    url: _bool ? handleAccents(url, 'file') : url,
    autoplay: true,
    onEnded: () => {
      data.isplaybr = false
    },
  })
}

// 播放美英
export const playus = (data: anyObj, url: string, _bool = true) => {
  if (!url) return
  data.isplayus = true
  useAudio({
    url: _bool ? handleAccents(url, 'file') : url,
    autoplay: true,
    onEnded: () => {
      data.isplayus = false
    },
  })
}

// 后端直接返回高亮下标，保持规则一致
export const highlightText = (text: string, list: any[]) => {
  const startIdx = list[0]
  const endIdx = list[list.length - 1]
  if (list.length > 0) {
    return (
      text.substring(0, startIdx) +
      `<text style="color: #99D609">${text.slice(startIdx, startIdx + list.length)}</text>` +
      text.substring(endIdx + 1)
    )
  } else {
    return text
  }
}

// 词性 字符串转数组
export const checkAttr = (str: string) => {
  return (str && str.substring(1, str.length - 1).split(',')) || []
}
