import { symbols } from '@/constants'
import { BaseWidget } from '@/types/baseWidget'
import { Page } from '@/types/page'
import { imageSize } from 'image-size'
import { bfsWalk } from 'simple-mind-map/src/utils'

export * from './color'

/**
 * 根据路径获取文件
 * @param path 路径
 * @param encoding 编码
 * @returns content BufferEncoding
 */
export const getFileByPath = async (path: string, encoding?: BufferEncoding) => {
  if (!path) return
  const res = await window.electron.ipcRenderer.invoke('read-file', path, encoding)
  return res
}

/**
 * 根据路径获取图片
 * @param path 路径
 * @param encoding 编码
 * @returns {base64, dimensions}
 */
export const getImageByPath = async (path: string) => {
  if (!path) return
  const res = await getFileByPath(path, 'base64')
  const base64 = `data:image/${path.split('.').pop()};base64,` + res
  const buffer = await getFileByPath(path)
  const dimensions = imageSize(buffer)
  return { base64, dimensions, src: `local:///${path.replaceAll('\\', '/')}` }
}

/**
 * 生成一个用不重复的ID
 * @param randomLength 随机id长度 0 - 11
 */
export function getUUID(randomLength = 6, type: 'number' | 'string' = 'string'): string {
  // 生成字符类型UUID
  if (type === 'string') {
    const buf: string[] = []
    const max = 36 // 0-9, a-z 共36个字符
    const offset = 87 // 'a'的charCodeAt值为97，97 - 10 = 87
    for (let i = 0; i < randomLength; i++) {
      const k = Math.floor(Math.random() * max)
      buf.push(k < 10 ? k.toString() : String.fromCodePoint(offset + k))
    }
    return buf.join('')
  }

  // 生成数值类型UUID
  const times = 10 ** (randomLength - 1)
  return (times + Math.floor(Math.random() * 9 * times)).toString()
}

/**
 * 获取新增控件的index
 */
export function getAddWidgetIndex(page: Page, type: string) {
  if (!type) return 1

  let count = 0
  bfsWalk(page, (node) => {
    if (node.type === type) {
      count++
    }
  })

  return count + 1
}

/**
 * 移动数组位置
 * @param arr 数组
 * @param fromIndex 原索引
 * @param toIndex 目标索引
 */
export function moveToPosition(arr, fromIndex, toIndex) {
  if (fromIndex === toIndex) return arr
  // 处理负索引（从末尾计数）
  const normalizeIndex = (i) => (i < 0 ? Math.max(0, arr.length + i) : Math.min(i, arr.length - 1))

  const normalizedFrom = normalizeIndex(fromIndex)
  const normalizedTo = normalizeIndex(toIndex)

  const [item] = arr.splice(normalizedFrom, 1)
  arr.splice(normalizedTo, 0, item)
  return arr
}

/**
 * 获取symbol值
 * @param key
 * @returns lvgl symbol
 */
export const getSymbol = (key: string) => symbols.find((item) => item.label === key)?.value

/**
 * 获取创建下一项的索引
 * @param arr 数组
 * @param key
 */
export const getNextIndex = (arr: any[], key: string) => {
  const indexs =
    arr.map((item) => Number(item[key].split('_')?.at(-1))).filter((n) => !Number.isNaN(n)) || []

  return indexs.length ? Math.max(...indexs) + 1 : 1
}

/**
 * 根据ID判断是否是后代节点
 * @param parent 父级
 * @param child 子级ID
 */
export const isDescendant = (parent: BaseWidget | Page, childId: string) => {
  return parent?.children?.some((item) => item.id === childId || isDescendant(item, childId))
}
