<script lang="ts" setup>
import { nanoid } from 'nanoid'
import useMove from '@/common/utils/use-move.ts'

const props = withDefaults(defineProps<{
  show: boolean
  title: string
  width?: string
  modal?: boolean
  appendToBody?: boolean
  closed?: () => void
}>(), {
  width: 'fit-content',
  closeOnSuccess: true,
  modal: false,
  appendToBody: false,
  closeBtnText: '关闭',
  submitBtnText: '提交',
  closed() {
  },
})

const emits = defineEmits([ 'update:show' ])

const id = nanoid()
const modalClass = 'draggable-dialog-modal-' + id

const showDialog = computed({
  get: () => props.show,
  set: (val) => {
    emits('update:show', val)
  },
})
const enableRender = ref(false)
let moveHandle = useMove(id)

function openedHandler() {
  const modal = document.querySelector('.' + modalClass)
  let container = modal?.querySelector('.el-overlay-dialog') as HTMLElement
  let dialog = container?.querySelector('.draggable-dialog') as HTMLElement
  let header = dialog?.querySelector('.el-dialog__header .el-dialog__title') as HTMLElement
  moveHandle
    .disable()
    .setContainer(container)
    .setWidget(dialog)
    .setTriggerArea(header)
    .enable()
}

function closedHandler() {
  moveHandle
    .disable()
    .setContainer()
    .setWidget()
    .setTriggerArea()
}

onMounted(() => {
  enableRender.value = true
})
onActivated(() => {
  moveHandle.enable()
})
onUnmounted(() => {
  moveHandle.destroy()
})

</script>

<template>
  <ElDialog
    :close-on-click-modal="false"
    :append-to-body="appendToBody"
    :modal="modal"
    :modal-class="modalClass"
    :model-value="showDialog"
    :title="title"
    class="draggable-dialog"
    destroy-on-close
    :width="width" @close="closed"
    @closed="closedHandler"
    @opened="openedHandler"
    @update:model-value="showDialog = $event"
  >
    <ElScrollbar>
      <slot/>
    </ElScrollbar>
    <template #footer>
      <slot name="footer"/>
    </template>
  </ElDialog>
</template>

<style lang="stylus" scoped>
</style>
