import { message } from 'antd'

const copyHtmlToClipboard = (element: HTMLDivElement, slient = false): void => {
  document.getSelection()?.removeAllRanges()
  const range = document.createRange()
  range.selectNode(element)
  const selection = document.getSelection()
  if (selection) {
    selection.addRange(range)
  } else {
    message.error('复制失败')
  }
  try {
    document.execCommand('copy') ? !slient && message.success('复制成功') : message.error('复制失败')
  } catch {
    message.error('复制失败')
  }
  document.getSelection()?.removeAllRanges()
}

const readHtmlFromClipboard = async () => {
  const decoder = new TextDecoder()
  try {
    const ClipboardItem = (await navigator.clipboard.read())[0]
    const blob = await ClipboardItem.getType('text/html')
    const buffer = await blob.arrayBuffer()
    return decoder.decode(buffer)
  } catch {
    message.error('读取粘贴板内容失败')
    return ''
  }
}

export { copyHtmlToClipboard, readHtmlFromClipboard }
