<template>
  <div class="room-tree-container">
    <el-tree ref="tree" :data="treeData" node-key="id" :props="defaultProps" :highlight-current="true"
      :expand-on-click-node="false" @node-click="handleNodeClick">
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span>
          <i :class="data.icon" style="margin-right: 5px"></i>
          {{ node.label }}
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import { queryUnits, queryRoomsTree } from '@/api/fee/meterWaterManageApi'
import { getCommunityId } from '@/api/community/communityApi'

export default {
  name: 'RoomTreeDiv',
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'text'
      },
      communityId: ''
    }
  },
  created() {
    this.communityId = getCommunityId()
    this.loadTreeData()
  },
  methods: {
    async loadTreeData() {
      try {
        const units = await queryUnits({
          communityId: this.communityId
        })
        this.buildTreeData(units)
      } catch (error) {
        console.error('Failed to load tree data:', error)
      }
    },
    buildTreeData(units) {
      const treeMap = new Map()

      // Build floor nodes
      units.forEach(unit => {
        if (!treeMap.has(unit.floorId)) {
          treeMap.set(unit.floorId, {
            id: `f_${unit.floorId}`,
            floorId: unit.floorId,
            floorNum: unit.floorNum,
            icon: 'el-icon-office-building',
            text: `${unit.floorNum}栋`,
            children: []
          })
        }
      })

      // Build unit nodes
      units.forEach(unit => {
        const floorNode = treeMap.get(unit.floorId)
        if (floorNode) {
          floorNode.children.push({
            id: `u_${unit.unitId}`,
            unitId: unit.unitId,
            unitNum: unit.unitNum,
            icon: 'el-icon-connection',
            text: `${unit.unitNum}单元`,
            children: []
          })
        }
      })

      this.treeData = Array.from(treeMap.values())
    },
    async handleNodeClick(data) {
      if (data.id.startsWith('u_')) {
        await this.loadRooms(data)
      } else if (data.id.startsWith('r_')) {
        this.$emit('selectRoom', {
          roomId: data.roomId,
          roomName: data.roomName
        })
      }
    },
    async loadRooms(node) {
      try {
        const {rooms} = await queryRoomsTree({
          unitId: node.unitId,
          communityId: this.communityId,
          page: 1,
          row: 1000
        })

        const roomNodes = rooms.map(room => ({
          id: `r_${room.roomId}`,
          roomId: room.roomId,
          roomName: `${room.floorNum}-${room.unitNum}-${room.roomNum}`,
          icon: 'el-icon-house',
          text: room.ownerName
            ? `${room.roomNum}室(${room.ownerName})`
            : `${room.roomNum}室`
        }))

        // Update tree data
        const floorNode = this.treeData.find(
          item => item.id === `f_${node.floorId}`
        )
        if (floorNode) {
          const unitNode = floorNode.children.find(
            item => item.id === `u_${node.unitId}`
          )
          if (unitNode) {
            this.$set(unitNode, 'children', roomNodes)
            this.$refs.tree.updateKeyChildren(unitNode.id, roomNodes)

            // Auto select first room
            if (roomNodes.length > 0) {
              this.$emit('selectRoom', {
                roomId: roomNodes[0].roomId,
                roomName: roomNodes[0].roomName
              })
            }
          }
        }
      } catch (error) {
        console.error('Failed to load rooms:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.room-tree-container {
  height: 100%;
  overflow-y: auto;
  padding: 10px;

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    padding: 5px 0;
  }
}
</style>