<template>
  <a-modal
    v-bind="restAttrs"
    :dialog-style="{ top: `${y + 100}px`, left: `${x}px` }"
    :mask-closable="false"
    :width="1000"
    v-on="$listeners"
  >
    <template v-if="$scopedSlots.title || $attrs.title" v-slot:title="scope">
      <div :class="$style.title">
        <slot v-if="!$attrs.title" name="title" v-bind="scope" />
        <slot v-else name="title">
          {{ $attrs.title }}
        </slot>
        <VueDraggableResizable
          h="auto"
          w="auto"
          :resizable="false"
          :class-name="$style.handle"
          :on-drag="onDrag"
        >
          <LifecycleListener @created="titleCreated" />
        </VueDraggableResizable>
      </div>
    </template>
    <template v-for="(_, slot) of restSlots" v-slot:[slot]="scope">
      <slot :name="slot" v-bind="scope" />
    </template>
  </a-modal>
</template>

<script>
import { Modal } from 'ant-design-vue'
import VueDraggableResizable from 'vue-draggable-resizable'
import components from './_import-components/sd-draggable-modal-import'

const LifecycleListener = {
  created() {
    this.$emit('created')
  },
  render() {},
}

/**
 * 可拖拽的对话框，与 a-modal 用法相同并全局替换了 a-modal
 * @displayName SdDraggableModal 对话框
 * @since 8.0.11
 */
export default {
  name: 'SdDraggableModal',
  components: {
    ...components,
    'a-modal': Modal,
    VueDraggableResizable,
    LifecycleListener,
  },
  inheritAttrs: false,
  model: {
    prop: 'visible',
    event: 'change',
  },
  data() {
    return {
      x: 0,
      y: 0,
    }
  },
  computed: {
    restSlots() {
      const { title, ...rest } = this.$scopedSlots
      return rest
    },
    restAttrs() {
      const { title, ...rest } = this.$attrs
      return rest
    },
  },
  methods: {
    onDrag(x, y) {
      this.x = x
      this.y = y
    },
    titleCreated() {
      this.x = this.y = 0
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.title {
  position: relative;
}
.handle {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: -16px -24px;
  // 覆盖拖拽内容style标签里面的样式
  /* stylelint-disable-next-line  */
  transform: none !important;
}
</style>
