<template>
  <el-card class="tree-card">
    <el-tree
      :data="treeData"
      :props="defaultProps"
      node-key="id"
      default-expand-all
      highlight-current
      @node-click="handleNodeClick"
      :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
      </span>
    </el-tree>
  </el-card>
</template>

<script>
import { queryUnits, queryRoomsTree } from '@/api/property/roomApi'
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 this.getUnits()
        this.treeData = this.buildTreeData(units)
      } catch (error) {
        console.error('加载树数据失败:', error)
      }
    },
    async getUnits() {
      const params = {
        communityId: this.communityId
      }
      const response = await queryUnits(params)
      return response.data
    },
    buildTreeData(units) {
      const floors = {}
      
      // 按楼层分组
      units.forEach(unit => {
        if (!floors[unit.floorId]) {
          floors[unit.floorId] = {
            id: `f_${unit.floorId}`,
            floorId: unit.floorId,
            floorNum: unit.floorNum,
            text: `${unit.floorNum}栋`,
            icon: 'el-icon-office-building',
            children: []
          }
        }
        
        floors[unit.floorId].children.push({
          id: `u_${unit.unitId}`,
          unitId: unit.unitId,
          text: `${unit.unitNum}单元`,
          icon: 'el-icon-collection',
          children: []
        })
      })
      
      return Object.values(floors)
    },
    async handleNodeClick(data) {
      if (data.id.startsWith('u_')) {
        await this.loadRooms(data.unitId, data)
      } else if (data.id.startsWith('r_')) {
        this.$emit('selectRoom', {
          roomId: data.roomId,
          roomName: data.text
        })
      }
    },
    async loadRooms(unitId, node) {
      try {
        if (node.children && node.children.length > 0) return
        
        const params = {
          unitId: unitId,
          communityId: this.communityId,
          page: 1,
          row: 1000
        }
        
        const response = await queryRoomsTree(params)
        const rooms = response.data.rooms || []
        
        rooms.forEach(room => {
          let label = room.roomNum
          if (room.ownerName) {
            label += `(${room.ownerName})`
          }
          
          node.children.push({
            id: `r_${room.roomId}`,
            roomId: room.roomId,
            text: label,
            icon: 'el-icon-house',
            roomName: `${room.floorNum}-${room.unitNum}-${room.roomNum}`
          })
        })
        
        // 默认选择第一个房间
        if (rooms.length > 0) {
          const firstRoom = rooms[0]
          this.$emit('selectRoom', {
            roomId: firstRoom.roomId,
            roomName: `${firstRoom.floorNum}-${firstRoom.unitNum}-${firstRoom.roomNum}`
          })
        }
      } catch (error) {
        console.error('加载房间数据失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  height: 100%;
  /deep/ .el-card__body {
    padding: 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>