<template>
  <div class="region-edit">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>编辑区域</span>
        </div>
      </template>
      <el-form :model="regionForm" :rules="rules" ref="regionForm" label-width="100px">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="regionForm.name" placeholder="请输入区域名称"></el-input>
        </el-form-item>
        <el-form-item label="区域描述" prop="description">
          <el-input type="textarea" v-model="regionForm.description" 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 { regionApi } from '../../api/api'

export default {
  name: 'RegionEdit',
  data() {
    return {
      regionForm: {
        id: '',
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入区域描述', trigger: 'blur' },
          { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadRegionData()
  },
  methods: {
    async loadRegionData() {
      try {
        const id = this.$route.params.id
        const region = await regionApi.getById(id)
        if (region) {
          this.regionForm = region
        }
      } catch (error) {
        this.$message.error('加载区域数据失败')
      }
    },
    async submitForm() {
      this.$refs.regionForm.validate(async (valid) => {
        if (valid) {
          try {
            await regionApi.update(this.regionForm.id, this.regionForm)
            this.$message.success('编辑成功')
            this.$router.push('/region/list')
          } catch (error) {
            this.$message.error('编辑失败')
          }
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.loadRegionData()
    },
    goBack() {
      this.$router.push('/region/list')
    }
  }
}
</script>

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

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