<template>
  <transition
    name="dialog-fade"
    @after-enter="afterEnter"
    @after-leave="afterLeave"
  >
    <div
      v-show="visible"
      class="el-dialog__wrapper"
      @click.self="handleWrapperClick"
    >
      <div
        role="dialog"
        :key="key"
        aria-modal="true"
        :aria-label="title || 'dialog'"
        :class="[
          'el-dialog',
          { 'is-fullscreen': fullscreen, 'el-dialog--center': center },
          customClass,
        ]"
        ref="dialog"
        :style="style"
      >
        <!-- 对话框头部 -->
        <div class="el-dialog__header"
          v-if="header"
          :style="{
            'borderBottom': showDivider ? 'var(--border-1) solid rgb(var(--color-neutral-4))' : 'none',
            'height' : titleHeight !== '' ? `${titleHeight}px` : ''
          }"
        >
          <template v-if="title">
            <!-- 标题icon -->
            <i v-if="icon" :class="icon" class="dialog-title-icon"></i>
            <!-- 提示框默认样式 -->
            <span class="default" v-if="type == 'default' && !hiddenLine && !icon"></span>
            <!-- 不同类型提示框icon -->
            <i class="el-icon-success" v-if="type == 'success' && !icon"></i>
            <i class="el-icon-warning" v-if="type == 'warning' && !icon"></i>
            <i class="el-icon-error" v-if="type == 'error' && !icon"></i>
            <i class="el-icon-info" v-if="type == 'info' && !icon"></i>
            <span class="el-dialog__title">{{ title }}</span>
          </template>
          <slot name="title"></slot>
          <div v-if="!title && !$slots.title" class="el-dialog__header-placeholder"></div>
          <button
            type="button"
            class="el-dialog__headerbtn"
            aria-label="Close"
            v-if="showClose"
            @click="handleClose"
          >
            <i class="el-dialog__close el-icon el-icon-dialog-close"></i>
          </button>
        </div>
        <button
          type="button"
          class="el-dialog__headerbtn headerbtns"
          aria-label="Close"
          v-if="$slots.footer && !header"
          @click="handleClose"
        >
          <i class="el-dialog__close el-icon el-icon-dialog-close"></i>
        </button>
        <!-- 对话框内容 -->
        <div class="el-dialog__body" :class="{'hasfooter-content': $slots.footer && !header}" v-if="rendered" :style="bodyStyle">
          <div class="el-dialog__body_con">
            <div class="el-dialog__tip" v-if="tip">
              <el-tips-box
                  :tip-style="{
                border: 'var(--border-1) solid rgb(var(--modblue-7))',
                background: 'rgba(69, 101, 241, 0.1)',
              }"
                  :iconClassName="'el-icon-success'"
                  :iconStyle="{ color: 'rgb(var(--modblue-7))' }"
                  :type="success"
              >
                <template v-slot>
                  <div class="tips">
                    <span>{{tip}}</span>
                  </div>
                </template>
              </el-tips-box>
            </div>
            <slot></slot>
          </div>
        </div>
        <div class="el-dialog__footer" v-if="$slots.footer" :style="showDivider ? 'borderTop: var(--border-1) solid rgb(var(--color-neutral-4))' : 'borderTop:none'">
          <slot name="footer"></slot>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import Popup from 'modesign-ui/src/utils/popup';
import Migrating from 'modesign-ui/src/mixins/migrating';
import emitter from 'modesign-ui/src/mixins/emitter';

export default {
  name: 'ElDialog',

  mixins: [Popup, emitter, Migrating],

  props: {
    titleHeight: {
      type: [String, Number],
      default: ''
    },
    showIcon: {
      type: Boolean,
      default: false
    },
    showDivider: {
      type: Boolean,
      default: true
    },
    icon: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'default'
    },
    title: {
      type: String,
      default: ''
    },

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

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

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

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

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

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

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

    width: String,

    fullscreen: Boolean,

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

    top: {
      type: String,
      default: '15vh'
    },
    beforeClose: Function,
    center: {
      type: Boolean,
      default: false
    },
    tip: {
      type: String,
      default: ''
    },
    destroyOnClose: Boolean,

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

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

  data() {
    return {
      closed: false,
      key: 0,
      bodyStyle:{}
    };
  },

  watch: {
    visible(val) {
      if (val) {
        this.closed = false;
        this.$emit('open');
        this.$el.addEventListener('scroll', this.updatePopper);
        this.$nextTick(() => {
          this.$refs.dialog.scrollTop = 0;
        });
        if (this.appendToBody) {
          document.body.appendChild(this.$el);
        }

        //#region 计算el-dialog__body的高度
        let style = {};
        let headerFlag, footerFlag, headerHeight = 0, footerHeight = 0
        if (this.$refs.dialog.children.length > 0) {
          headerFlag = this.$refs.dialog.children[0].className === 'el-dialog__header'
          footerFlag = this.$refs.dialog.children[this.$refs.dialog.children.length - 1].className === 'el-dialog__footer'
        }
        
        this.$nextTick(()=>{
          if(headerFlag) {
            headerHeight = this.$el.querySelector(".el-dialog__header").getBoundingClientRect().height || 0
          }
          if(footerFlag) {
            footerHeight = this.$el.querySelector(".el-dialog__footer").getBoundingClientRect().height || 0
          }
          style.maxHeight = this.fullscreen ? `calc(100vh - ${headerHeight + footerHeight}px)` : `calc(100vh - ${120 + headerHeight + footerHeight}px)`
          style.overflowY = 'auto'
          this.bodyStyle = style
        })
        //#endregion
      } else {
        this.bodyStyle = {};
        this.$el.removeEventListener('scroll', this.updatePopper);
        if (!this.closed) this.$emit('close');
        if (this.destroyOnClose) {
          this.$nextTick(() => {
            this.key++;
          });
        }
      }
    }
  },

  computed: {
    style() {
      let style = {};
      if (!this.fullscreen) {
        // style.marginTop = this.top;
        if (this.width) {
          style.width = this.width;
          style.margin = '60px auto';
        }
      }
      return style;
    },
    // bodyStyle() {
    //   let style = {};
    //   let headerFlag, footerFlag
    //   if (this.$refs.dialog.children.length > 0) {
    //     headerFlag = this.$refs.dialog.children[0].className === 'el-dialog__header'
    //     footerFlag = this.$refs.dialog.children[this.$refs.dialog.children.length - 1].className === 'el-dialog__footer'
    //   }
    //   let headerHeight = headerFlag ? 64 : 0
    //   let footerHeight = footerFlag ? 64 : 0
    //   style.maxHeight = this.fullscreen ? `calc(100vh - ${48 + headerHeight + footerHeight}px)` : `calc(100vh - ${168 + headerHeight + footerHeight}px)`
    //   style.overflowY = 'auto'
    //   return style
    // }
  },

  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');
    },
    afterEnter() {
      this.$emit('opened');
    },
    afterLeave() {
      this.$emit('closed');
    }
  },

  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);
    }
    this.bodyStyle = {};
  }
};
</script>
