<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus";
defineProps({
  title: String,
  rules: {
    type: Object as () => FormRules,
    default: () => ({}),
  },
});
const emit = defineEmits<{
  submit: [form: any, formRef: FormInstance | undefined];
  reset: [];
}>();
const visible = defineModel<boolean>("visible");
const form = defineModel<any>("form");
const formRef = ref<FormInstance>();
watch(visible, (newV, oldV) => {
  if (!newV) {
    formRef.value?.clearValidate();
  }
});
defineExpose({
  formRef,
  clearValidate: () => formRef.value?.clearValidate(),
  resetFields: () => formRef.value?.resetFields(),
});
const handleReset = () => {
  // 1. 清除验证状态
  formRef.value?.clearValidate();

  // 2. 重置表单字段到初始值 (如果 form 是响应式对象，这通常有效)
  // 注意：resetFields 需要 form 初始值不为空，如果初始是 {}，可能无效。
  // 为了保险，我们发出事件让父组件处理复杂逻辑，自己只负责基础清理

  // 3. 如果没有父组件监听，默认行为是清空 form (可选，视需求而定)
  form.value = {};

  emit("reset");
};
</script>
<template>
  <el-dialog
    :title="title"
    v-model="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :lock-scroll="false"
  >
    <el-form ref="formRef" label-position="left" label-width="auto" :model="form" :rules="rules || {}">
      <slot name="form-items"></slot>
      <el-form-item>
        <div class="button-container">
          <el-button type="primary" @click="emit('submit', form, formRef)">{{ $t("_button.submit") }}</el-button>
          <el-button @click="handleReset">{{ $t("_button.reset") }}</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<style>
.button-container {
  width: 100%;
  margin: 20px 0;
  text-align: center;
}

:deep(.el-dialog) {
  overflow: hidden;
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 16px 20px;
  margin-right: 0;
  background-color: var(--el-fill-color-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

:deep(.el-dialog__headerbtn) {
  top: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-regular);
}
</style>
