<template>
  <el-dialog
    v-model="visible"
    title="实施采购"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
    @close="handleClose"
  >
    <ImplementContent
      ref="implementContentRef"
      @close="handleContentClose"
      @saved="handleContentSaved"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="confirming" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ImplementForm">
import { ref, nextTick } from 'vue'
import ImplementContent from './implement.vue'

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

const visible = ref(false)
const implementContentRef = ref<InstanceType<typeof ImplementContent>>()
const confirming = ref(false)
const pendingRow = ref<{ id: string | number } | null>(null)

const handleClose = () => {
  visible.value = false
}

const handleContentClose = () => {
  visible.value = false
  emit('refresh')
}

const handleContentSaved = () => {
  emit('refresh')
}

const handleConfirm = async () => {
  confirming.value = true
  try {
    await implementContentRef.value?.handleConfirm()
    visible.value = false
    emit('refresh')
  } finally {
    confirming.value = false
  }
}

const openDialog = async (row: { id: string | number }) => {
  pendingRow.value = row
  visible.value = true
  // 等待 dialog 及内部组件挂载完成后再调用 open
  await nextTick()
  if (pendingRow.value) {
    implementContentRef.value?.open(pendingRow.value)
    pendingRow.value = null
  }
}

defineExpose({
  openDialog,
})
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>