<template>
  <div class="room-edit">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>编辑房间</span>
        </div>
      </template>
      <el-form :model="roomForm" :rules="rules" ref="roomForm" label-width="100px">
        <el-form-item label="公寓" prop="apartmentId">
          <el-select v-model="roomForm.apartmentId" placeholder="请选择公寓">
            <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="房间号" prop="roomNumber">
          <el-input v-model="roomForm.roomNumber" placeholder="请输入房间号"></el-input>
        </el-form-item>
        <el-form-item label="面积(㎡)" prop="area">
          <el-input type="number" v-model="roomForm.area" placeholder="请输入面积"></el-input>
        </el-form-item>
        <el-form-item label="月租金(元)" prop="monthlyPrice">
          <el-input type="number" v-model="roomForm.monthlyPrice" placeholder="请输入月租金"></el-input>
        </el-form-item>
        <el-form-item label="年租金(元)" prop="yearlyPrice">
          <el-input type="number" v-model="roomForm.yearlyPrice" placeholder="请输入年租金"></el-input>
        </el-form-item>
        <el-form-item label="主状态" prop="status">
          <el-select v-model="roomForm.status" placeholder="请选择主状态">
            <el-option label="空房" value="empty"></el-option>
            <el-option label="在租" value="rented"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="附属状态" prop="subStatus" v-if="roomForm.status === 'rented'">
          <el-select v-model="roomForm.subStatus" placeholder="请选择附属状态">
            <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="其他状态" prop="otherStatus">
          <el-select v-model="roomForm.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>
          <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 { roomApi, apartmentApi } from '../../api/api'

export default {
  name: 'RoomEdit',
  data() {
    return {
      roomForm: {
        id: '',
        apartmentId: '',
        roomNumber: '',
        area: '',
        monthlyPrice: '',
        yearlyPrice: '',
        status: '',
        otherStatus: '',
        subStatus: 'normal'
      },
      // 保存返回时的查询参数
      returnQuery: {},
      apartments: [],
      rules: {
        apartmentId: [
          { required: true, message: '请选择公寓', trigger: 'blur' }
        ],
        roomNumber: [
          { required: true, message: '请输入房间号', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        area: [
          { validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                callback()
              } else if (isNaN(Number(value))) {
                callback(new Error('请输入数字'))
              } else {
                callback()
              }
            }, trigger: 'blur' }
        ],
        monthlyPrice: [
          { validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                callback()
              } else if (isNaN(Number(value))) {
                callback(new Error('请输入数字'))
              } else {
                callback()
              }
            }, trigger: 'blur' }
        ],
        yearlyPrice: [
          { validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                callback()
              } else if (isNaN(Number(value))) {
                callback(new Error('请输入数字'))
              } else {
                callback()
              }
            }, trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 获取返回时的查询参数
    this.returnQuery = this.$route.query
    this.loadApartments()
    this.loadRoomData()
  },
  methods: {
    async loadApartments() {
      try {
        const response = await apartmentApi.getAll()
        this.apartments = response.data || response
      } catch (error) {
        this.$message.error('加载公寓数据失败')
      }
    },
    async loadRoomData() {
      try {
        const id = this.$route.params.id
        const room = await roomApi.getById(id)
        if (room) {
          this.roomForm = room
        }
      } catch (error) {
        this.$message.error('加载房间数据失败')
      }
    },
    async submitForm() {
      this.$refs.roomForm.validate(async (valid) => {
        if (valid) {
          try {
            await roomApi.update(this.roomForm.id, this.roomForm)
            this.$message.success('编辑成功')
            this.$router.push({
              path: '/room/list',
              query: this.returnQuery
            })
          } catch (error) {
            this.$message.error('编辑失败')
          }
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.loadRoomData()
    },
    goBack() {
      this.$router.push({
        path: '/room/list',
        query: this.returnQuery
      })
    }
  }
}
</script>

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

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