<script setup lang="ts">
import {useDraggable, useZIndex} from "element-plus";
import XEUtils from "xe-utils";
import {Close} from "@element-plus/icons-vue";
import {onDeactivated} from "@vue/runtime-core";

const props = withDefaults(defineProps<{
  width?: string | number,
  height?: string | number,
  x?: string | number,
  y?: string | number,
  title?: string,
  modelValue: boolean
}>(), {
  width: '300px',
  height: '400px',
  x: 30,
  y: 40,
  title: '标题'
})

const emits = defineEmits<{
  (e: "update:modelValue", value: boolean): void,
}>()

const vodyRef = ref()
const vRef = ref()
const zIndex = ref(useZIndex().nextZIndex())
const draggable = computed(() => {
  return true
})

const addUnit = (val: number | string) => XEUtils.addUnit(val)

const boxStyle = computed(() => {
  return {
    height: addUnit(props.height),
    width: addUnit(props.width),
    left: addUnit(props.x),
    top: addUnit(props.y),
    zIndex: zIndex.value
  }
})

watch(() => props.modelValue, (value, oldValue, onCleanup) => {
  if (value)
    zIndex.value = useZIndex().nextZIndex()
})

useDraggable(vodyRef, vRef, draggable)

onDeactivated(() => {
  emits('update:modelValue', false)
})

onUnmounted(() => {
  emits('update:modelValue', false)
})

</script>

<template>
  <transition name="el-fade-in-linear">
    <div class="floating_frame-box"
         :style="boxStyle"
         v-show="props.modelValue"
         ref="vodyRef">
      <header class="floating_frame-drag_reference" ref="vRef">
        <div class="floating_frame-title">
          {{ props.title }}
        </div>
        <div class="floating_frame-close_icon">
          <el-icon :size="16" @click="emits('update:modelValue' , false)">
            <Close/>
          </el-icon>
        </div>
      </header>
      <div class="floating_frame-body">
        <slot/>
      </div>
    </div>
  </transition>
</template>

<style scoped lang="scss">
.floating_frame-box {
  position: fixed;
  box-sizing: border-box;
  border-radius: 5px;
  background: white;
  box-shadow: var(--el-box-shadow);
  padding: 5px 16px;

  div {
    box-sizing: border-box;
    background: white;
  }

  .floating_frame-drag_reference {
    height: 30px;
    width: 100%;
    cursor: all-scroll;
    user-select: none;
    position: relative;
    border-bottom: 1px solid var(--el-border-color);

    .floating_frame-title {
      text-align: center;
      line-height: 30px;
    }

    .floating_frame-close_icon {
      position: absolute;
      height: inherit;
      width: 30px;
      right: 0;
      display: flex;
      top: 0;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }
  }

  .floating_frame-body {
    height: calc(100% - 30px);
    overflow: auto;
  }
}
</style>
