<template>
  <a-card :title="title" :bordered="true">
    <a-tree
      :load-data="onLoadData"
      :tree-data="treeData"
      @select="handleSelect"
      style="overflow: hidden; overflow-wrap: normal;"
    />
  </a-card>
</template>

<script>
import { getAction } from '@api/manage'

export default {
  name: 'DeviceTree',
  props: {
    maxLevel: {
      type: Number,
      default: -1,
      required: false,
    },
    title: {
      type: String,
      default: '设备构型',
      required: false,
    },
  },
  data() {
    return {
      treeData: [],
      urlList: {
        listAllType: '/device/buDeviceType/list/deviceType', // 设备类型树
        listAllDevice: '/device/buDevice/list',              // 具体设备列表
        listAllPart: '/device/part/list',                    // 部件树
      },
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    handleSelect(key, e) {
      console.log('设备树选择', key, e)
      this.$emit('select-device', key, e.node.dataRef.nodeType)
    },

    // 初始加载：设备类型根节点
    loadData() {
      getAction(this.urlList.listAllType).then((res) => {
        if (res.success) {
          this.treeData = this.buildDeviceTypeNodes(res.result, 0)
        }
      })
    },

    // 构建设备类型节点（支持多层）
    buildDeviceTypeNodes(items, level) {
      if (!items || !Array.isArray(items)) return []
      return items.map(item => {
        const hasSub = item.subTypes && item.subTypes.length > 0
        const isLeafByMax = this.maxLevel !== -1 && level >= this.maxLevel

        return {
          key: item.id,
          title: `${item.typeName}(${item.typeCode})`,
          level,
          nodeType: 'deviceType',
          // 缓存子类型用于懒展开
          rawSubTypes: !isLeafByMax && hasSub ? item.subTypes : null,
          children: [],
          // ⭐ 设备类型永远不是叶子！即使无 subTypes，也要加载具体设备
          isLeaf: false,
        }
      })
    },

    // 构建具体设备节点（来自 listAllDevice）
    buildDeviceNodes(records, level) {
      if (!records || !Array.isArray(records)) return []
      return records.map(item => ({
        key: item.id,
        title: `${item.deviceName}(${item.deviceCode})`,
        level,
        nodeType: 'device',
        children: [],
        // 设备节点默认可展开（加载部件），除非被 maxLevel 限制
        isLeaf: this.maxLevel !== -1 && level >= this.maxLevel,
      }))
    },

    // 构建部件节点（支持多层嵌套）
    buildPartNodes(items, level) {
      if (!items || !Array.isArray(items)) return []
      return items.map(item => {
        const hasChildren = item.children && item.children.length > 0
        const isLeafByMax = this.maxLevel !== -1 && level >= this.maxLevel

        return {
          key: item.id,
          title: `${item.name}(${item.serialCode})`,
          level,
          nodeType: 'part',
          rawChildren: !isLeafByMax && hasChildren ? item.children : null,
          children: [],
          isLeaf: isLeafByMax || !hasChildren,
        }
      })
    },

    // 统一懒加载逻辑
    onLoadData(treeNode) {
      const dataRef = treeNode.dataRef
      if (!dataRef) return Promise.resolve()

      // 情况1：有缓存的子数据（设备类型 or 部件）
      if (dataRef.rawSubTypes || dataRef.rawChildren) {
        const nextLevel = dataRef.level + 1
        let children = []

        if (dataRef.nodeType === 'deviceType') {
          children = this.buildDeviceTypeNodes(dataRef.rawSubTypes, nextLevel)
          dataRef.rawSubTypes = null
        } else if (dataRef.nodeType === 'part') {
          children = this.buildPartNodes(dataRef.rawChildren, nextLevel)
          dataRef.rawChildren = null
        }

        dataRef.children = children
        return Promise.resolve()
      }

      // 情况2：设备类型节点 → 加载具体设备
      if (dataRef.nodeType === 'deviceType') {
        return getAction(this.urlList.listAllDevice, {
          deviceTypeId: dataRef.key,
          pageNo: 1,
          pageSize: 100,
        }).then((res) => {
          if (res.success && res.result.records) {
            const nextLevel = dataRef.level + 1
            const deviceNodes = this.buildDeviceNodes(res.result.records, nextLevel)
            dataRef.children = deviceNodes
            // 如果没设备，可考虑标记为叶子（可选）
            if (deviceNodes.length === 0) {
              dataRef.isLeaf = true
            }
          }
        }).catch(err => {
          console.error('加载具体设备失败:', err)
          return Promise.reject(err)
        })
      }

      // 情况3：具体设备节点 → 加载其下的部件树
      if (dataRef.nodeType === 'device') {
        return getAction(this.urlList.listAllPart, {
          device: dataRef.key, // 注意：参数名是 device
          pageNo: 1,
          pageSize: 1000,
        }).then((res) => {
          if (res.success && res.result.records) {
            const nextLevel = dataRef.level + 1
            const partNodes = this.buildPartNodes(res.result.records, nextLevel)
            dataRef.children = partNodes
          }
        }).catch(err => {
          console.error('加载部件失败:', err)
          return Promise.reject(err)
        })
      }

      // 情况4：部件叶子节点（无需处理）

      return Promise.resolve()
    },
  },
}
</script>

<style scoped></style>