<template>
  <el-dialog 
    title="简单信息维护" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="600px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="120px" 
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-form-item label="姓名" prop="realName">
        <el-input 
          v-model="form.realName" 
          placeholder="请输入姓名" 
          clearable />
      </el-form-item>
      <el-form-item label="曾用名" prop="oldName">
        <el-input 
          v-model="form.oldName" 
          placeholder="请输入曾用名" 
          clearable />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input 
          v-model="form.idCard" 
          placeholder="请输入身份证号" 
          clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="SimpleEditDialog">
import { ref, reactive, nextTick } from 'vue'
import { useMessage } from "/@/hooks/message";
import { updateStuSimpleInfo } from '/@/api/basic/basicstudent'

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)

// 提交表单数据
const form = reactive({
  id: '',
  realName: '',
  oldName: '',
  idCard: ''
});

// 定义校验规则 - 只有姓名和身份证号是必填的，曾用名不是必填
const dataRules = ref({
  realName: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
  // oldName 不是必填，不需要验证规则
})

// 打开弹窗
const openDialog = (rowData: any) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: rowData.id || '',
    realName: rowData.realName || '',
    oldName: rowData.oldName || '',
    idCard: rowData.idCard || ''
  })

  // 清除表单验证状态
  nextTick(() => {
    dataFormRef.value?.clearValidate();
    dataFormRef.value?.resetFields();
  });
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;
    await updateStuSimpleInfo(form);
    useMessage().success('更新成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || '更新失败');
  } finally {
    loading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  openDialog
});
</script>

