<template>
  <el-dialog
    class="modify-field"
    :visible.sync="modalIsShow"
    title="新增扩展字段"
    top="10vh"
    width="448px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-position="top"
    >
      <el-form-item prop="name" label="字段名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="请输入字段名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="code" label="字段变量名：">
        <el-input
          v-model.trim="modalForm.code"
          placeholder="请输入字段变量名"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="submit">确认</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
const initModalForm = {
  name: "",
  code: "",
  enable: false
};

export default {
  name: "modify-field",
  data() {
    return {
      modalIsShow: false,
      modalForm: {},
      rules: {
        name: [
          {
            required: true,
            message: "请输入字段名称",
            trigger: "change"
          },
          {
            max: 20,
            message: "字段名称不能超过20",
            trigger: "change"
          }
        ],
        code: [
          {
            required: true,
            pattern: /^[a-zA-Z]{3,30}$/,
            message: "字段变量名只能由字母组成，长度在3-30之间",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...initModalForm };
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      this.$emit("confirm", this.modalForm);
      this.cancel();
    }
  }
};
</script>
