<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,ElDialog,ElTable,ElTableColumn,ElButton } 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 { manualRowMoveRenderer } from '#/components/db-hst/sort'

const containerRef = ref<HTMLElement | null>(null)
const { height: containerHeight } = useElementSize(containerRef)

type Tree = { id: string; label: string; children?: Tree[] }
const treeData = 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费率库' }
        ]
      }
    ]
  }
])


// 自定义渲染器：根据checkbox状态显示'更多'按钮
const settingRenderer = (instance: any, td: HTMLElement, row: number, col: number, prop: string, value: any, cellProperties: any) => {
  td.innerHTML = ''
  const rowData = instance.getSourceDataAtRow(row)
  
  if (rowData && rowData.priceExTax) {
    const link = document.createElement('a')
    link.textContent = '更多'
    link.style.color = '#409eff'
    link.style.cursor = 'pointer'
    link.style.textDecoration = 'underline'
    link.onclick = (e) => {
      e.preventDefault()
      openDialog(row)
    }
    td.appendChild(link)
  }
  
  return td
}

const topColumns = ref<any[]>([
{type:'text',data:'sort',title:'⇅', renderer: manualRowMoveRenderer,
  width: 40,
    readOnly: true,
    editor: false,
},
{type:'text',data:'code',title:'编码', renderer: codeRenderer},
{type:'text',data:'name',title:'费率项'},
{type:'text',data:'unit',title:'费率代号(%)'},
{type:'checkbox',data:'priceExTax',title:'埴',width: 40},
{type:'text',data:'priceInTax',title:'设置',width: 60, renderer: settingRenderer, readOnly: true}
])


const topHstRef = ref<any>(null)
let rowSchema: any = {}
// 根据 columns 的 data 字段生成对象结构
topColumns.value.forEach((col: any) => {
  if (col.data ) {
    rowSchema[col.data] = null
  }
})
// console.log(rowSchema)
// Dialog相关状态
const dialogVisible = ref(false)
const currentRow = ref<number>(0)
const dialogTableData = ref<any[]>([
  { base: '基数1', method: '小于等于', earthwork: '10', stonework: '20', transport: '30', pavement: '40', col1: '', col2: '' },
  { base: '基数2', method: '每增加', earthwork: '15', stonework: '25', transport: '35', pavement: '45', col1: '', col2: '' }
])

const openDialog = (row: number) => {
  currentRow.value = row
  dialogVisible.value = true
}

const topMock = ()=>{
    // 生成父子级模拟数据
    const mockData: any[] = []
    
    // 生成5个父级数据
    for (let i = 1; i <= 5; i++) {
      const parent = {
        code: `FL${String(i).padStart(6, '0')}`,
        name: `费率项目${i}`,
        unit: `${(Math.random() * 15 + 1).toFixed(2)}`,
        priceExTax: i % 2 === 0, // checkbox值改为boolean
        priceInTax: '',
        __children: [] as any[]
      }
      
      // 为每个父级生成3-5个子级
      const childCount = Math.floor(Math.random() * 3) + 3
      for (let j = 1; j <= childCount; j++) {
        const child = {
          code: `FL${String(i).padStart(6, '0')}-${String(j).padStart(3, '0')}`,
          name: `费率子项${i}-${j}`,
          unit: `${(Math.random() * 15 + 1).toFixed(2)}`,
          priceExTax: j % 2 === 1, // checkbox值改为boolean
          priceInTax: ''
        }
        parent.__children.push(child)
      }
      
      mockData.push(parent)
    }
    
    return mockData;
}
let topDbSettings = {
  data: topMock(),
  dataSchema: rowSchema,
  colWidths: 120,
  columns: topColumns.value,
  manualRowMove: true,
  rowHeaders: false,
  nestedRows: true,
  bindRowsWithHeaders: true,
  afterChange: (changes: any, source: string) => {
    if (source === 'edit' && changes) {
      changes.forEach(([row, prop]: [number, string]) => {
        if (prop === 'priceExTax' && topHstRef.value?.hotInstance) {
          // 当checkbox改变时，重新渲染设置列
          topHstRef.value.hotInstance.render()
        }
      })
    }
  },
  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 treeHandleSelect = (node: Tree) => {
  console.log('treeHandleSelect',node)
}

function onTopHeight(height: number){
  if (topHstRef.value?.hotInstance) {
    topHstRef.value.hotInstance.updateSettings({
      height: height-15,
    })
    // 更新 code 列的宽度
    topHstRef.value.updateCodeColWidth()
    
    topHstRef.value.hotInstance.render()
    
    // console.log('onResizeEnd-onTopHeight',height, 'codeColWidth:', topHstRef.value.codeColWidth);
  }
}

// 直接使用配置对象，DbTree 会自动创建 HierarchyContextMenuHandler
const contextMenuHandler = {
  rootKey: 'add-category',
  rootText: '添加单价费率库',
  levels: [
    {
      depth: 0,
      addKey: 'add-province',
      addText: '添加省市',
      allowDelete: true
    },
    {
      depth: 1,
      addKey: 'add-name',
      addText: '添加名称',
      allowDelete: true
    },
    {
      depth: 2,
      addKey: 'add-model',
      addText: '添加模式',
      allowDelete: true
    },
    {
      depth: 3,
      allowDelete: true
    }
  ]
}
onMounted(() => {
  setTimeout(() => {
    onTopHeight(containerHeight.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="treeData" @select="treeHandleSelect" :defaultExpandedKeys="3" :context-menu-handler="contextMenuHandler"  :search="false" />
        </ElCard>
      </ElSplitterPanel>
      <ElSplitterPanel collapsible :min="200">
        <ElCard class="w-full h-full" body-class="!p-0 h-full">
            <DbHst ref="topHstRef" :settings="topDbSettings"></DbHst>
        </ElCard>
      </ElSplitterPanel>
    </ElSplitter>

    <!-- 弹窗 -->
    <ElDialog v-model="dialogVisible" title="费率详细设置" width="50%" :close-on-click-modal="false">
      <ElTable :data="dialogTableData" border style="width: 100%">
        <ElTableColumn prop="base" label="基数" width="120" />
        <ElTableColumn prop="method" label="取值方式" width="150">
          <template #default="{ row }">
            <el-select v-model="row.method" placeholder="请选择">
              <el-option label="小于等于" value="小于等于" />
              <el-option label="每增加" value="每增加" />
            </el-select>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="earthwork" label="土方" width="100" />
        <ElTableColumn prop="stonework" label="石方" width="100" />
        <ElTableColumn prop="transport" label="运输" width="100" />
        <ElTableColumn prop="pavement" label="路面" width="100" />
        <ElTableColumn prop="col1" label="插入列1" width="" />
        <ElTableColumn prop="col2" label="插入列2" width="" />
      </ElTable>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="dialogVisible = false">确定</ElButton>
      </template>
    </ElDialog>
</Page>
</template>

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