<template>
  <div class="rental-list">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>租房管理</span>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公寓">
          <el-select v-model="searchForm.apartmentId" placeholder="请选择公寓" style="width: 100%">
            <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="请选择主状态" style="width: 100%">
            <el-option label="全部" value=""></el-option>
            <el-option label="空房" value="empty"></el-option>
            <el-option label="在租" value="rented"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附属状态">
          <el-select v-model="searchForm.subStatus" placeholder="请选择附属状态" style="width: 100%">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="normal"></el-option>
            <el-option label="即将到期" value="soon_expire"></el-option>
            <el-option label="已到期" value="expired"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="其他状态">
          <el-select v-model="searchForm.otherStatus" placeholder="请选择其他状态" style="width: 100%">
            <el-option label="全部" value=""></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>
      
      <!-- 房间卡片列表 -->
      <div class="room-cards" v-loading="isLoading">
        <div 
          v-for="room in rooms" 
          :key="room.id"
          @click="handleRoomClick(room.id)"
          class="room-card-wrapper"
        >
          <el-card 
            :class="['room-card', `status-${room.status === 'rented' ? room.subStatus : room.status}`]"
          >
            <div class="room-card-header">
              <h3>{{ getApartmentName(room.apartmentId) }}</h3>
              <div class="room-card-tags">
                <el-tag v-if="room.status === 'rented'" :type="getSubStatusType(room.subStatus)" size="small">{{ getSubStatusText(room.subStatus) }}</el-tag>
                <el-tag v-else size="small">空房</el-tag>
                <el-tag v-if="room.otherStatus" :type="getOtherStatusType(room.otherStatus)" size="small">{{ getOtherStatusText(room.otherStatus) }}</el-tag>
              </div>
            </div>
            <div class="room-card-body">
              <div class="room-info">
                <span class="room-number">{{ room.roomNumber }}</span>
                <span class="room-area">{{ room.area }}㎡</span>
                <div class="price-info">
                  <span class="room-price">¥{{ room.monthlyPrice }}/月</span>
                  <span v-if="room.yearlyPrice" class="room-price yearly">¥{{ room.yearlyPrice }}/年</span>
                </div>
              </div>
              <div class="rental-info" v-if="room.Rentals && room.Rentals.length > 0">
                <p><i class="el-icon-user"></i> {{ room.Rentals[0].tenantName }}</p>
                <p><i class="el-icon-date"></i> {{ room.Rentals[0].startDate }} 至 {{ room.Rentals[0].endDate }}</p>
              </div>
              <div class="rental-info" v-else>
                <p class="no-rental">暂无租客信息</p>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      
      <div class="pagination-wrapper">
        <el-pagination
          :layout="paginationLayout"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100, 99999]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

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

export default {
  name: 'RentalList',
  data() {
    return {
      rooms: [],
      apartments: [],
      total: 0,
      searchForm: {
        apartmentId: '',
        status: '',
        subStatus: '',
        otherStatus: '',
        roomNumber: ''
      },
      currentPage: 1,
      pageSize: 50,
      isLoading: false,
      isMobile: false
    }
  },
  computed: {
    paginationLayout() {
      return this.isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'
    }
  },
  mounted() {
    this.checkDevice()
    window.addEventListener('resize', this.checkDevice)
    this.initFromQuery()
    this.loadData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkDevice)
  },
  methods: {
    checkDevice() {
      this.isMobile = window.innerWidth <= 768
    },
    initFromQuery() {
      const query = this.$route.query
      if (query) {
        if (query.apartmentId) this.searchForm.apartmentId = parseInt(query.apartmentId)
        if (query.status) this.searchForm.status = query.status
        if (query.subStatus) this.searchForm.subStatus = query.subStatus
        if (query.otherStatus) this.searchForm.otherStatus = query.otherStatus
        if (query.roomNumber) this.searchForm.roomNumber = query.roomNumber
        if (query.page) this.currentPage = parseInt(query.page)
        if (query.pageSize) this.pageSize = parseInt(query.pageSize)
      }
    },
    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,
          subStatus: this.searchForm.subStatus,
          otherStatus: this.searchForm.otherStatus,
          roomNumber: this.searchForm.roomNumber,
          page: this.currentPage,
          pageSize: this.pageSize
        }
        
        const roomsResponse = await roomApi.getAll(params)
        if (roomsResponse.data) {
          this.rooms = roomsResponse.data
          this.total = roomsResponse.total
        } else {
          this.rooms = roomsResponse
          this.total = roomsResponse.length
        }
      } catch (error) {
        this.$message.error('加载数据失败')
      } finally {
        this.isLoading = false
      }
    },
    getApartmentName(apartmentId) {
      const apartment = this.apartments.find(a => a.id == apartmentId)
      return apartment ? apartment.name : ''
    },
    getSubStatusType(status) {
      switch (status) {
        case 'normal': return 'success'
        case 'soon_expire': return 'warning'
        case 'expired': return 'danger'
        default: return ''
      }
    },
    getSubStatusText(status) {
      switch (status) {
        case 'normal': return '正常'
        case 'soon_expire': return '即将到期'
        case 'expired': return '已到期'
        default: return status
      }
    },
    getOtherStatusType(status) {
      switch (status) {
        case 'cleaning': return 'warning'
        case 'maintenance': return 'danger'
        default: return ''
      }
    },
    getOtherStatusText(status) {
      switch (status) {
        case 'cleaning': return '打扫中'
        case 'maintenance': return '维修中'
        default: return status
      }
    },
    handleRoomClick(roomId) {
      try {
        this.$router.push({
          path: `/rental/detail/${roomId}`,
          query: {
            ...this.searchForm,
            page: this.currentPage,
            pageSize: this.pageSize
          }
        })
      } catch (error) {
        console.error('Navigation error:', error)
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    resetSearch() {
      this.searchForm = {
        apartmentId: '',
        status: '',
        subStatus: '',
        otherStatus: '',
        roomNumber: ''
      }
      this.currentPage = 1
      this.loadData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.$router.push({
        path: this.$route.path,
        query: {
          ...this.searchForm,
          page: this.currentPage,
          pageSize: this.pageSize
        }
      })
      this.loadData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.$router.push({
        path: this.$route.path,
        query: {
          ...this.searchForm,
          page: this.currentPage,
          pageSize: this.pageSize
        }
      })
      this.loadData()
    }
  }
}
</script>

<style scoped>
.rental-list {
  padding: 0;
}

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

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

.room-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.room-card-wrapper {
  cursor: pointer;
}

.room-card {
  transition: all 0.3s ease;
  border: 2px solid #e4e7ed;
  height: 100%;
}

.room-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.room-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 8px;
}

.room-card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.room-card-tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.room-card-body {
  display: flex;
  flex-direction: column;
}

.room-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  flex-wrap: wrap;
  gap: 8px;
}

.room-number {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.room-area {
  color: #606266;
  font-size: 14px;
}

.price-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.room-price {
  color: #f56c6c;
  font-weight: 500;
  font-size: 14px;
}

.room-price.yearly {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.rental-info {
  margin-top: 10px;
}

.rental-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.rental-info p.no-rental {
  color: #909399;
  font-style: italic;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 状态样式 */
.status-empty {
  border-color: #dcdfe6;
  background-color: #f5f7fa;
}

.status-normal {
  border-color: #67c23a;
  background-color: #f0f9eb;
}

.status-soon_expire {
  border-color: #e6a23c;
  background-color: #fdf6ec;
}

.status-expired {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .search-form {
    margin-bottom: 15px;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .search-form .el-form-item__content {
    width: 100%;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 100%;
  }
  
  .room-cards {
    grid-template-columns: 1fr;
    gap: 10px;
    margin-top: 15px;
  }
  
  .room-card {
    padding: 12px;
  }
  
  .room-card:hover {
    transform: none;
  }
  
  .room-card-header h3 {
    font-size: 14px;
  }
  
  .room-number {
    font-size: 16px;
  }
  
  .room-info {
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
  
  .pagination-wrapper {
    justify-content: center;
  }
  
  .card-header span {
    font-size: 16px;
  }
}

@media screen and (max-width: 375px) {
  .room-cards {
    gap: 8px;
  }
  
  .room-card {
    padding: 10px;
  }
  
  .room-number {
    font-size: 14px;
  }
  
  .room-price {
    font-size: 13px;
  }
}
</style>
