<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="500px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="反应器" prop="reactorId">
        <el-select
          v-model="form.reactorId"
          placeholder="请选择反应器"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in reactorOptions"
            :key="item.id"
            :label="`${item.name} - ${item.spec}`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

interface ReactorOption {
  id: number
  name: string
  spec: string
}

interface FormData {
  reactorId: number | null
  remark: string
}

interface Props {
  title?: string
  reactorOptions?: ReactorOption[]
}

const props = withDefaults(defineProps<Props>(), {
  title: '选择反应器',
  reactorOptions: () => []
})

const emit = defineEmits<{
  confirm: [data: FormData]
}>()

const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()

const form = reactive<FormData>({
  reactorId: null,
  remark: ''
})

const rules: FormRules = {
  reactorId: [
    { required: true, message: '请选择反应器', trigger: 'change' }
  ]
}

const open = () => {
  visible.value = true
  // 重置表单
  nextTick(() => {
    form.reactorId = null
    form.remark = ''
    formRef.value?.clearValidate()
  })
}

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

const handleConfirm = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    
    console.log('弹窗确认, 发送的数据:', {
      reactorId: form.reactorId,
      remark: form.remark
    })
    
    emit('confirm', {
      reactorId: form.reactorId,
      remark: form.remark
    })
    
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const closeDialog = () => {
  loading.value = false
  visible.value = false
}

defineExpose({
  open,
  closeDialog
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style> 