<script setup lang="ts">
import { getQuotaCatalogItemTree } from '#/api/database/quota/index';
import { DbTree } from '#/components/db-tree';
import { Page } from '@vben/common-ui';
import { ElCard, ElSplitter, ElSplitterPanel } from 'element-plus';
import { onMounted, onUnmounted, ref } from 'vue';

// 导入子组件
import VariableSettings from './unit/VariableSettings.vue';

type Tree = { id: string; label: string; children?: Tree[];[key: string]: any }
const treeData = ref<Tree[]>([])
const selectedNode = ref<any>(null)

// 转换后端数据为树形结构（后端已通过 exclude: 'rate_mode' 过滤掉费率模式节点）
const transformTreeData = (data: any[]): Tree[] => {
  if (!data || !Array.isArray(data)) {
    console.warn('transformTreeData: 数据不是数组', data)
    return []
  }

  return data.map(item => {
    const treeNode: Tree = {
      ...item,
      id: String(item.id),
      label: item.name || item.label || '未命名',
    }

    if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      treeNode.children = transformTreeData(item.children)
    }

    return treeNode
  })
}

// 加载定额专业树（排除 rate_mode 节点，与定额基价页面一致）
const loadCategoryTree = async () => {
  try {
    const res = await getQuotaCatalogItemTree({ exclude: 'rate_mode,majors,fields_majors' })
    console.log('定额专业树原始数据:', res)
    treeData.value = transformTreeData(res)
    console.log('定额专业树转换后数据:', treeData.value)
  } catch (error) {
    console.error('加载定额专业树失败:', error)
  }
}

// 处理树节点点击（只有 specialty 节点才显示变量设置）
const handleNodeClick = (payload: { node: any, data: any, event: MouseEvent }) => {
  const { node, data } = payload
  console.log('节点点击:', node, data)
  // 只有定额专业节点才显示变量设置
  if (data.nodeType === 'specialty') {
    selectedNode.value = data
  } else {
    selectedNode.value = null
  }
}

onMounted(() => {
  loadCategoryTree()
})
onUnmounted(() => {
})

</script>

<template>
<Page auto-content-height>
   <ElSplitter>
      <ElSplitterPanel size="15%" :min="200">
        <ElCard class="w-full h-full border-radius-0" body-class="!p-0 h-full w-full flex flex-col">
            <DbTree
              ref="treeRef"
              :tree-data="treeData"
              :draggable="false"
              :default-expanded-level="3"
              @node-click="handleNodeClick"
            />
        </ElCard>
      </ElSplitterPanel>
      <ElSplitterPanel :min="200">
        <ElCard class="w-full h-full border-radius-0" body-class="!p-0 h-full w-full">
          <VariableSettings  :selectedNode="selectedNode"/>
        </ElCard>
      </ElSplitterPanel>
    </ElSplitter>
</Page>
</template>

<style lang="scss">
.el-tabs--border-card>.el-tabs__content  {
  padding: 0 !important;
}
</style>
