useAnswer.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { useCheckObjectiveStore } from "@/store";
  2. import { saveStudentObjectiveConfirmData } from "@/api/checkPage";
  3. import { message } from "ant-design-vue";
  4. import { useStudent } from "../useStudent";
  5. export default function useAnswer() {
  6. const checkObjectiveStore = useCheckObjectiveStore();
  7. const { updateCurStudent, getNextStudent } = useStudent();
  8. // 修改答案
  9. const allowKey = [
  10. "Delete",
  11. "Backspace",
  12. "ArrowLeft",
  13. "ArrowRight",
  14. "#",
  15. "Shift",
  16. "[A-Za-z]",
  17. ];
  18. const allowKeyRef = new RegExp(allowKey.join("|"));
  19. function onPreventAnswerKey(e: KeyboardEvent) {
  20. if (!allowKeyRef.test(e.key)) {
  21. e.preventDefault();
  22. }
  23. }
  24. function changeAnswer(event: Event, question: string, defaultValue?: string) {
  25. const target = event.target as HTMLInputElement;
  26. checkObjectiveStore.student.answers =
  27. checkObjectiveStore.student.answers.map((v) => {
  28. if (
  29. v.mainNumber === question.mainNumber &&
  30. v.subNumber === question.subNumber
  31. ) {
  32. v.answer = target?.value.toUpperCase().trim() || defaultValue || "";
  33. }
  34. return v;
  35. });
  36. }
  37. // 保存答案
  38. let loading = false;
  39. async function saveStudentAnswer() {
  40. if (!checkObjectiveStore.student) return;
  41. if (loading) return;
  42. loading = true;
  43. const data = {
  44. studentId: checkObjectiveStore.student.studentId,
  45. answers: checkObjectiveStore.student.answers
  46. .map((v) => v.answer || "#")
  47. .join(","),
  48. };
  49. // if (!answers.match(/^(#*,*[A-Z]*)+$/g)) {
  50. // void message.error("答案只能是#和大写英文字母");
  51. // return;
  52. // }
  53. const res = await saveStudentObjectiveConfirmData(data).catch(() => false);
  54. loading = false;
  55. if (!res) {
  56. void message.error("保存失败,请刷新页面。");
  57. } else {
  58. void message.success("保存成功");
  59. if (!checkObjectiveStore.isMultiStudent) {
  60. window.close();
  61. return;
  62. }
  63. if (checkObjectiveStore.isLast) {
  64. await updateCurStudent();
  65. } else {
  66. await getNextStudent();
  67. }
  68. }
  69. }
  70. return {
  71. onPreventAnswerKey,
  72. changeAnswer,
  73. saveStudentAnswer,
  74. };
  75. }