<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref, nextTick, createVNode, render, watch,computed, readonly } from 'vue'
import { Page } from '@vben/common-ui';
import { ElSplitter,ElSplitterPanel,ElCard } from 'element-plus';
import { useElementSize } from '@vueuse/core'
import { DbTree } from '#/components/db-tree';
import { DbHst } from '#/components/db-hst';

import { handleRowOperation, codeRenderer } from '#/components/db-hst/tree'
// import { sourceDataObject } from '#/components/db-hst/mockData'
const containerRef = ref<HTMLElement | null>(null)
const { height: containerHeight } = useElementSize(containerRef)
const topContainerRef = ref<HTMLElement | null>(null)
const { height: topContainerHeight } = useElementSize(topContainerRef)
const bottomContainerRef = ref<HTMLElement | null>(null)
const { height: bottomContainerHeight } = useElementSize(bottomContainerRef)

type Tree = { id: string; label: string; children?: Tree[] }
const categoryTreeData = ref<Tree[]>([
  {
    id: '1',
    label: '行业总类',
    children: [
      {
        id: '2',
        label: '广东',
        children: [
          { id: '3', label: '行业1' },
          { id: '4', label: '行业2' },
          { id: '5', label: '行业3' }
        ]
      }
    ]
  },
  {
    id: '11',
    label: '行业2',
    children: [
      {
        id: '12',
        label: '广西',
        children: [
          { id: '13', label: '行业5' },
          { id: '14', label: '行业6' },
          { id: '15', label: '行业7' }
        ]
      }
    ]
  }
])

const tagRenderer = (instance: any, td: HTMLElement, row: number, col: number, prop: string, value: any, cellProperties: any) => {
  // 清空单元格内容
  td.innerHTML = ''
  td.style.padding = '4px'
  td.style.overflow = 'visible'
  
  // 获取当前单元格的标签数据
  const getCurrentTags = (): string[] => {
    const currentValue = instance.getDataAtCell(row, col)
    // console.log(currentValue)
    if (typeof currentValue === 'string') {
      return currentValue ? currentValue.split(',').map(t => t.trim()).filter(t => t) : []
    } else if (Array.isArray(currentValue)) {
      return [...currentValue]
    }
    return []
  }
  
  // 创建容器
  const container = document.createElement('div')
  container.style.cssText = 'display: flex; flex-wrap: wrap; gap: 4px; align-items: center; min-height: 24px;'
  
  // 渲染标签
  const renderTags = () => {
    const tags = getCurrentTags()
    container.innerHTML = ''
    
    tags.forEach((tag, index) => {
      const tagEl = document.createElement('span')
      tagEl.style.cssText = `
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        background: #f0f0f0;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        font-size: 12px;
        gap: 4px;
      `
      tagEl.textContent = tag
      
      // 删除按钮
      const closeBtn = document.createElement('span')
      closeBtn.innerHTML = '×'
      closeBtn.style.cssText = `
        cursor: pointer;
        font-size: 14px;
        font-weight: bold;
        color: #999;
        margin-left: 2px;
      `
      closeBtn.onmouseover = () => closeBtn.style.color = '#333'
      closeBtn.onmouseout = () => closeBtn.style.color = '#999'
      closeBtn.onclick = (e) => {
        e.stopPropagation()
        const currentTags = getCurrentTags()
        currentTags.splice(index, 1)
        instance.setDataAtCell(row, col, currentTags.join(','))
        renderTags()
      }
      
      tagEl.appendChild(closeBtn)
      container.appendChild(tagEl)
    })
    
    // 添加输入框
    const inputWrapper = document.createElement('span')
    inputWrapper.style.cssText = 'display: inline-flex; align-items: center;'
    
    const input = document.createElement('input')
    input.type = 'text'
    input.placeholder = '按Enter回车键添加'
    //border: 1px solid #d9d9d9;
    input.style.cssText = `

      border-radius: 4px;
      padding: 2px 8px;
      font-size: 12px;
      outline: none;
      width: 100%;
    `
    
    input.onfocus = () => {
      input.style.borderColor = '#409eff'
    }
    
    input.onblur = () => {
      input.style.borderColor = '#d9d9d9'
      
      // 失去焦点时添加标签
      if (input.value.trim()) {
        const newTag = input.value.trim()
        const currentTags = getCurrentTags()
        console.log('添加前的标签:', currentTags)
        if (!currentTags.includes(newTag)) {
          currentTags.push(newTag)
          console.log('添加后的标签:', currentTags)
          instance.setDataAtCell(row, col, currentTags.join(','))
          input.value = ''
          renderTags()
        } else {
          input.value = ''
        }
      }
    }
    
    input.onkeydown = (e) => {
      // 保留 Enter 键功能，按 Enter 也可以添加
      if (e.key === 'Enter' && input.value.trim()) {
        e.preventDefault()
        input.blur() // 触发失去焦点事件
      }
    }
    
    inputWrapper.appendChild(input)
    container.appendChild(inputWrapper)
  }
  
  renderTags()
  td.appendChild(container)
  
  return td
}

const bottomColumns = ref<any[]>([
  {type:'text',data:'code',title:'序号'},
  {type:'text',data:'name',title:'名称'},
  {type:'text',data:'content',title:'内容',width: 300, renderer: tagRenderer, readOnly:true},
  {type:'text',data:'spec',title:'代码'},

])
// const colHeaders = ref<string[]>(topColHeaders)

const bottomHstRef = ref<any>(null)

const bootomMock = ()=>{
    // 生成模拟数据
    const mockData = Array.from({ length: 30 }, (_, index) => ({
      code: `DTL${String(index + 1).padStart(6, '0')}`,
      name: `明细项目${index + 1}`,
      content: ``,
      spec: `规格${index + 1}`,
    }))
    return mockData;
}
let bottomDbSettings = {
  columns: bottomColumns.value,
}
const categoryHandleSelect = (node: Tree) => {
  console.log('categoryhandleSelect',node)
}

const detailHandleSelect = (node: Tree) => {
  // if (topHstRef.value && typeof topHstRef.value.loadData === 'function') {
  //   // console.log('hstData.value',hstData.value)
  //   // topHstRef.value.loadData(topHstData.value)
  // }
}
function onBottomHeight(height: number){
  if (bottomHstRef.value?.hotInstance) {
    bottomHstRef.value.hotInstance.updateSettings({
      height: height-15
    })
    
    bottomHstRef.value.loadData(bootomMock())
    bottomHstRef.value.hotInstance.render()
    console.log('onResizeEnd-bottomHstRef',height);
  }
}


onMounted(() => {
  setTimeout(() => {
    onBottomHeight(bottomContainerHeight.value)
  }, 200);
})
onUnmounted(() => {
})

</script>

<template>
<Page auto-content-height>
   <ElSplitter >
      <ElSplitterPanel collapsible size="15%" :min="200">
        <ElCard class="w-full h-full border-radius-0" body-class="!p-0 h-full" ref="containerRef">
            <DbTree :height="containerHeight" :data="categoryTreeData" @select="categoryHandleSelect" :defaultExpandedKeys="2"  :search="false" />
        </ElCard>
      </ElSplitterPanel>
      <ElSplitterPanel collapsible :min="200">
        <ElCard class="w-full h-full border-radius-0" body-class="!p-0 h-full">
            <DbHst ref="bottomHstRef" :settings="bottomDbSettings"></DbHst>
        </ElCard>
      </ElSplitterPanel>
    </ElSplitter>
</Page>
</template>

<style lang="css">
    
</style>
