<template>
  <div class="level-add">
    <h1 v-if="ruleForm.id">添加等级</h1>
    <div class="form-content">
      <!-- model 绑定数据 对应data中的变量 -->
      <!-- rules 表单验证规则 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="ruleForm.name"></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>
  </div>
</template>
<script>
// 引入axios
import axios from "axios";
export default {
  name: "LevelAdd",
  data() {
    return {
      ruleForm: {
        name: "",
        id:""
      },
      rules: {
        name: [{ required: true, message: "请输入等级名称", trigger: "blur" }],
      },
    };
  },
  //   组件创建完成后生命周函数
  created() {
    console.log(this.$route.query.id);
    console.log(this.$route.query.name);
    this.ruleForm.name = this.$route.query.name;
    this.ruleForm.id = this.$route.query.id;
  },
  methods: {
    // 定义一个函数添加等级
    addFun() {
      axios({
        method: "post",
        url: "http://39.105.160.25:18080/levelController/saveOrUpdateLevel",
        // data 传递给后端的参数
        data: {
          levelname: this.ruleForm.name,
        },
      })
        // 等级添加成功的回调函数
        .then((res) => {
          //  弹框提示成功
          this.$message({
            message: "恭喜你，这是一条成功消息",
            type: "success",
          });
          //   跳转页面
          this.$router.push("/level/list");
        })
        .catch((res) => {
          console.log(res);
        });
    },
    submitForm(formName) {
      // 对整个表单进行验证如果通过 valid会返回一个true 否则就是 false
      this.$refs[formName].validate((valid) => {
        //   this.$refs.ruleForm.validate((valid) => {
        // 表单验证成功
        if (valid) {
          this.addFun();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style scoped>
.form-content {
  width: 50%;
  margin: 100px auto;
}
</style>