<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref, nextTick, createVNode, render, watch,computed } 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: '广东工民建工料机' },
          { id: '4', label: '广东公路工料机' },
          { id: '5', label: '广东水利工料机' }
        ]
      }
    ]
  },
  {
    id: '11',
    label: '工料机总类2',
    children: [
      {
        id: '12',
        label: '广西',
        children: [
          { id: '13', label: '工料机1' },
          { id: '14', label: '工料机1' },
          { id: '15', label: '工料机2' }
        ]
      }
    ]
  }
])
const topColumns = ref<any[]>([
{type:'text',data:'code',title:'编码', renderer: codeRenderer},
{type:'text',data:'name',title:'名称'},
{type:'text',data:'unit',title:'单位'},
])

const bottomColumns = ref<any[]>([
  {type:'text',data:'code',title:'特征编码'},
  {type:'text',data:'name',title:'名称'},
  {type:'text',data:'spec',title:'代码'},

])
// const colHeaders = ref<string[]>(topColHeaders)
const topHstRef = ref<any>(null)
const bottomHstRef = ref<any>(null)
let rowSchema: any = {level: null,__children: []}
    
// 根据 columns 的 data 字段生成对象结构
topColumns.value.forEach((col: any) => {
  if (col.data && col.data !== 'level' && col.data !== '__children') {
    rowSchema[col.data] = null
  }
})
// console.log(rowSchema)

const topMock = ()=>{
  // 生成带层级结构的模拟数据
  const categories = ['人', '人机', '材', '机']
  const units = ['台', '个', 't', 'm³', 'm²', 'kg']
  
  const mockData = []
  let codeCounter = 1
  
  // 生成5个父级项目
  for (let i = 0; i < 5; i++) {
    const parentCode = `MAC${String(codeCounter++).padStart(6, '0')}`
    const parent = {
      code: parentCode,
      name: `机械设备分类${i + 1}`,
      unit: units[i % units.length],
      level: String(i),
      __children: []
    }
    
    // 为每个父级生成2-4个子项
    const childCount = Math.floor(Math.random() * 3) + 2
    for (let j = 0; j < childCount; j++) {
      const childCode = `${parentCode}-${String(j + 1).padStart(3, '0')}`
      const child = {
        code: childCode,
        name: `${parent.name}-子项${j + 1}`,
        unit: units[(i + j) % units.length],
        level: `${i}-${j + 1}`,
        __children: []
      }
      
      // 为部分子项生成孙项
      if (j === 0 && i < 3) {
        const grandChildCount = Math.floor(Math.random() * 2) + 1
        for (let k = 0; k < grandChildCount; k++) {
          const grandChild = {
            code: `${childCode}-${String(k + 1).padStart(2, '0')}`,
            name: `${child.name}-明细${k + 1}`,
            unit: units[(i + j + k) % units.length],
            level: `${i}-${j + 1}-${k + 1}`,
            __children: []
          }
          child.__children.push(grandChild)
        }
      }
      
      parent.__children.push(child)
    }
    
    mockData.push(parent)
  }
  
  return mockData
}

let topDbSettings = {
  data: topMock(),
  dataSchema: rowSchema,
  colWidths: 120,
  columns: topColumns.value,
  // preventOverflow: 'horizontal',
  rowHeaders: false,
  nestedRows: true,
  bindRowsWithHeaders: true,
  contextMenu: {
    items: {
      custom_row_above: {
        name: '在上方插入行',
        callback: function() {
          handleRowOperation(this, 'above')
        }
      },
      custom_row_below: {
        name: '在下方插入行',
        callback: function() {
          handleRowOperation(this, 'below')
        }
      },
      separator1: '---------',
      custom_add_child: {
        name: '添加子行',
        callback: function() {
          handleRowOperation(this, 'child')
        }
      },
      separator2: '---------',
      remove_row: {
        name: '删除行',
        callback: function() {
          handleRowOperation(this, 'delete')
        }
      },
      // separator3: '---------',
      // undo: {},
      // redo: {}
    }
  },
}
const bootomMock = ()=>{
    // 生成模拟数据
    const categories = ['人', '人机', '材', '机']
    const units = ['台', '个', 't', 'm³', 'm²', 'kg']
    const mockData = Array.from({ length: 30 }, (_, index) => ({
      code: `DTL${String(index + 1).padStart(6, '0')}`,
      name: `明细项目${index + 1}`,
      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)
  }
}
// watch(
//   () => topContainerHeight.value,
//   (val) => {
//     console.log('topContainerHeight', val);
//   },
//   { immediate: true },
// )

function onTopHeight(height: number){
  if (topHstRef.value?.hotInstance) {
    topHstRef.value.hotInstance.updateSettings({
      height: height-15,
    })
    
    // topHstRef.value.loadData(topMock())
    
    // 更新 code 列的宽度
    topHstRef.value.updateCodeColWidth()
    
    console.log('onResizeEnd-onTopHeight',height, 'codeColWidth:', topHstRef.value.codeColWidth);
  }
}
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(() => {
    onTopHeight(topContainerHeight.value)
    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="topHstRef" :settings="topDbSettings"></DbHst>
        </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>
