<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,ElTabs,ElTabPane } from 'element-plus';
import { useElementSize } from '@vueuse/core'
import { DbTree } from '#/components/db-tree';
import { DbHst } from '#/components/db-hst';
// 懒加载各个标签页组件
import SubItemMaterials from './price/SubItemMaterials.vue'
import MarketMaterials from './price/MarketMaterials.vue'
import QuotaAdjustmentSetting from './price/QuotaAdjustmentSetting.vue'
import QuotaAdjustment from './price/QuotaAdjustment.vue'
import QuotaDescription from './price/QuotaDescription.vue'
// import BaseSummary from './price/BaseSummary.vue'

const containerRef = ref<HTMLElement | null>(null)
const activeTab = ref('subItem')
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)
const bottomPanelHeight = ref<number>(0)

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: '工料机2定额' },
          { id: '15', label: '工料机3定额' }
        ]
      }
    ]
  }
])
const detailTreeData = 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: '塑料工程' },
          { id: '14', label: '塑胶工程' },
          { id: '15', label: '非金属工程' }
        ]
      }
    ]
  }
])

const topColumns = ref<any[]>([
{type:'text',data:'code',title:'编码'},
{type:'text',data:'name',title:'名称'},
{type:'text',data:'unit',title:'单位'},
{type:'text',data:'priceExTax',title:'除税定额单价'},
{type:'text',data:'priceInTax',title:'含税定额单价'},
{type:'text',data:'priceExTaxComp',title:'除税编制单价'},
{type:'text',data:'priceInTaxComp',title:'含税编制单价'}
])

const bottomColumns = ref<any[]>([
  {type:'text',data:'code',title:'编码'},
  {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:'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 topHstRef = ref<any>(null)
const bottomHstRef = ref<any>(null)
let rowSchema: any = {}
// 根据 columns 的 data 字段生成对象结构
topColumns.value.forEach((col: any) => {
  if (col.data ) {
    rowSchema[col.data] = null
  }
})
// console.log(rowSchema)
const topMock = ()=>{
    // 生成模拟数据
    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 topDbSettings = {
  data: topMock(),
  dataSchema: rowSchema,
  colWidths: 120,
  columns: topColumns.value,
  contextMenu: ['row_above','row_below','cut','copy','remove_row']

}

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 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-15,
    })
    
    
    topHstRef.value.hotInstance.render()
    
    // console.log('onResizeEnd-onTopHeight',height, 'codeColWidth:', topHstRef.value.codeColWidth);
  }
}
function onBottomHeight(height: number){
  bottomPanelHeight.value = height
}

// 直接使用配置对象，DbTree 会自动创建 HierarchyContextMenuHandler
const contextMenuHandler = {
  rootKey: 'add-category',
  rootText: '添加定额总类',
  levels: [
    {
      depth: 0,
      addKey: 'add-province',
      addText: '添加省市',
      allowDelete: true
    },
    {
      depth: 1,
      addKey: 'add-specialty',
      addText: '添加定额专业',
      allowDelete: true
    },
    {
      depth: 2,
      allowDelete: true
    }
  ]
}
onMounted(() => {
  setTimeout(() => {
    onTopHeight(topContainerHeight.value)

    // onBottomHeight(bottomContainerHeight.value)
    // console.log(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" :context-menu-handler="contextMenuHandler"  :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">
                  <ElTabs v-model="activeTab" type="border-card" class="quota-tabs">
                    <ElTabPane label="子目工料机" name="subItem" lazy>
                      <SubItemMaterials v-if="activeTab === 'subItem'" :height="bottomPanelHeight" />
                    </ElTabPane>
                    <ElTabPane label="市场主材设备" name="market" lazy>
                      <MarketMaterials v-if="activeTab === 'market'" :height="bottomPanelHeight"/>
                    </ElTabPane>
                    <ElTabPane label="定额调整设置" name="adjustQuery" lazy>
                      <QuotaAdjustmentSetting v-if="activeTab === 'adjustQuery'" :height="bottomPanelHeight"/>
                    </ElTabPane>
                    <ElTabPane label="定额调整" name="adjust" lazy>
                      <QuotaAdjustment v-if="activeTab === 'adjust'" :height="bottomPanelHeight"/>
                    </ElTabPane>
                    <ElTabPane label="定额说明" name="description" lazy>
                      <QuotaDescription v-if="activeTab === 'description'" :height="bottomPanelHeight"/>
                    </ElTabPane>
                    <!-- <ElTabPane label="基数类别汇总" name="baseSummary" lazy>
                      <BaseSummary v-if="activeTab === 'baseSummary'" :height="bottomPanelHeight"/>
                    </ElTabPane> -->
                  </ElTabs>
            </ElCard>
          </ElSplitterPanel>
        </ElSplitter>
      </ElSplitterPanel>
    </ElSplitter>
</Page>
</template>

<style lang="css">
/* .quota-tabs {
  height: 100%;
}

.quota-tabs :deep(.ElTabs__content) {
  height: calc(100% - 40px);
  overflow: auto;
}

.quota-tabs :deep(.ElTabPane) {
  height: 100%;
} */
.el-tabs--border-card>.el-tabs__content  {
    padding: 5px 0;
}
</style>
