<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="90%"
    :style="{ maxWidth: '1600px' }"
    :close-on-click-modal="false"
    destroy-on-close
    class="form-iframe-dialog"
    @close="handleClose"
  >
    <div class="form-iframe-content">
      <iframe
        ref="iframeRef"
        :src="iframeSrc"
        frameborder="0"
        class="form-iframe"
      />
    </div>
  </el-dialog>
</template>

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

const props = defineProps<{
  dictData?: Record<string, any>
}>()

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

const visible = ref(false)
const iframeRef = ref<HTMLIFrameElement>()
const mode = ref<'add' | 'edit' | 'view'>('add')
const rowId = ref<string | number>('')

const dialogTitle = computed(() => {
  const titles = {
    add: '新增采购申请',
    edit: '编辑采购申请',
    view: '查看采购申请',
  }
  return titles[mode.value] || titles.add
})

const iframeSrc = computed(() => {
  const baseUrl = window.location.origin + window.location.pathname
  let src = `${baseUrl}#/purchase/purchasingrequisition/add`
  if (mode.value !== 'add' && rowId.value) {
    src += `?mode=${mode.value}&id=${rowId.value}`
  }
  return src
})

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

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

const openDialog = (openMode: 'add' | 'edit' | 'view', row?: any) => {
  mode.value = openMode
  rowId.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">
.form-iframe-content {
  width: 100%;
  height: 70vh;
  min-height: 500px;
  max-height: calc(100vh - 200px);
  position: relative;
  overflow: hidden;

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

<style>
.form-iframe-dialog.el-dialog {
  display: flex;
  flex-direction: column;
  max-height: 90vh;
  margin-top: 5vh !important;
}
.form-iframe-dialog .el-dialog__body {
  padding: 20px;
  overflow: hidden;
  flex: 1;
  min-height: 0;
}
</style>
