import Clipboard from 'clipboard'
import { decrypt } from '@/utils/crypto'

/**
 * 复制文本到剪贴板
 * @param text 文本内容
 */
export const copyText = (text: string) => {
  return new Promise((resolve, reject) => {
    const fakeElement = document.createElement('button')
    const clipboard = new Clipboard(fakeElement, {
      text: () => text,
      action: () => 'copy',
      container: document.body,
    })
    clipboard.on('success', e => {
      clipboard.destroy()
      resolve(e)
    })
    clipboard.on('error', e => {
      clipboard.destroy()
      reject(e)
    })
    document.body.appendChild(fakeElement)
    fakeElement.click()
    document.body.removeChild(fakeElement)
  })
}

/**
 * 复制图到剪贴板
 * @param image 图内容 png有效
 */
 export const copyImage = async (image: string) => {
  try {
    const imageSrc = image; 
    const response = await fetch(imageSrc);
    const blob = await response.blob();
    await navigator.clipboard.write([
        new ClipboardItem({
          [blob.type]: blob
        })
    ]);
      return 'success'
  } catch (error) {
      return 'info'
  }
 }

export const replaceText = (text:string,content:string,method:'R'|'I') =>{
  const fakeElement = document.createElement('div')
  fakeElement.innerHTML = text
  const targetElement = findMiniChildNode(fakeElement)
  
  if(targetElement){
    const parentElement = targetElement.parentElement
    if (parentElement) {
      parentElement.innerText = (method=='I'?parentElement.innerText:'')+content
    }
  }
  return fakeElement.innerHTML

}

const convertToHTMLElement = (node: ChildNode): HTMLElement | null => {
  if (node instanceof HTMLElement) {
    return node;
  } else {
    return null; // 或者根据需要处理非 HTMLElement 的节点
  }
}

const findMiniChildNode = (element: Element | ChildNode): ChildNode | null => {
  if (element.hasChildNodes()) {
    const childs = element.childNodes;
    for (let i = 0; i < childs.length; i++) {
      const foundNode = findMiniChildNode(childs.item(i));
      if (foundNode) {
        return foundNode;
      }
    }
  } else {
    return element;
  }
  return null;
}

// 读取剪贴板
export const readClipboard = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    if (navigator.clipboard?.readText) {
      navigator.clipboard.readText().then(text => {
        if (!text) reject('剪贴板为空或者不包含文本')
        return resolve(text)
      })
    }
    else reject('浏览器不支持或禁止访问剪贴板，请使用快捷键 Ctrl + V')
  })
}

// 解析加密后的剪贴板内容
export const pasteCustomClipboardString = (text: string) => {
  let clipboardData
  try {
    clipboardData = JSON.parse(decrypt(text))
  }
  catch {
    clipboardData = text
  }

  return clipboardData
}

// 尝试解析剪贴板内容是否为Excel表格（或类似的）数据格式
export const pasteExcelClipboardString = (text: string): string[][] | null => {
  const lines: string[] = text.split('\r\n')

  if (lines[lines.length - 1] === '') lines.pop()

  let colCount = -1
  const data: string[][] = []
  for (const index in lines) {
    data[index] = lines[index].split('\t')

    if (data[index].length === 1) return null
    if (colCount === -1) colCount = data[index].length
    else if (colCount !== data[index].length) return null
  }
  return data
}