<template>
  <div class="x-drawer">
    <el-drawer
      :append-to-body="appendToBody"
      :destroy-on-close="destroyOnClose"
      :close-on-press-escape="closeOnPressEscape"
      :custom-class="wrapperClass + ' x-drawer-wrapper'"
      :show-close="false"
      :visible="drawerVisible"
      v-bind="$attrs"
      :size="activeAxis"
      @update:visible="updateDrawerVisible"
      v-on="$listeners"
    >
      <template v-slot:title class="x-drawer-header">
        <div v-if="!$scopedSlots.title" class="drawer-header-row">
          <label class="header-title">{{ title }}</label>
          <template>
            <div class="block"></div>
          </template>
          <x-svg-icon
            class="header-close-icon"
            name="close-icon"
            @click.native="closeBtnClick"
          ></x-svg-icon>
        </div>
        <slot v-else name="title"></slot>
      </template>
      <div class="x-drawer-body">
        <slot></slot>
      </div>
      <div v-if="$scopedSlots.footer" class="x-drawer-footer">
        <slot name="footer"></slot>
      </div>
    </el-drawer>
  </div>
</template>
<script>
export default {
  name: 'XDrawer',
  props: {
    width: {
      required: true,
      type: String
    },
    drawerVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    closeConfig: {
      type: Object,
      default: function() {
        return {}
      }
    },
    appendToBody: {
      type: Boolean,
      default: true
    },
    destroyOnClose: {
      type: Boolean,
      default: true
    },
    wrapperClass: {
      type: String,
      default: ''
    },
    headerType: {
      type: String
    },
    closeOnPressEscape: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      okButtonLoading: false,
      cancelButtonLoading: false,
      searchStr: ''
    }
  },
  computed: {
    activeAxis() {
      if (!isNaN(this.width) && this.width.indexOf('%') === -1) {
        return this.width + 'px'
      }
      return this.width
    }
  },
  mounted() {
    // console.log(this.$scopedSlots, '$scopedSlots')
  },
  methods: {
    updateDrawerVisible($event) {
      this.$emit('update:drawerVisible', $event)
    },
    closeBtnClick($event) {
      if (!this.closeConfig || !this.closeConfig.onClose) {
        this.updateDrawerVisible(false)
      } else {
        const result = this.closeConfig.onClose($event)
        // 返回true，阻止关闭
        if (!(result instanceof Promise) && result !== true) {
          this.updateDrawerVisible(false)
        } else if (result instanceof Promise) {
          // 点击关闭的阻断，只能用在弹出新的弹窗，一般不建议
          // console.warn('点击关闭的阻断，只能用在弹出新的弹窗，一般不建议')
          result
            .then((res) => {
              if (res !== true) {
                this.updateDrawerVisible(false)
              }
            })
            .finally((res) => {})
        }
      }
    }
  }
}
</script>
