<template>
  <qf-container class="qf-dialog-def">
    <qf-header class="qf-dialog-header">
      <span class="qf-dialog-icon" v-if="$slots.icon">
        <slot name="icon"></slot>
      </span>
      <span class="qf-dialog-title">{{title}}<slot name="title"></slot></span>
      <qf-font-icon name="ic-ic_close" class="qf-dialog-close" @click="onCancel" v-if="closable"></qf-font-icon>
    </qf-header>
    <qf-main class="qf-dialog-body">
      <slot></slot>
    </qf-main>
    <slot name="footer">
      <qf-footer class="qf-dialog-footer">
        <div class="qf-dialog-footer-left">
          <slot name="footer-left"></slot>
        </div>
        <qf-button size="large" @click="onConfirm" v-show="showConfirm" type="primary" ref="confirm">
          {{confirmText || t('qf.dialog.confirm')}}
        </qf-button>
        <qf-button size="large" @click="onCancel" v-show="showCancel" ref="cancel">{{cancelText ||
          t('qf.dialog.cancel')}}
        </qf-button>
      </qf-footer>
    </slot>
  </qf-container>
</template>

<script>
import QfButton from '../button';
import QfFontIcon from '../font-icon';
import QfContainer from '../container';
import QfHeader from '../header';
import QfMain from '../main';
import QfFooter from '../footer';
import KeydownMgr from '../util/KeydownMgr';
import LocaleMixin from '../locale/mixin';

export default {
  name: 'QfDialogDef',
  mixins: [LocaleMixin],
  components: {
    QfFooter,
    QfMain,
    QfHeader,
    QfContainer,
    QfButton,
    QfFontIcon
  },
  props: {
    title: '',
    cancelText: '',
    confirmText: '',
    closable: {
      type: Boolean,
      default: true
    },
    showCancel: {
      default: true
    },
    showConfirm: {
      default: true
    },
    focus: {
      type: String,
      default: 'confirm'
    }
  },

  data() {
    return {};
  },

  created() {
    KeydownMgr.bind(this, this.onKeydown);
  },

  beforeDestroy() {
    KeydownMgr.unbind(this, this.onKeydown);
  },

  mounted() {
    if (this.focus === 'confirm') {
      this.$nextTick(() => {
        this.doFocusConfirm();
      });
    } else if (this.focus === 'cancel') {
      this.$nextTick(() => {
        this.doFocusCancel();
      });
    }
  },

  methods: {
    onCancel() {
      this.$emit('cancel');
    },

    onConfirm() {
      this.$emit('confirm');
    },

    doFocusConfirm() {
      if (this.showConfirm && this.$refs.confirm) {
        this.$refs.confirm.focus();
      }
    },

    doFocusCancel() {
      if (this.showCancel && this.$refs.cancel) {
        this.$refs.cancel.focus();
      }
    },

    onKeydown(event) {
      if (event.keyCode === 37 || event.keyCode === 39) {
        if (this.$refs.confirm && event.target === this.$refs.confirm.$el) {
          this.doFocusCancel();
        }
        if (this.$refs.cancel && event.target === this.$refs.cancel.$el) {
          this.doFocusConfirm();
        }
      }
    }
  }
};
</script>
