<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)
        this.$message.error(this.$t('roomTree.loadError'))
      }
    },
    buildTreeData(units) {
      const floorMap = {}

      // Build floor nodes and unit nodes
      units.forEach(unit => {
        if (!floorMap[unit.floorId]) {
          floorMap[unit.floorId] = {
            id: `f_${unit.floorId}`,
            floorId: unit.floorId,
            floorNum: unit.floorNum,
            icon: "/img/floor.png",
            text: `${unit.floorNum}${this.$t('room.floorUnitTree.building')}`,
            children: []
          }
        }

        floorMap[unit.floorId].children.push({
          id: `u_${unit.unitId}`,
          unitId: unit.unitId,
          unitNum: unit.unitNum,
          floorId: unit.floorId, // Add floorId reference
          icon: "/img/unit.png",
          text: `${unit.unitNum}${this.$t('room.floorUnitTree.unit')}`,
          children: []
        })
      })

      this.treeData = Object.values(floorMap)
      this.$nextTick(() => {
        this.expandAndSelectFirstRoom()
      })
    },
    async expandAndSelectFirstRoom() {
      if (!this.treeData.length) return
      const firstFloor = this.treeData[0]
      if (!firstFloor.children || !firstFloor.children.length) return
      const firstUnit = firstFloor.children[0]
      const treeRef = this.$refs.tree
      if (treeRef && treeRef.store) {
        treeRef.store.nodesMap[firstFloor.id] && (treeRef.store.nodesMap[firstFloor.id].expanded = true)
        treeRef.store.nodesMap[firstUnit.id] && (treeRef.store.nodesMap[firstUnit.id].expanded = true)
      }
      await this.loadRooms(firstUnit, { data: firstUnit })
    },
    async handleNodeClick(data, node) {
      if (data.id.startsWith('u_')) {
        if (!node.expanded) {
          await this.loadRooms(data, node)
          node.expanded = true
        }
      } else if (data.id.startsWith('r_')) {
        this.$emit('selectRoom', {
          roomId: data.roomId,
          roomName: data.roomName
        })
      }
    },
    async loadRooms(unitData, node) {
      try {
        const { rooms } = await queryRoomsTree({
          unitId: unitData.unitId,
          communityId: this.communityId,
          page: 1,
          row: 1000
        })

        if (rooms && rooms.length > 0) {
          const roomNodes = rooms.map(room => ({
            id: `r_${room.roomId}`,
            roomId: room.roomId,
            roomName: `${room.floorNum}-${room.unitNum}-${room.roomNum}`,
            icon: "/img/room.png",
            text: room.ownerName
              ? `${room.roomNum}${room.ownerName})`
              : `${room.roomNum}`
          }))

          // Update the node's children
          this.$set(node.data, 'children', roomNodes)
          this.$emit('selectRoom', {
            roomId: roomNodes[0].roomId,
            roomName: roomNodes[0].roomName
          })
        }
      } catch (error) {
        console.error('Failed to load rooms:', error)
        this.$message.error(this.$t('roomTree.loadRoomError'))
      }
    }
  }
}
</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>