<template>
  <div class="xd-dialog">
    <el-dialog
      class="xd-dialog__box"
      custom-class="xd-dialog__box-modal"
      top="0"
      :title="title"
      :visible.sync="uiShow"
      :z-index="zIndex"
      :width="width"
      :close-on-click-modal="closeOnClickModal"
      :close-on-press-escape="closeOnPressEscape"
      :modal-append-to-body="modalAppendToBody"
      :append-to-body="appendToBody"
      :show-close="showClose"
      @closed="handleClosed"
      v-draggable
    >
      <div class="xd-dialog__box-modal-body">
        <slot></slot>
      </div>
      <div class="xd-dialog__box-modal-btn" v-if="isBtn">
        <slot name="btn">
          <div class="xd-dialog__box-footer">
            <el-button size="medium" @click="handleCancel">{{cancelName}}</el-button>
            <el-button size="medium" type="primary" @click="handleConfirm">{{confirmName}}</el-button>
          </div>
        </slot>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  /**
   * @description 重写el-dailog（兼容h5端显示）
   * 依赖于 element-ui
   * 参考网站如下：
   * https://element.eleme.cn/#/zh-CN/component/dialog
   * 文档：https://www.npmjs.com/package/gxd-helper
   *
   * @property {Array} width 插件宽度 （选填） 默认：50%
   * @property {Boolean} isBtn 是否确认取消按钮 （选填） 默认：true
   * @property {Boolean} show 控制插件显示隐藏 （选填） 默认：false
   * @property {Boolean} modalAppendToBody 遮罩层是否插入至 body 元素上，若为 false，则遮罩层会插入至 Dialog 的父元素上 （选填） 默认：true（插入body）
   * @property {Boolean} appendToBody Dialog 自身是否插入至 body 元素上。嵌套的 Dialog 必须指定该属性并赋值为 true （选填） 默认：true（插入body）
   * @property {Boolean} closeOnClickModal 是否可以通过点击 modal 关闭 Dialog（选填） 默认：false
   * @property {Boolean} closeOnPressEscape 是否可以通过按下 ESC 关闭 Dialog （选填） 默认：false
   * @property {Number} zIndex 显示层级关系 （选填） 默认：3000
   * @property {String} title 插件显示标题  默认：标题
   *
   * @event {Function} onClose 插件关闭事件
   * @event {Function} onCancel 当显示取消和确认按钮时候-取消按钮事件
   * @event {Function} onConfirm  当显示取消和确认按钮时候-确认按钮事件
   *
   * @slot 默认插槽（default）
   * @slot 按钮插槽（btn）
   */
  let XdDialogVm = null
  export default {
    name: "XdDialog",
    props:{
      showClose: {
        type: Boolean,
        default: true
      },
      confirmName:{
        type:String,
        default: '确 定'
      },
      cancelName:{
        type:String,
        default: '取 消'
      },
      width: {
        type:String,
        default: '50%'
      },
      isBtn:{
        type: Boolean,
        default: true
      },
      show: {
        type: Boolean,
        default: false
      },
      modalAppendToBody: {
        type: Boolean,
        default: true
      },
      appendToBody: {
        type: Boolean,
        default: true
      },
      closeOnClickModal: {
        type: Boolean,
        default: false
      },
      closeOnPressEscape: {
        type: Boolean,
        default: false
      },
      title:{
        type: String,
        default: '标题'
      },
      zIndex: {
        type: Number,
        default: 3000
      },
      isAutoCancel: {
        type: Boolean,
        default: true
      },
      isMove:{
        type: Boolean,
        default: false
      },
    },
    directives:{
      draggable:{
        bind(el) {
          if(XdDialogVm.isMove === false) return;
          let startPosition = {x: 0, y: 0};
          let dialogPosition = {x: 0, y: 0};
          let dragging = false;
          const handleMouseDown = (e) => {
            let ele = e.target || e.srcElement;
            if(ele.className.indexOf('el-dialog__header') !== -1) {
              startPosition.x = e.clientX;
              startPosition.y = e.clientY;
              dialogPosition.x = parseInt(el.style.left, 10) || 0;
              dialogPosition.y = parseInt(el.style.top, 10) || 0;
              document.addEventListener('mousemove', handleMouseMove);
              document.addEventListener('mouseup', handleMouseUp);
              ele.style.cursor = 'move';
              dragging = true;
              e.stopPropagation();
              e.preventDefault();
            }
          };
          const handleMouseMove = (e) => {
            if (dragging) {
              const offsetX = e.clientX - startPosition.x;
              const offsetY = e.clientY - startPosition.y;
              el.style.left = `${dialogPosition.x + offsetX}px`;
              el.style.top = `${dialogPosition.y + offsetY}px`;
              el.style.right = `${-(dialogPosition.x + offsetX)}px`;
              el.style.bottom = `${-(dialogPosition.y + offsetY)}px`;
            }
          };
          const handleMouseUp = (e) => {
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
            let ele = e.target || e.srcElement;
            ele.style.cursor = '';
            dragging = false;
          };
          el.addEventListener('mousedown', handleMouseDown);
        }
      }
    },
    data(){
      return {
        uiShow: false
      }
    },
    watch:{
      show(value){
        console.log(value);
        this.uiShow = value
      }
    },
    created(){
      this.uiShow = this.show;
      XdDialogVm = this
    },
    methods: {
      handleClosed(){
        this.$emit('update:show', this.uiShow);
        this.$emit('onClose')
      },

      handleCancel(){
        if(this.isAutoCancel) {
          this.uiShow = false;
          this.$emit('update:show', this.uiShow);
        }
        this.$emit('onCancel')
      },

      handleConfirm(){
        this.$emit('onConfirm')
      }


    }
  }
</script>

<style scoped lang="scss">
  .xd-dialog {
    &__box {
      ::v-deep &-modal {
        top: 50%;
        transform: translateY(-50%);
        padding-bottom: 20px;

        & .el-dialog__body {
          margin: 0;
          padding: 0;
        }

        &-body {
          /*margin: 10px 20px 0;*/
          margin: 0;
          padding: 10px 20px 0;
          max-height: 80vh;
          overflow-y: auto;
        }

        &-btn {
          margin: 20px 20px 5px;
          display: flex;
          justify-content: flex-end;
          align-items: center;
        }


      }

    }
  }

  @media screen and (max-width: 768px) {
    .xd-dialog {
      &__box {
        ::v-deep &-modal {
          width: 95% !important;
          margin: 0 auto;
          padding-bottom: 10px;

          & .el-dialog__header {
            padding: 10px 10px 5px;

          }

          & .el-dialog__headerbtn {
            top: 15px;
            right: 10px;
          }

          & .el-dialog__title {
            font-size: 14px;
          }

          &-body {
            margin: 0;
            padding: 10px 10px 0;
            max-height: 70vh;
            overflow-y: auto;
          }
        }


      }
    }
  }
</style>
