<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 { topColHeaders } from './machine'
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 detailTreeData = ref<Tree[]>([
  {
    id: '1',
    label: '目录1',
    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: '塑料' },
          { id: '14', label: '塑胶' },
          { id: '15', label: '非金属' }
        ]
      }
    ]
  }
])
const topColumns = ref<any[]>([
{type:'text',data:'code',title:'编码', renderer: codeRenderer},
{type:'text',data:'name',title:'名称'},
{type:'text',data:'spec',title:'型号规格'},
{type:'text',data:'category',title:'类别'},
{type:'text',data:'unit',title:'单位'},
{type:'text',data:'taxRate',title:'税率'},
{type:'text',data:'priceExTax',title:'除税基价'},
{type:'text',data:'priceInTax',title:'含税基价'},
{type:'text',data:'priceExTaxComp',title:'除税编制价'},
{type:'text',data:'priceInTaxComp',title:'含税编制价'},
{type:'text',data:'calcBase',title:'计算基数'}
])
const tableHeaders = ref<string[]>([
  '编码',
  '名称',
  '型号规格',
  '类别',
  '单位',
  '税率',
  '除税基价',
  '含税基价',
  '除税编制价',
  '含税编制价',
  '计算基数'
])

// 生成 tableData 模拟数据
const generateTableData = () => {
  const categories = ['人', '人机', '材', '机']
  const units = ['台', '个', 't', 'm³', 'm²', 'kg']
  
  return Array.from({ length: 20 }, (_, index) => ({
    code: `TBL${String(index + 1).padStart(6, '0')}`,
    name: `表格项目${index + 1}`,
    spec: `规格${index + 1}`,
    category: categories[index % categories.length],
    unit: units[index % units.length],
    taxRate: `${(Math.random() * 0.13 + 0.03).toFixed(2)}`,
    priceExTax: (Math.random() * 8000 + 800).toFixed(2),
    priceInTax: (Math.random() * 9000 + 900).toFixed(2),
    priceExTaxComp: (Math.random() * 8500 + 850).toFixed(2),
    priceInTaxComp: (Math.random() * 9500 + 950).toFixed(2),
    calcBase: (Math.random() * 80 + 1).toFixed(2)
  }))
}

const tableData = ref<any[]>(generateTableData())
const bottomColumns = ref<any[]>([
  {type:'text',data:'code',title:'编码'},
  {type:'text',data:'name',title:'名称',
    renderer: 'db-table',
    customDropdownSource: tableData.value,
    customGetLabel: (item: any) => item?.name,
    customTableHeaders: tableHeaders.value,
    // 自定义字段键，按顺序对应表头
    customFieldKeys: ['code', 'name', 'spec', 'category', 'unit', 'taxRate', 'priceExTax', 'priceInTax', 'priceExTaxComp', 'priceInTaxComp', 'calcBase'],
    // 自定义搜索字段
    customSearchFields: ['code', 'name', 'spec', 'category', 'unit']
  },
  {type:'text',data:'spec',title:'型号规格'},
{type:'text',data:'category',title:'类别'},
{type:'text',data:'unit',title:'单位'},
{type:'text',data:'taxRate',title:'税率'},
{type:'text',data:'priceExTax',title:'除税基价'},

{type:'text',data:'priceExTax1',title:'除税编制价'},
{type:'text',data:'priceExTax2',title:'含税编制价'},
{type:'text',data:'priceExTax3',title:'定额消耗量'},
{type:'text',data:'priceExTax4',title:'含税编制合价'},
{type:'text',data:'priceExTax5',title:'除税基价合价'},
{type:'text',data:'priceExTax6',title:'含税基价合价'},
{type:'text',data:'priceExTax7',title:'除税编制合价'},
{type:'text',data:'calcBase',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}`,
      spec: `规格${i + 1}`,
      category: categories[i % categories.length],
      unit: units[i % units.length],
      taxRate: `${(Math.random() * 0.13 + 0.03).toFixed(2)}`,
      priceExTax: (Math.random() * 10000 + 1000).toFixed(2),
      priceInTax: (Math.random() * 11000 + 1100).toFixed(2),
      priceExTaxComp: (Math.random() * 10500 + 1050).toFixed(2),
      priceInTaxComp: (Math.random() * 11500 + 1150).toFixed(2),
      calcBase: (Math.random() * 100 + 1).toFixed(2),
      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}`,
        spec: `规格${i + 1}-${j + 1}`,
        category: categories[(i + j) % categories.length],
        unit: units[(i + j) % units.length],
        taxRate: `${(Math.random() * 0.13 + 0.03).toFixed(2)}`,
        priceExTax: (Math.random() * 5000 + 500).toFixed(2),
        priceInTax: (Math.random() * 5500 + 550).toFixed(2),
        priceExTaxComp: (Math.random() * 5200 + 520).toFixed(2),
        priceInTaxComp: (Math.random() * 5700 + 570).toFixed(2),
        calcBase: (Math.random() * 50 + 1).toFixed(2),
        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}`,
            spec: `规格${i + 1}-${j + 1}-${k + 1}`,
            category: categories[(i + j + k) % categories.length],
            unit: units[(i + j + k) % units.length],
            taxRate: `${(Math.random() * 0.13 + 0.03).toFixed(2)}`,
            priceExTax: (Math.random() * 2000 + 200).toFixed(2),
            priceInTax: (Math.random() * 2200 + 220).toFixed(2),
            priceExTaxComp: (Math.random() * 2100 + 210).toFixed(2),
            priceInTaxComp: (Math.random() * 2300 + 230).toFixed(2),
            calcBase: (Math.random() * 20 + 1).toFixed(2),
            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}`,
      category: categories[index % categories.length],
      unit: units[index % units.length],
      taxRate: `${(Math.random() * 0.13 + 0.03).toFixed(2)}`,
      priceExTax: (Math.random() * 5000 + 500).toFixed(2),
      priceExTax1: (Math.random() * 5200 + 520).toFixed(2),
      priceExTax2: (Math.random() * 5800 + 580).toFixed(2),
      priceExTax3: (Math.random() * 10 + 1).toFixed(2),
      priceExTax4: (Math.random() * 60000 + 6000).toFixed(2),
      priceExTax5: (Math.random() * 55000 + 5500).toFixed(2),
      priceExTax6: (Math.random() * 62000 + 6200).toFixed(2),
      priceExTax7: (Math.random() * 58000 + 5800).toFixed(2),
      calcBase: (Math.random() * 100 + 1).toFixed(2)
    }))
    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)
  }
  // // 访问内部的 hotTableComponent
  // if (dbHstRef.value?.hotTableComponent) {
  //   console.log('hotTableComponent', dbHstRef.value.hotTableComponent)
  // }
  // // 访问 hotInstance
  // if (dbHstRef.value?.hotInstance) {
  //   dbHstRef.value?.hotInstance.loadData(topHstData.value)
  //   console.log('hotInstance', dbHstRef.value.hotInstance)
  // }
}
// watch(
//   () => topContainerHeight.value,
//   (val) => {
//     console.log('topContainerHeight', val);
//   },
//   { immediate: true },
// )
function onResizeEnd(index: number, sizes: number[]) {
  // 通过 hotInstance 来操作 Handsontable
  console.log(index,sizes)
  onTopHeight(sizes[0])
  onBottomHeight(sizes[1])
}
function onTopHeight(height: number){
  if (topHstRef.value?.hotInstance) {
    topHstRef.value.hotInstance.updateSettings({
      height: height,
    })
    
    // 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
    })
    
    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 size="15%" :min="200">
        <ElCard class="w-full h-full border-radius-0" body-class="!p-0 h-full">
            <DbTree :height="containerHeight" :data="detailTreeData" @select="detailHandleSelect" :defaultExpandedKeys="2"  :search="false" />
        </ElCard>
      </ElSplitterPanel>
      <ElSplitterPanel >
        <ElSplitter layout="vertical" @resize-end="onResizeEnd">
          <ElSplitterPanel collapsible size="60%" :min="200">
            <ElCard class="w-full h-full" body-class="!p-0 h-full" ref="topContainerRef">
                <DbHst ref="topHstRef" :settings="topDbSettings"></DbHst>
            </ElCard>
          </ElSplitterPanel>
          <ElSplitterPanel collapsible :min="200">
            <ElCard class="w-full h-full" body-class="!p-0 h-full" ref="bottomContainerRef">
                <DbHst ref="bottomHstRef" :settings="bottomDbSettings"></DbHst>
            </ElCard>
          </ElSplitterPanel>
        </ElSplitter>
      </ElSplitterPanel>
    </ElSplitter>
</Page>
</template>

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