export const copyText = async (
  text: string,
  fallback?: boolean
): Promise<void> => {
  if (navigator.clipboard && !fallback) {
    const permiss = await navigator.permissions.query({ name: 'geolocation' })
    permiss.state === 'denied'

    if (permiss && permiss.state === 'denied') {
      console.error(permiss)
      throw new Error('请授予写入粘贴板权限！')
    } else {
      try {
        await navigator.clipboard.writeText(text)
      } catch (e) {
        console.error('不支持navigator.clipboard.writeText 开启回退')
        return await copyText(text, true)
      }
    }
  } else {
    const textarea = document.createElement('textarea')
    document.body.appendChild(textarea)
    // 隐藏此输入框
    textarea.style.position = 'fixed'
    textarea.style.clip = 'rect(0 0 0 0)'
    textarea.style.top = '10px'
    // 赋值
    textarea.value = text
    // 选中
    textarea.select()
    // 复制
    document.execCommand('copy', true)
    // 移除输入框
    document.body.removeChild(textarea)
  }
}
