<template>
  <div class="room-list">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>房间列表</span>
          <el-button type="primary" @click="handleAdd">添加房间</el-button>
        </div>
      </template>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公寓">
          <el-select v-model="searchForm.apartmentId" placeholder="请选择公寓">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="apartment in apartments" :key="apartment.id" :label="apartment.name" :value="apartment.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="空房" value="empty"></el-option>
            <el-option label="在租" value="rented"></el-option>
            <el-option label="即将到期" value="soon_expire"></el-option>
            <el-option label="已到期" value="expired"></el-option>
            <el-option label="打扫中" value="cleaning"></el-option>
            <el-option label="维修中" value="maintenance"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号">
          <el-input v-model="searchForm.roomNumber" placeholder="请输入房间号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table 
        :data="rooms" 
        style="width: 100%"
      >
        <el-table-column prop="apartmentName" label="公寓" width="150"></el-table-column>
        <el-table-column prop="roomNumber" label="房间号" width="100"></el-table-column>
        <el-table-column prop="area" label="面积(㎡)" width="100"></el-table-column>
        <el-table-column prop="price" label="租金(元/月)" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" style="margin-top: 20px;">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { roomApi, apartmentApi } from '../../api/api'

export default {
  name: 'RoomList',
  data() {
    return {
      apartments: [],
      rooms: [],
      total: 0,
      searchForm: {
        apartmentId: '',
        status: '',
        roomNumber: ''
      },
      currentPage: 1,
      pageSize: 10,
      isLoading: false
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      if (this.isLoading) return
      
      this.isLoading = true
      try {
        // 加载公寓数据
        const apartmentsResponse = await apartmentApi.getAll()
        this.apartments = apartmentsResponse.data || apartmentsResponse
        
        // 构建查询参数
        const params = {
          apartmentId: this.searchForm.apartmentId,
          status: this.searchForm.status,
          roomNumber: this.searchForm.roomNumber,
          page: this.currentPage,
          pageSize: this.pageSize
        }
        
        // 加载房间数据
        const roomsResponse = await roomApi.getAll(params)
        if (roomsResponse.data) {
          this.rooms = roomsResponse.data.map(room => {
            // 为房间添加公寓名称
            const apartment = this.apartments.find(a => a.id == room.apartmentId)
            return {
              ...room,
              apartmentName: apartment ? apartment.name : ''
            }
          })
          this.total = roomsResponse.total
        } else {
          // 兼容旧的返回格式
          this.rooms = roomsResponse.map(room => {
            const apartment = this.apartments.find(a => a.id == room.apartmentId)
            return {
              ...room,
              apartmentName: apartment ? apartment.name : ''
            }
          })
          this.total = roomsResponse.length
        }
      } catch (error) {
        this.$message.error('加载数据失败')
      } finally {
        this.isLoading = false
      }
    },
    getStatusType(status) {
      switch (status) {
        case 'empty': return ''
        case 'rented': return 'success'
        case 'soon_expire': return 'warning'
        case 'expired': return 'danger'
        case 'cleaning': return 'info'
        case 'maintenance': return 'danger'
        default: return ''
      }
    },
    getStatusText(status) {
      switch (status) {
        case 'empty': return '空房'
        case 'rented': return '在租'
        case 'soon_expire': return '即将到期'
        case 'expired': return '到期'
        case 'cleaning': return '打扫中'
        case 'maintenance': return '维修中'
        default: return status
      }
    },
    handleAdd() {
      this.$router.push('/room/add')
    },
    handleEdit(id) {
      this.$router.push(`/room/edit/${id}`)
    },
    async handleDelete(id) {
      this.$confirm('确定要删除这个房间吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await roomApi.delete(id)
          this.$message.success('删除成功')
          this.loadData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    resetSearch() {
      this.searchForm = {
        apartmentId: '',
        status: '',
        roomNumber: ''
      }
      this.currentPage = 1
      this.loadData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    }
  }
}
</script>

<style scoped>
.room-list {
  padding: 20px 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>