<template>
  <el-dialog class="dialog"
             :visible.sync="dialogVisible"
             center
             :title="data?'编辑':'添加'"
             append-to-body
             :before-close="onBeforeClose"
             @close="onClose"
             width="600px">
    <el-form label-width="120px" ref="dataForm" :model="dataForm" :rules="dataRules">
      <el-form-item label="分类目录名称" prop="typeName">
        <el-input v-model="dataForm.typeName"></el-input>
      </el-form-item>

    </el-form>

    <div slot="footer">
      <el-button type="primary" @click="onConfirm">确 认</el-button>
      <el-button @click="onCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import {validateNotEmpty} from "@/utils/validate";

export default {
  name: "inspectionClassifyDialogEdit",
  components: {},
  props: {
    visible: {
      type: Boolean
    },
    data: {
      type: Object
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  data() {
    return {
      dataForm: {
        typeName: undefined, // 分类目录名称
      },

      dataRules: {
        typeName: [{validator: validateNotEmpty, errorMessage: "分类目录名称不能为空", required: true, trigger: 'blur'}]
      }
    }
  },

  mounted() {
    if (this.data) {
      this.dataForm = {...this.data};
    }
  },

  methods: {
    // 取消
    onCancel() {
      this.dialogVisible = false;
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.data) { // 更新
            this.$axios.put("/v1/check/item/type/update", this.dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$emit("update");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post("/v1/check/item/type/add", this.dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$emit("add");
              this.onCancel();
            });
          }
        }
      });
    },

    // 关闭前确认
    onBeforeClose(done) {
      if (this.$store.state.app.closeConfirmEnable) {
        this.$confirm("确认关闭？").then(() => done());
      } else {
        done();
      }
    },

    // 关闭
    onClose() {
      this.$emit("close");
    }
  }
}
</script>

<style scoped lang="scss">

</style>
