<template>
  <div class="add-location">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="地址名称" prop="address">
        <el-input v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="ruleForm.longitude"></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="ruleForm.latitude"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addLocation } from "@/api/location";
export default {
  data() {
    return {
      ruleForm: {
        address: "",
        longitude: "",
        latitude: "",
      },
      rules: {
        address: [
          { required: true, message: "请输入地址名称", trigger: "blur" },
        ],
        longitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
        latitude: [{ required: true, message: "请输入纬度", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addLocation({
            address: this.ruleForm.address,
            longitude: this.ruleForm.longitude,
            latitude: this.ruleForm.latitude,
          })
            .then((res) => {
              this.$message({
                message: "恭喜你，添加地址信息成功",
                type: "success",
              });
              this.$refs[formName].resetFields();
              this.$router.push('/location/locationList')
            })
            .catch((err) => {
              this.$message.error('错了哦，添加地址信息失败');
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.add-location {
  width: 70%;
  margin: 120px auto;
}
</style>