<template>
    <div class="c_dialog" v-show="visible">
        <!-- <div class="bg"></div> -->
        <div class="wrapper">
            <div class="header" >
                <div class="text">{{ title }}</div>
                <div class="fn">
                    <div class="close" v-if="showClose" @click="handleClose"></div>
                </div>
            </div>
            <div class="content">
                <slot></slot>
            </div>
        </div>
    </div>
</template>
<script>
  import Migrating from 'touch-vue/src/mixins/migrating';
  import emitter from 'touch-vue/src/mixins/emitter';

  export default {
    name: 'ToDialog',

    mixins: [emitter, Migrating],

    props: {
      visible: {
        type: Boolean,
        default: false
      },

      title: {
        type: String,
        default: ''
      },

      closeOnPressEscape: {
        type: Boolean,
        default: true
      },

      showClose: {
        type: Boolean,
        default: true
      },

      width: String,

      customClass: {
        type: String,
        default: ''
      },

      beforeClose: Function,
      center: {
        type: Boolean,
        default: false
      },

      destroyOnClose: Boolean
    },
    data() {
      return {
        closed: false,
        key: 0
      };
    },
    watch: {
      visible(val) {
        if (val) {
          this.closed = false;
          this.$emit('open');
          this.$nextTick(() => {
            // this.$refs.dialog.scrollTop = 0;
          });
          //document.body.appendChild(this.$el);
        } else {
          if (!this.closed) this.$emit('close');
          if (this.destroyOnClose) {
            this.$nextTick(() => {
              this.key++;
            });
          }
        }
      }
    },
    mounted() {
      this.$nextTick(() => {
        document.body.appendChild(this.$el);
      });
    },
    methods: {
      getMigratingConfig() {
        return {
          props: {
            'size': 'size is removed.'
          }
        };
      },
      handleWrapperClick() {
        if (!this.closeOnClickModal) return;
        this.handleClose();
      },
      handleClose() {
        if (typeof this.beforeClose === 'function') {
          this.beforeClose(this.hide);
        } else {
          this.hide();
        }
      },
      hide(cancel) {
        if (cancel !== false) {
          this.$emit('update:visible', false);
          this.$emit('close');
          this.closed = true;
        }
      }
    },
    destroyed() {
      if (this.$el && this.$el.parentNode) {
        this.$el.parentNode.removeChild(this.$el);
      }
    }
  };
</script>
