<template>
  <div class="apartment-add">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>添加公寓</span>
        </div>
      </template>
      <el-form :model="apartmentForm" :rules="rules" ref="apartmentForm" label-width="100px">
        <el-form-item label="区域" prop="regionId">
          <el-select v-model="apartmentForm.regionId" placeholder="请选择区域">
            <el-option v-for="region in regions" :key="region.id" :label="region.name" :value="region.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公寓名称" prop="name">
          <el-input v-model="apartmentForm.name" placeholder="请输入公寓名称"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="apartmentForm.address" placeholder="请输入地址"></el-input>
        </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 { apartmentApi, regionApi } from '../../api/api'

export default {
  name: 'ApartmentAdd',
  data() {
    return {
      apartmentForm: {
        regionId: '',
        name: '',
        address: ''
      },
      regions: [],
      rules: {
        regionId: [
          { required: true, message: '请选择区域', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入公寓名称', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadRegions()
  },
  methods: {
    async loadRegions() {
      try {
        const response = await regionApi.list()
        this.regions = response
      } catch (error) {
        this.$message.error('加载区域数据失败')
      }
    },
    async submitForm() {
      this.$refs.apartmentForm.validate(async (valid) => {
        if (valid) {
          try {
            await apartmentApi.create(this.apartmentForm)
            this.$message.success('添加成功')
            this.$router.push('/apartment/list')
          } catch (error) {
            this.$message.error('添加失败')
          }
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.apartmentForm.resetFields()
    },
    goBack() {
      this.$router.push('/apartment/list')
    }
  }
}
</script>

<style scoped>
.apartment-add {
  padding: 20px 0;
}

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