<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="请选择公寓">
            <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-select>
        </el-form-item>
        <el-form-item label="附属状态">
          <el-select v-model="searchForm.subStatus" placeholder="请选择附属状态">
            <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="请选择其他状态">
            <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">
        <div 
          v-for="room in rooms" 
          :key="room.id"
          @click="handleRoomClick(room.id)"
          style="cursor: pointer;"
        >
          <el-card 
            :class="['room-card', `status-${room.status === 'rented' ? room.subStatus : room.status}`]"
          >
          <div class="room-card-header">
            <h3>{{ getApartmentName(room.apartmentId) }}</h3>
            <div style="display: flex; gap: 8px;">
              <el-tag v-if="room.status === 'rented'" :type="getSubStatusType(room.subStatus)">{{ getSubStatusText(room.subStatus) }}</el-tag>
              <el-tag v-else>空房</el-tag>
              <el-tag v-if="room.otherStatus" :type="getOtherStatusType(room.otherStatus)">{{ 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>租客: {{ room.Rentals[0].Tenant.name }}</p>
              <p>租期: {{ room.Rentals[0].startDate }} 至 {{ room.Rentals[0].endDate }}</p>
            </div>
            <div class="rental-info" v-else>
              <p>暂无租客信息</p>
            </div>
          </div>
          </el-card>
        </div>
      </div>
      <div class="pagination" style="margin-top: 20px;">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :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
    }
  },
  mounted() {
    // 从路由参数中获取查询参数和页码
    this.initFromQuery()
    this.loadData()
  },
  methods: {
    // 从路由参数初始化搜索参数和页码
    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 'info'
        case 'maintenance': return 'danger'
        default: return ''
      }
    },
    getOtherStatusText(status) {
      switch (status) {
        case 'cleaning': return '打扫中'
        case 'maintenance': return '维修中'
        default: return status
      }
    },

    handleAdd() {
      this.$router.push('/rental/add')
    },
    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: 20px 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 {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid #e4e7ed;
  position: relative;
  z-index: 1;
  height: 220px;
  display: flex;
  flex-direction: column;
}

.room-card * {
  pointer-events: none;
}

.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: center;
  margin-bottom: 15px;
}

.room-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.room-card-body {
  flex: 1;
  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-shrink: 0;
}

.room-number {
  font-size: 24px;
  font-weight: bold;
}

.room-area {
  color: #606266;
}

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

.room-price {
  color: #409EFF;
  font-weight: 500;
}

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

.rental-info {
  margin-top: 10px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.rental-info p {
  margin: 5px 0;
  color: #606266;
}

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

.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;
}
</style>