<template>
  <MegaDrawer
    :visible.sync="myVisible"
    :title="title"
    :mask-closable="false"
    closable
    destroy-on-close
    width="520"
    @close="close()"
  >
    <div slot="main">
      <slot name="iDialogForm">
        <i-form
          ref="iDialogForm"
          :label-width="labelWidth"
          :form-disable="viewFormDisable"
          :form-item="formItem"
          :search-form="searchForm"
          :span="span"
        />
      </slot>
    </div>
    <template slot="footer">
      <div v-show="showFooter" class="drawer-footer">
        <a-button :loading="btnLoading" type="primary" @click="confirm">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="close">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </div>
    </template>
  </MegaDrawer>
</template>

<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";

export default {
  name: "IDialogForm",
  components: {
    MegaDrawer,
    Icon,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    viewFormDisable: {
      type: Boolean,
      default: false,
    },
    drawerWidth: {
      type: String,
      default: "520px",
    },
    labelWidth: {
      type: Number,
      default: 100,
    },
    span: {
      type: Number,
      default: 1,
    },
    operation: {
      type: String,
      default: "add",
    },
    title: {
      type: String,
      default: "",
    },
    formItem: {
      type: Object,
      default: () => ({
        factoryId: {
          label: "",
          handle: () => {},
          isRequired: false,
          isShow: true,
          options: [],
          optionsProps: {
            label: "name",
            value: "id",
          },
        },
      }),
    },
    searchForm: {
      type: Object,
      default: () => {},
    },
    showFooter: {
      type: Boolean,
      default: true,
    },
    btnLoading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      myRules: {},
      myVisible: false,
    };
  },
  watch: {
    visible(newVal, oldVal) {
      this.myVisible = newVal;
    },
  },
  methods: {
    close() {
      if (this.$refs.iDialogForm) {
        this.$refs.iDialogForm.$refs.iForm.resetFields();
      }
      this.$emit("close", false);
    },
    confirm() {
      if (this.$refs.iDialogForm) {
        // eslint-disable-next-line
        this.$refs.iDialogForm.$refs.iForm.validate((valid) => {
          if (valid) {
            this.$emit("save", this.$refs.iDialogForm.$refs.iForm.model);
          } else {
            this.$message.error(this.$t("REQUIRED_INFO"));
            return false;
          }
        });
      } else {
        this.$emit("save");
      }
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .i-form .form-row {
  padding: 0 !important;
}
</style>
