<template>
  <Vue3DraggableResizable
    v-if="visible"
    :id="panelId"
    v-bind="$attrs"
    v-model:x="x"
    v-model:y="y"
    v-model:w="w"
    v-model:h="h"
    v-model:active="active"
    :style="{ zIndex: zIndex }"
    :min-w="minWidth"
    :min-h="minHeight"
    class="cimui-resize-drag-panel"
    :init-w="width"
    :init-h="height"
    :draggable="draggable"
    :resizable="resizable"
    @activated="print('activated')"
    @deactivated="print('deactivated')"
    @drag-start="print('drag-start')"
    @resize-start="print('resize-start')"
    @dragging="dragging"
    @resizing="print('resizing')"
    @drag-end="dragEnd"
    @resize-end="print('resize-end')"
  >
    <div
      v-if="showHeader"
      class="cimui-panel-header"
      :class="draggable ? 'draggable-title' : ''"
    >
      <div class="cimui-panel-title">
        {{ title }}
        <slot name="header"></slot>
      </div>
    </div>
    <div
      ref="contentRef"
      class="cimui-drag-panel-content"
      :style="{
        height: showHeader?`${h - 40}px`:`${h}px`,
      }"
    >
      <slot> </slot>
    </div>
  </Vue3DraggableResizable>
</template>
<script lang="ts">
import { defineComponent, provide, toRefs, nextTick } from 'vue'
import Vue3DraggableResizable from 'vue3-draggable-resizable'
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css'

// import { addResizeFunction, removeResizeFunction } from '@/libs/utils'

export default defineComponent({
  name: 'ResizeDraggablePanel',
  components: { Vue3DraggableResizable },
  props: {
    panelId: {
      type: String,
      default: ''
    },
    // 面板样式，宽度/高度/初次显示时的位置
    panelStyle: {
      type: Object,
      default: () => {}
    },
    // 面板title
    title: {
      type: String,
      default: () => ''
    },
    back: {
      type: Boolean,
      default: false
    },
    // 是否可以拉伸
    resizable: {
      type: Boolean,
      default: true
    },
    // 是否可以拖拽
    draggable: {
      type: Boolean,
      default: true
    },
    showHeader: {
      type: Boolean,
      default: false
    },
    customClose: {
      type: Boolean,
      default: false
    },
    posChangable: {
      type: Boolean,
      default: true
    }
  },
  setup(props) {
    const { panelId } = toRefs(props)
    provide('identity', panelId.value)
  },
  data() {
    return {
      width: this.panelStyle?.width || 200,
      height: this.panelStyle?.height || 200,
      x:
        this.panelStyle?.left ||
        document.body.clientWidth -
          this.panelStyle?.width -
          this.panelStyle?.right ||
        100,
      y:
        this.panelStyle?.top ||
        document.body.clientHeight -
          this.panelStyle?.height -
          this.panelStyle?.bottom ||
        90,
      h: this.panelStyle?.height || 200,
      w: this.panelStyle?.width || 200,
      minWidth: this.panelStyle?.minWidth || 200,
      minHeight: this.panelStyle?.minHeight || 100,
      maxHeight: this.panelStyle?.maxHeight || 200,
      active: false,
      flootHeight: this.panelStyle?.footerHeight ?? 40,
      observer: null
    }
  },
  computed: {
    visible() {
      const that = this as any
      return true
    },
    zIndex() {
      const that = this as any
      return 999
    },
    globalSearchPanelVisible() {
      const that = this as any
      return true
    }
  },
  watch: {
    visible(val) {
      const that = this as any
      if (val) {
        this.$emit('beforeOpen')
        // addResizeFunction(that.panelId, that.changePanelPos)
        setTimeout(() => {
          that.changePanelPos()
        }, 300)

        if (that.panelStyle.maxHeight) {
          that.$nextTick(() => {
            that.refreshSize()
            that.observer.observe(document.querySelector(`#${that.panelId}`), {
              attributes: true,
              subtree: true,
              childList: true,
              characterData: true
            })
          })
        }
      } else {
        // removeResizeFunction(that.panelId)
        this.$emit('beforeClose')
      }
    },
    globalSearchPanelVisible(val) {
      if (!this.posChangable) {
        return
      }
      if (val) {
        this.y = 132
        this.changePanelPos()
      } else {
        this.y = 90
        this.changePanelPos()
      }
    }
  },
  mounted() {
    const that = this as any
    // 监听DOM变化
    if (that.panelStyle.maxHeight) {
      that.observer = new window.MutationObserver(() => {
        that.refreshSize()
      })
    }
  },
  methods: {
    changePanelPos() {
      const that = this as any
      const clientHeight = document.body.clientHeight
      if (that.panelStyle?.right) {
        that.x =
            document.body.clientWidth - that.width - that.panelStyle?.right
      }
      if (that.panelStyle?.bottom) {
        that.y =
            clientHeight - that.height - that.panelStyle?.bottom
      }
      this.changeHeight()
    },
    changeHeight() {
      const that = this as any
      const clientHeight = document.body.clientHeight
      const bottom = clientHeight - that.y - that.h

      if (bottom <= 16) {
        that.h = clientHeight - that.y - 16
      } else {
        that.h = that.height
      }
    },
    changeHeight_v2() {
      const that = this as any
      const clientHeight = window.innerHeight
      const currentH =
        that.$refs.contentRef?.children[0]?.offsetHeight + that.flootHeight + 40 || 200 // slot内容 + floot + header
      const bottom = clientHeight - that.y - currentH 
      const bottomWidget = document.getElementsByClassName('status-active')[0] as HTMLElement || 0//底部状态栏高度
      if (bottom <= 16 || currentH >= that.maxHeight) {
        if(bottomWidget.offsetHeight ){
          this.h = clientHeight - that.y - 16 - bottomWidget?.offsetHeight
          that.maxHeight = clientHeight - that.y - 16 - bottomWidget?.offsetHeight
        } else {
          this.h = clientHeight - that.y - 16
          that.maxHeight = clientHeight - that.y - 16
        }
      } else {
        this.h = currentH
      }
    },
    changeHeight_v3() {
      const that = this as any
      const clientHeight = window.innerHeight
      const currentH =
        that.$refs.contentRef?.children[0].offsetHeight + that.flootHeight + 40 // slot内容 + floot + header
      const bottom = clientHeight - that.y - currentH 
      const bottomWidget = document.getElementsByClassName('status-active')[0] as HTMLElement || 0//底部状态栏高度
      if (currentH >= that.maxHeight) {
        if(bottomWidget.offsetHeight ){
          this.h = clientHeight - that.y - that.panelStyle.bottom - bottomWidget?.offsetHeight
          that.maxHeight = clientHeight - that.y - that.panelStyle.bottom - bottomWidget?.offsetHeight
        } else {
          this.h = clientHeight - that.y - that.panelStyle.bottom
          that.maxHeight = clientHeight - that.y - that.panelStyle.bottom
        }
      } else {
        this.h = currentH
      }
    },
    refreshSize() {
      const that = this as any
      const currentH =
        that.$refs.contentRef?.children[0].offsetHeight + that.flootHeight + 40 // slot内容 + floot + header
      if (currentH <= that.height) {
        // 小于预设不改变大小
        that.h = that.height
      } else {
        if (currentH > that.maxHeight) {
          that.h = that.maxHeight

          const clientHeight = document.body.clientHeight
          const bottom = clientHeight - that.y - that.h
          // if (bottom <= 16) {
          //   that.h = clientHeight - that.y - 16
          // }
        } else {
          that.h = currentH
        }
      }
    },
    print(val: any) {
      if (val === 'drag-start') {
        document.body.style.cursor = 'move'
      } else if (val === 'drag-end') {
        document.body.style.cursor = 'default'
      }
    },
    // 阻止拖动body移动
    preventMouseMove() {
      console.log('prevent')
    },
    handleClose() {
      document.body.style.cursor = 'default'
      const _this = this as any
      if (this.$attrs['onHandleClose']) {
        this.$emit('handleClose')
      } else {
        _this.$store.commit('setPanelVisible', {
          id: _this.panelId,
          visible: false
        })
      }
      let domList = document.querySelectorAll('.el-sub-menu') 
      domList.forEach((dom: any) =>{
        dom.classList.remove('is-active')
      })
    },
    goBack() {
      this.$emit('back')
    },
    dragging(item: any) {
      // console.log('iye',item)
      // if(item.y < 88){
      //   this.y = 88
      // }
    },
    dragEnd(item: any) {
      if (item.y < 88) {
        this.y = 88
      }
      if (item.x > document.body.clientWidth) {
        this.x = document.body.clientWidth - this.w - 70
      }
      if (item.x < 0) {
        this.x = 50
      }
      // if (item.y > document.body.clientHeight - this.h) {
      //   this.y = document.body.clientHeight - this.h - 20
      // }
      document.body.style.cursor = 'default'
      this.$emit('panelDragEnd')
    }
  }
})
</script>
<style>
.vdr-handle {
  opacity: 0;
}
</style>
<style scoped lang="scss">
.cimui-resize-drag-panel {
  pointer-events: auto;
  background-color: rgba(0, 0, 0, 0.8);
  color: rgba(255,255,255);
  .cimui-panel-header {
    display: flex;
    justify-content: space-between;
    height: 40px;
    padding: 0px 10px;
    line-height: 40px;
    border-bottom: 1px solid #D8D8D8;
    font-weight: normal;
    font-size: 16px;
    &.draggable-title {
      cursor: move;
    }
    .close {
      color: #e1e5ec;
      cursor: pointer;
      margin-top: 14px;
      &:hover {
        color: #fff;
      }
    }
  }
  .cimui-drag-panel-content {
    overflow: auto;
    padding: 0 10px;
    font-size: 14px;
    &::-webkit-scrollbar{
      display: none;
    }
  }
  .cim-back {
    color: #BDC3CD;
    font-size: 22px;
    vertical-align: middle;
  }
}
</style>