<template>
  <el-dialog
    v-model="visible"
    title="实施采购"
    width="560px"
    :close-on-click-modal="false"
    destroy-on-close
    class="implement-iframe-dialog"
    @close="handleClose"
  >
    <div class="implement-iframe-content">
      <iframe
        ref="iframeRef"
        :src="iframeSrc"
        frameborder="0"
        class="implement-iframe"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts" name="ImplementForm">
import { ref, computed, watch } from 'vue'

const emit = defineEmits<{
  (e: 'refresh'): void
}>()

const visible = ref(false)
const iframeRef = ref<HTMLIFrameElement>()
const applyId = ref<string | number>('')

const iframeSrc = computed(() => {
  const baseUrl = window.location.origin + window.location.pathname
  return `${baseUrl}#/finance/purchasingrequisition/implement?id=${applyId.value}`
})

const handleClose = () => {
  visible.value = false
  window.removeEventListener('message', handleMessage)
}

const handleMessage = (event: MessageEvent) => {
  if (event.data?.type === 'purchasingimplement:submitSuccess') {
    handleClose()
    emit('refresh')
  } else if (event.data?.type === 'purchasingimplement:close') {
    handleClose()
  } else if (event.data?.type === 'purchasingimplement:saved') {
    emit('refresh')
  }
}

const openDialog = (row: { id: string | number }) => {
  applyId.value = row?.id ?? ''
  visible.value = true
  window.addEventListener('message', handleMessage)
}

watch(visible, (val) => {
  if (!val) {
    window.removeEventListener('message', handleMessage)
  }
})

defineExpose({
  openDialog,
})
</script>

<style scoped lang="scss">
.implement-iframe-content {
  width: 100%;
  height: 65vh;
  min-height: 480px;
  max-height: calc(100vh - 180px);
  position: relative;
  overflow: hidden;

  .implement-iframe {
    width: 100%;
    height: 100%;
    min-height: 480px;
    border: none;
    display: block;
  }
}
</style>

<style>
.implement-iframe-dialog .el-dialog__body {
  padding: 16px;
  overflow: hidden;
}
</style>
