<template>
  <transition
    name="dialog-fade"
    @after-leave="afterLeave">
    <div class="el-dialog__wrapper" v-show="visible" @click.self="handleWrapperClick">
      <div
        class="el-dialog"
        :class="[{ 'is-fullscreen': fullscreen, 'el-dialog--center': center }, customClass]"
        ref="dialog"
        :style="[style, setBottom, {'width': width, 'height': height, 'margin-bottom': this.bottom ? '0' : ''}]">
        <div class="el-dialog__header">
          <slot name="title">
            <span class="el-dialog__title">{{ title }}</span>
          </slot>
          <button
            type="button"
            class="el-dialog__headerbtn"
            aria-label="Close"
            v-if="showClose"
            @click="handleClose">
            <i class="el-dialog__close el-icon el-icon-close"></i>
          </button>
        </div>
        <div class="el-dialog__body" ref="body" v-if="rendered">
          <!-- 当有定义height,bottom,responseLimit才显示滚动条配置 -->
          <el-scrollbar class="el-dialog__scrollbar"
                        :wrap-style="(height || bottom ? 'height:' + wrapHeight + 'px;' : '') + (responseLimit ? 'maxHeight:' + wrapMaxHeight + 'px;' : '')"
                        outsider
                        v-if="this.bottom || this.responseLimit || this.height"
                        ref="dialogScroll"
                        wrap-class="el-dialog__wrap"
                        view-class="el-dialog__view">
            <div class="el-dialog__content" ref="content">
              <slot></slot>
            </div>
          </el-scrollbar>
          <div class="el-dialog__content" v-else ref="contentBody">
            <slot></slot>
          </div>
        </div>
        <div class="el-dialog__footer"  ref="footer" v-if="$slots.footer">
          <slot name="footer"></slot>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
  import Popup from 'nui-v2/src/utils/popup';
  import Migrating from 'nui-v2/src/mixins/migrating';
  import emitter from 'nui-v2/src/mixins/emitter';
  import { addResizeListener } from 'nui-v2/src/utils/resize-event';

  export default {
    name: 'ElDialog',

    mixins: [Popup, emitter, Migrating],

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

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

      modalAppendToBody: {
        type: Boolean,
        default: false
      },

      appendToBody: {
        type: Boolean,
        default: false
      },

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

      closeOnClickModal: {
        type: Boolean,
        default: false
      },

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

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

      width: String,

      height: String,
      // ContentHeight: String,
      // ContentMinHeight: String,

      fullscreen: Boolean,

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

      top: {
        type: String,
        default: '15vh'
      },

      bottom: String,
      beforeClose: Function,
      nesting: {
        type: Boolean,
        default: false
      },
      // 内容区域自适应高度，不超出一屏高度
      responseLimit: {
        type: Boolean,
        default: true
      },
      // 是否显示横向滚动条
      showScrollX: {
        type: Boolean,
        default: true
      },
      // 弹窗是否垂直居中
      vetically: {
        type: Boolean,
        default: true
      },
      center: {
        type: Boolean,
        default: false
      }
    },

    data() {
      return {
        closed: false,
        setTop: '',
        wrapMaxHeight: '',
        wrapHeight: ''
      };
    },

    watch: {
      visible: {
        handler(val) {
          let maxHeight;
          let height;
          if (val) {
            this.closed = false;
            this.$emit('open');
            // this.$el.addEventListener('scroll', this.updatePopper);
            this.$nextTick(() => {
              this.$refs.dialog.scrollTop = 0;
              if (this.bottom || this.responseLimit || this.height) {
                // 设置内容区域高度
                maxHeight = window.innerHeight + 17 - ((this.$refs.header !== undefined ? this.$refs.header.offsetHeight : 0) + (this.$refs.footer !== undefined ? this.$refs.footer.offsetHeight : 0) + 2 * (this.$refs.dialogScroll.$el.offsetTop - (this.$refs.header !== undefined ? this.$refs.header.offsetHeight : 0)));
                if (navigator.platform === 'Mac68K' || navigator.platform === 'MacPPC' || navigator.platform === 'Macintosh' || navigator.platform === 'MacIntel') {
                  height = this.$refs.dialog.clientHeight + 45 - ((this.$refs.header !== undefined ? this.$refs.header.offsetHeight : 0) + (this.$refs.footer !== undefined ? this.$refs.footer.offsetHeight : 0) + 2 * (this.$refs.dialogScroll.$el.offsetTop - (this.$refs.header !== undefined ? this.$refs.header.offsetHeight : 0)));
                } else {
                  height = this.$refs.dialog.clientHeight + 17 + 45 - ((this.$refs.header !== undefined ? this.$refs.header.offsetHeight : 0) + (this.$refs.footer !== undefined ? this.$refs.footer.offsetHeight : 0) + 2 * (this.$refs.dialogScroll.$el.offsetTop - (this.$refs.header !== undefined ? this.$refs.header.offsetHeight : 0)));
                }
                this.wrapMaxHeight = maxHeight;
                this.wrapHeight = height;
                // 隐藏横向滚动条
                if (!this.showScrollX) {
                  if (this.$refs.dialogScroll.$el.children[1]) {
                    this.$refs.dialogScroll.$el.children[1].style.opacity = '0';
                  }
                }
                // 监听滚动条
                this.$refs.dialogScroll.$el.children[0].addEventListener('scroll', this.scrollEvent);
              }
              // // 设置内容区高度
              // if (this.ContentHeight) {
              //   this.$refs.contentBody.style.height = this.ContentHeight;
              // }
              // // 设置内容区最小高度
              // if (this.ContentMinHeight) {
              //   this.$refs.contentBody.style.minHeight = this.ContentMinHeight;
              // }
              addResizeListener(this.$refs.dialog, this.setTopValue);
            });
            if (this.appendToBody) {
              document.body.appendChild(this.$el);
            }
          } else {
            // this.$el.removeEventListener('scroll', this.updatePopper);
            // this.setTop = '';
            maxHeight = 0;
            height = 0;
            if (!this.closed) this.$emit('close');
            this.wrapMaxHeight = '';
            this.wrapHeight = '';
          }
        },
        immediate: true,
        deep: true
      }
    },

    computed: {
      style() {
        return this.size === 'full' ? {} : { 'top': this.veticallyStatus ? this.setTop : this.top };
      },
      setBottom() {
        return this.size === 'full' ? {} : { 'bottom': this.veticallyStatus ? '' : this.bottom };
      },
      // 设置是否垂直居中的状态
      veticallyStatus() {
        if (this.bottom) {
          return false;
        } else {
          return this.vetically;
        }
      }
    },

    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;
        }
      },
      updatePopper() {
        this.broadcast('ElSelectDropdown', 'updatePopper');
        this.broadcast('ElDropdownMenu', 'updatePopper');
      },
      afterLeave() {
        this.$emit('closed');
      },
      setTopValue() {
        if (this.$refs.dialog) {
          if (window.innerHeight > this.$refs.dialog.clientHeight) {
            this.setTop = (window.innerHeight - this.$refs.dialog.clientHeight) / 2 + 'px';
          } else {
            this.setTop = '20px';
            if (this.$refs.dialogScroll && this.responseLimit) {
              this.$refs.dialogScroll.$el.firstChild.style.maxHeight = this.$refs.dialogScroll.$el.firstChild.clientHeight - 20 + 'px';
            }
          }
        }
      }
    },

    mounted() {
      if (this.visible) {
        this.rendered = true;
        this.open();
        if (this.appendToBody) {
          document.body.appendChild(this.$el);
        }
      }
    },

    destroyed() {
      // if appendToBody is true, remove DOM node after destroy
      if (this.appendToBody && this.$el && this.$el.parentNode) {
        this.$el.parentNode.removeChild(this.$el);
      }
    }
  };
</script>