export const codeRenderer = (
  hot: any,
  TD: HTMLTableCellElement,
  row: number,
  col: number,
  prop: any,
  value: any,
  cellProperties: any
) => {
  while (TD.firstChild) TD.removeChild(TD.firstChild)
  const nestedRowsPlugin = hot.getPlugin('nestedRows')
  const physicalRow = nestedRowsPlugin ? nestedRowsPlugin.collapsingUI.translateTrimmedRow(row) : hot.toPhysicalRow(row)
  const rowObj = hot.getSourceDataAtRow(physicalRow)
  const container = document.createElement('div')
  container.style.display = 'flex'
  container.style.alignItems = 'center'
  container.style.gap = '6px'
  const level = nestedRowsPlugin?.dataManager.getRowLevel(physicalRow) ?? 0
  for (let i = 0; i < (level || 0); i++) {
    const spacer = document.createElement('span')
    spacer.className = 'ht_nestingLevel_empty'
    container.appendChild(spacer)
  }
  if (rowObj && Array.isArray(rowObj.__children) && rowObj.__children.length > 0) {
     
    const isCollapsed = nestedRowsPlugin?.collapsingUI.areChildrenCollapsed(physicalRow) ?? false
    const btn = document.createElement('div')
    btn.className = `ht_nestingButton ${isCollapsed ? 'ht_nestingExpand' : 'ht_nestingCollapse'}`
    btn.addEventListener('mousedown', (ev) => {
      if (ev.button !== 0) return
      ev.stopPropagation()
      ev.preventDefault()
      if (!nestedRowsPlugin) return
      const nowCollapsed = nestedRowsPlugin.collapsingUI.areChildrenCollapsed(physicalRow)
      if (nowCollapsed) nestedRowsPlugin.collapsingUI.expandChildren(physicalRow)
      else nestedRowsPlugin.collapsingUI.collapseChildren(physicalRow)
    })
    container.appendChild(btn)
  }/*else{
    container.classList.add('text-relative')
  }*/
  const text = document.createElement('span')
  text.textContent = value == null ? '' : String(value)
  text.classList.add('rowHeader')
  //解决右键行头触发上下文菜单事件
  text.addEventListener('contextmenu', (ev) => {
    ev.preventDefault()
    ev.stopPropagation()
    const e = new MouseEvent('contextmenu', {
      bubbles: true,
      cancelable: true,
      view: window,
      button: 2,
      clientX: (ev as MouseEvent).clientX,
      clientY: (ev as MouseEvent).clientY
    })
    TD.dispatchEvent(e)
  })
  container.appendChild(text)
  TD.appendChild(container)

  return TD
}

export const computeCodeColWidth = (hot: any): number => {
//   if (!hot) return codeColWidth.value
  const data = hot.getSourceData() || []
  const maxLen = data.reduce((m: number, r: any) => {
    const v = r && r.code != null ? String(r.code) : ''
    return Math.max(m, v.length)
  }, 0)
  const charWidth = 9
  const basePadding = 24
  const nested = hot.getPlugin('nestedRows')
  const levelCount = nested?.dataManager?.cache?.levelCount ?? 0
  const rootEl = hot.rootElement as HTMLElement
  const styles = rootEl ? getComputedStyle(rootEl) : null
  const iconSizeStr = styles ? styles.getPropertyValue('--ht-icon-size') : ''
  const iconSize = Number.parseFloat(iconSizeStr) || 16
  const indicatorWidth = 5
  const gap = 6
  const nestedPadding = levelCount * indicatorWidth + iconSize + gap
  const width = Math.ceil(maxLen * charWidth) + basePadding + nestedPadding
  return Math.min(Math.max(80, width), 480)
}

// 工具函数：解析 level 字符串
const parseLevel = (level: string): number[] => 
  level?.split('-').map(n => Number(n)).filter(n => !Number.isNaN(n)) ?? []

// 工具函数：根据 level 获取容器和索引
const getContainerAndIndexByLevel = (data: any[], level: string) => {
  const seg = parseLevel(level)
  if (seg.length === 0) return null
  if (seg.length === 1) return { container: data, index: seg[0], parentLevel: null }
  
  let parent = data[seg[0]]
  for (let i = 1; i < seg.length - 1; i++) {
    if (!Array.isArray(parent.__children)) parent.__children = []
    parent = parent.__children[seg[i] - 1]
    if (!parent) return null
  }
  
  const container = Array.isArray(parent.__children) ? parent.__children : (parent.__children = [])
  const index = seg[seg.length - 1] - 1
  const parentLevel = seg.slice(0, -1).join('-')
  return { container, index, parentLevel }
}

// 工具函数：根据 level 查找节点
const findNodeByLevel = (data: any[], level: string) => {
  const loc = getContainerAndIndexByLevel(data, level)
  return loc ? (loc.container[loc.index] ?? null) : null
}

// 工具函数：重新索引 level
const reindexLevels = (container: any[], parentLevel: string | null): void => {
 container.forEach((row, i) => {
    const currentLevel = parentLevel == null ? String(i) : `${parentLevel}-${i + 1}`
    row.level = currentLevel
    if (Array.isArray(row.__children) && row.__children.length > 0) {
      reindexLevels(row.__children, currentLevel)
    }
  })
}

// 统一的行操作处理函数
export const handleRowOperation = (hot: any, type: 'above' | 'below' | 'child' | 'delete') => {
  const selected = hot.getSelected()
  if (!selected || selected.length === 0) return
  
  const row = selected[0][0]
  const nestedRowsPlugin = hot.getPlugin('nestedRows')
  if (!nestedRowsPlugin) return
  
  const physicalRow = nestedRowsPlugin ? nestedRowsPlugin.collapsingUI.translateTrimmedRow(row) : hot.toPhysicalRow(row)
  const rowData = hot.getSourceDataAtRow(physicalRow)
  const currentLevel = String(rowData.level ?? '')
  const data = JSON.parse(JSON.stringify(hot.getSettings().data))
  if (type === 'delete') {
    // 删除行
    const loc = getContainerAndIndexByLevel(data, currentLevel)
    if (!loc) return
    const { container, index, parentLevel } = loc
    container.splice(index, 1)
    reindexLevels(container, parentLevel)
  } else {
    // 根据 columns 配置动态生成 newRow 对象结构
    const columns = hot.getSettings().columns || []
    const newRow: any = {
      level: null,
      __children: []
    }
    
    // 根据 columns 的 data 字段生成对象结构
    columns.forEach((col: any) => {
      if (col.data && col.data !== 'level' && col.data !== '__children') {
        newRow[col.data] = null
      }
    })
    
    if (type === 'child') {
      // 添加子行
      const parentNode = findNodeByLevel(data, currentLevel)
      if (!parentNode) return
      if (!Array.isArray(parentNode.__children)) parentNode.__children = []
      const nextIndex = parentNode.__children.length + 1
      newRow.level = `${currentLevel}-${nextIndex}`
      parentNode.__children.push(newRow)
    } else {
      // 在上方或下方插入行
      const loc = getContainerAndIndexByLevel(data, currentLevel)
      if (!loc) return
      const { container, index, parentLevel } = loc
      const insertIndex = type === 'above' ? Math.max(index, 0) : Math.max(index + 1, 0)
      container.splice(insertIndex, 0, newRow)
      reindexLevels(container, parentLevel)
    }
  }
  hot.updateSettings({ data })
  // nestedRowsPlugin.headersUI.updateRowHeaderWidth()
  hot.render()
}
