<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="科目" prop="subject">
        <select-subject v-model="formModel.subject"></select-subject>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="学号" prop="studentCode">
        <el-input v-model="formModel.studentCode" placeholder="请输入学号" />
      </el-form-item>
      <el-form-item label="准考证号" prop="examNumber">
        <el-input
          v-model="formModel.examNumber"
          placeholder="请输入准考证号"
          :disabled="isEdit"
        />
      </el-form-item>
      <el-form-item label="学院" prop="college">
        <el-input v-model="formModel.college" placeholder="请输入学院" />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-input v-model="formModel.className" placeholder="请输入班级" />
      </el-form-item>
      <el-form-item label="任课老师" prop="teacher">
        <el-input v-model="formModel.teacher" placeholder="请输入任课老师" />
      </el-form-item>
      <el-form-item label="签到表编号">
        <el-input
          v-model="formModel.packageCode"
          placeholder="请输入签到表编号"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">返回</el-button>
        <el-button type="primary" :loading="loading" @click="confirm"
          >保存</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import type { StudentItem, StudentUpdateParam } from '@/api/types/student';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign, objModifyAssign } from '@/utils/utils';
  import { updateStudent } from '@/api/student';

  defineOptions({
    name: 'ModifyStudent',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  interface Props {
    rowData: StudentItem;
  }

  const props = withDefaults(defineProps<Props>(), {
    rowData: {} as StudentItem,
  });
  const emit = defineEmits(['modified']);

  const isEdit = computed(() => !!props.rowData?.id);
  const title = computed(() => `${isEdit.value ? '编辑' : '新增'}学生`);

  const formRef = ref<FormInstance>();
  const initialFormState: Partial<StudentUpdateParam> = {
    name: '',
    studentCode: '',
    examNumber: '',
    college: '',
    className: '',
    teacher: '',
    packageCode: '',
    subject: '',
  };

  const formModel = reactive({ ...initialFormState });

  const rules: FormRules<keyof StudentUpdateParam> = {
    subject: [{ required: true, message: '请选择科目', trigger: 'change' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
    studentCode: [{ required: true, message: '请输入学号', trigger: 'change' }],
    examNumber: [
      { required: true, message: '请输入准考证号', trigger: 'change' },
    ],
    college: [{ required: true, message: '请输入学院', trigger: 'change' }],
    className: [{ required: true, message: '请输入班级', trigger: 'change' }],
    teacher: [{ required: true, message: '请输入任课老师', trigger: 'change' }],
    packageCode: [
      { required: true, message: '请输入签到表编号', trigger: 'change' },
    ],
  };

  const handleClose = () => {
    formRef.value?.resetFields();
  };

  /* confirm */
  const { loading, setLoading } = useLoading();
  async function confirm() {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    setLoading(true);
    const datas = objAssign(formModel, {});
    if (isEdit.value) {
      datas.id = props.rowData.id;
    }
    let res = true;
    await updateStudent(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    ElMessage.success(`${isEdit.value ? '编辑' : '新增'}成功！`);
    emit('modified', datas);
    close();
  }

  /* init modal */
  function modalBeforeOpen() {
    if (props.rowData.id) {
      // 编辑模式，映射字段
      objModifyAssign(formModel, props.rowData);
    } else {
      objModifyAssign(formModel, initialFormState);
    }
  }
</script>
