<template>
  <div class="rental-edit">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>编辑租房</span>
        </div>
      </template>
      <el-form :model="rentalForm" :rules="rules" ref="rentalForm" label-width="120px">
        <el-form-item label="房间" prop="roomId">
          <el-select v-model="rentalForm.roomId" placeholder="请选择房间" style="width: 100%">
            <el-option
              v-for="room in rooms"
              :key="room.id"
              :label="`${getApartmentName(room.apartmentId)} - ${room.roomNumber}`"
              :value="room.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider>租客信息</el-divider>
        <el-form-item label="租客姓名" prop="tenantName">
          <el-input v-model="rentalForm.tenantName" placeholder="请输入租客姓名"></el-input>
        </el-form-item>
        <el-form-item label="租客电话" prop="tenantPhone">
          <el-input v-model="rentalForm.tenantPhone" placeholder="请输入租客电话"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="tenantIdCard">
          <el-input v-model="rentalForm.tenantIdCard" placeholder="请输入身份证号"></el-input>
        </el-form-item>
        <el-divider>合同信息</el-divider>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="rentalForm.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="rentalForm.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="租金(元/月)" prop="rent">
          <el-input v-model.number="rentalForm.rent" placeholder="请输入租金"></el-input>
        </el-form-item>
        <el-form-item label="押金(元)" prop="deposit">
          <el-input v-model.number="rentalForm.deposit" placeholder="请输入押金"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="rentalForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="有效" value="active"></el-option>
            <el-option label="到期" value="expired"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

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

export default {
  name: 'RentalEdit',
  data() {
    return {
      rentalForm: {
        id: '',
        roomId: '',
        tenantName: '',
        tenantPhone: '',
        tenantIdCard: '',
        startDate: '',
        endDate: '',
        rent: '',
        deposit: '',
        status: ''
      },
      rules: {
        roomId: [{ required: true, message: '请选择房间', trigger: 'blur' }],
        tenantName: [{ required: true, message: '请输入租客姓名', trigger: 'blur' }],
        tenantPhone: [{ required: true, message: '请输入租客电话', trigger: 'blur' }],
        tenantIdCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        startDate: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        endDate: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        rent: [{ required: true, message: '请输入租金', trigger: 'blur' }],
        deposit: [{ required: true, message: '请输入押金', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
      },
      rooms: [],
      apartments: []
    }
  },
  mounted() {
    this.loadData()
    this.loadRentalData()
  },
  methods: {
    async loadData() {
      try {
        // 并行加载房间和公寓数据
        const [roomsResponse, apartmentsResponse] = await Promise.all([
          roomApi.getAll(),
          apartmentApi.getAll()
        ])
        
        this.rooms = roomsResponse
        this.apartments = apartmentsResponse
      } catch (error) {
        this.$message.error('加载数据失败')
      }
    },
    async loadRentalData() {
      try {
        const id = this.$route.params.id
        const rental = await rentalApi.getById(id)
        if (rental) {
          this.rentalForm = {
            ...rental,
            startDate: new Date(rental.startDate),
            endDate: new Date(rental.endDate)
          }
        }
      } catch (error) {
        this.$message.error('加载租房数据失败')
      }
    },
    getApartmentName(apartmentId) {
      const apartment = this.apartments.find(a => a.id == apartmentId)
      return apartment ? apartment.name : ''
    },
    async submitForm() {
      this.$refs.rentalForm.validate(async (valid) => {
        if (valid) {
          try {
            await rentalApi.update(this.rentalForm.id, this.rentalForm)
            this.$message.success('编辑成功')
            this.$router.push('/rental/list')
          } catch (error) {
            this.$message.error('编辑失败')
          }
        } else {
          this.$message.error('请填写所有必填项')
          return false
        }
      })
    },
    resetForm() {
      this.loadRentalData()
    },
    goBack() {
      this.$router.push('/rental/list')
    }
  }
}
</script>

<style scoped>
.rental-edit {
  padding: 20px 0;
}

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