<template>
  <el-dialog v-model="visible" :title="dialogTitle" width="560px" destroy-on-close>
    <div class="dialog-form">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-suffix="：">
        <el-form-item label="专业领域" prop="expertiseAreaInfo">
          <el-input v-model="form.expertiseAreaInfo" placeholder="请输入专业领域" clearable />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="visible = false"> 取 消 </el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit"> 保 存 </el-button>
    </template>
  </el-dialog>
</template>

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

interface DialogOptions {
  title: string;
  row?: Record<string, any>;
  onSubmit: (params: Record<string, any>) => Promise<any>;
}

const visible = ref(false);
const loading = ref(false);
const formRef = ref<FormInstance>();
const options = ref<DialogOptions>({
  title: "",
  onSubmit: async () => Promise.resolve()
});

const form = reactive({
  id: "",
  expertiseAreaInfo: ""
});

const rules = reactive({
  expertiseAreaInfo: [{ required: true, message: "请输入专业领域", trigger: "blur" }]
});

const dialogTitle = computed(() => options.value.title);

const resetForm = () => {
  form.id = "";
  form.expertiseAreaInfo = "";
};

const open = (payload: DialogOptions) => {
  resetForm();
  options.value = payload;
  if (payload.row) {
    Object.assign(form, payload.row);
  }
  visible.value = true;
  nextTick(() => formRef.value?.clearValidate());
};

const emits = defineEmits<{
  success: [];
}>();

const handleSubmit = () => {
  formRef.value?.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      await options.value.onSubmit({ ...form });
      emits("success");
      visible.value = false;
    } finally {
      loading.value = false;
    }
  });
};

defineExpose({
  open
});
</script>

<style scoped lang="scss">
.dialog-form {
  max-width: 420px;
  margin: 0 auto;
}
</style>
