<template>
  <el-drawer
    v-model="props.drawer"
    custom-class="custom-drawer-header"
    :title="props.data.properties?.name || '参数配置'"
    class="no-header-margin"
    :before-close="confirmSave"
  >
    <component
      :is="currentComponent"
      ref="paramsComponentRef"
      :data="props.data"
      @save-success="handleSaveSuccess"
      @save-error="handleSaveError"
    />
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { emitter } from '@/utils/eventBus'

// 导入各子组件
import StartParams from './params/StartParams.vue'
import BasicNodeParams from './params/BasicNodeParams.vue'
import CodeNodeParams from './params/CodeNodeParams.vue'
import HttpNodeParams from './params/HttpNodeParams.vue'
import SdAgentNodeParams from './params/SdAgentNodeParams.vue'
import RecognizeNodeParams from './params/RecognizeNodeParams.vue'

const props = defineProps({
  drawer: Boolean,
  data: Object
})

const emits = defineEmits(['close'])
const paramsComponentRef = ref(null)

// 根据节点类型决定渲染哪个子组件
const currentComponent = computed(() => {
  const type = props.data?.type
  if (type === 'start') return StartParams
  if (['currentLoop', 'serviceNode', 'sleep', 'loop'].includes(type)) return BasicNodeParams
  if (type === 'code') return CodeNodeParams
  if (type === 'http') return HttpNodeParams
  if (type === 'sdAgent') return SdAgentNodeParams
  if (type === 'recognize') return RecognizeNodeParams
  return null
})

// 这里提供一个公开方法供父组件调用
const confirmSave = async () => {
  if (paramsComponentRef.value && typeof paramsComponentRef.value.validateAndSave === 'function') {
    await paramsComponentRef.value.validateAndSave()
  }
}

// 暴露给父组件使用
defineExpose({ confirmSave })

// 保存成功 / 失败处理
const handleSaveSuccess = () => {
  emitter.emit('setProperties', { id: props.data.id })
  emitter.emit("throwAnError", { id: props.data.id, hasError: false, type: props.data.type });
  // 无错误，关闭抽屉
  emits('close')
}

const handleSaveError = () => {
  emitter.emit('setProperties', { id: props.data.id })
  emitter.emit("throwAnError", { id: props.data.id, hasError: true, type: props.data.type });
  emits('close')
}

// 组件卸载时清理事件监听
// 注意：emitter.off 应在各子组件中自行清理，父组件不再重复
</script>

<style lang="scss">
.no-header-margin .el-drawer__header {
  margin-bottom: 0 !important;
}
</style>