<template>
  <el-button :type="type" @click="preSubmitData"><slot></slot></el-button>
</template>

<script>
  export default {
    name: "ht-save-button",
    props: {
      isSubmit: {
        type: Boolean,
        default: true,
      },
      type: {
        type: String,
        default: "primary",
      },
      scopeName: {
        type: String,
        required: true,
      },
      isShowErrorDetail: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {};
    },
    mounted() {
      this.$validator = this.$root.$validator;
    },
    methods: {
      preSubmitData() {
        this.$validator.validateAll(this.scopeName).then((result) => {
          if (result) {
            this.submitData();
          } else {
            let arr = this.$validator.errors.items.filter(
              (item) => item.scope == this.scopeName
            );
            if (this.isShowErrorDetail) {
              const errorMsg = arr.map((err) => {
                return `${err.field}: ${err.msg}`;
              });
              this.$notify({
                title: "错误提示:",
                dangerouslyUseHTMLString: true,
                message: `请正确填写以下内容：<br/>${errorMsg.join("<br/>")}`,
                type: "error",
              });
            } else {
              let errorLength = arr.length;
              this.$message({
                showClose: true,
                message: `有${errorLength}个字段未通过校验，请正确填写表单内容。`,
                type: "warning",
              });
            }
          }
        });
      },
      async submitData() {
        // 表单数据 model  是否提交  true 提交 false 不提交
        await this.$emit("before-save-data");

        if (this.isSubmit) {
          this.$emit("request-save-data");
        }
      },
    },
  };
</script>
