import { selfCloseTagList } from "../constants/constant"

// 驼峰转连字符
export const camelCaseToHyphen = (str: string): string => {
  return str.replace(/([a-z])([A-Z])/g, (...args: string[]): string => {
    return args[1] + '-' + args[2].toLowerCase()
  })
}

// 检查一个字符串是否是富文本字符
let checkIsRichTextEl: HTMLDivElement | null = null
export const checkIsRichText = (str: string): boolean => {
  if (!checkIsRichTextEl) {
    checkIsRichTextEl = document.createElement('div')
  }
  checkIsRichTextEl.innerHTML = str
  for (let c = checkIsRichTextEl.childNodes, i = c.length; i--;) {
    if (c[i].nodeType === 1) return true
  }
  return false
}

// html转义
export const htmlEscape = (str?: string): string => {
  [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;']
  ].forEach((item: string[]) => {
    str = str?.replace(new RegExp(item[0], 'g'), item[1])
  })
  return str || ''
}

// 给html自闭合标签添加闭合状态
export const handleSelfCloseTags = (str: string): string => {
  selfCloseTagList.forEach((tagName: string) => {
    str = str.replaceAll(
      new RegExp(`<${tagName}([^>]*)>`, 'g'),
      `<${tagName} $1 />`
    )
  })
  return str
}

// 从头html结构字符串里获取带换行符的字符串
export const getStrWithBrFromHtml = (str: string): string => {
  str = str.replace(/<br>/gim, '\n')
  const el = document.createElement('div')
  el.innerHTML = str
  str = el.textContent || ''
  return str
}

interface DataUrlResult {
  type: string
  base64: string
}

// 解析dataUrl
export const parseDataUrl = (data: string): string | DataUrlResult => {
  if (!/^data:/.test(data)) return data
  const [typeStr, base64] = data.split(',')
  const res = /^data:[^/]+\/([^;]+);/.exec(typeStr)
  if (!res) throw new Error('Invalid data URL')
  const type = res[1]
  return {
    type,
    base64
  }
}

// 将以空格分隔的字符串值转换成成数字/单位/值数组
export const getNumberValueFromStr = (value: string | number) => {
  let arr = String(value).split(/\s+/)
  return arr.map(item => {
    if (/^[\d.]+/.test(item)) {
      // 数字+单位
      let res = /^([\d.]+)(.*)$/.exec(item)
      if (!res) return item
      return [Number(res[1]), res[2]]
    } else {
      // 单个值
      return item
    }
  })
}