import { httpApp } from "@/plugins/axiosIndex";
import { pickBy } from "lodash-es";
import { getMd5FromBlob, object2QueryString } from "@/utils/utils";

export async function searchTasks({
  examId = "",
  entityId = "",
  type = "",
  pageNumber = 1,
  pageSize = 10,
}) {
  const data = pickBy(
    { examId, entityId, type, pageNumber, pageSize },
    (v) => v !== ""
  );
  return httpApp.post("/api/admin/task/query?" + object2QueryString(data));
}

export async function importPaper({
  examId,
  processPaper,
  processAnswer,
  encryptMode = "auto",
  objectiveShuffle = "",
  optionShuffle = "",
  audioPlayCount = "",
  fileName,
  file,
}) {
  const form = new FormData();
  form.append("examId", examId);
  form.append("processPaper", processPaper);
  form.append("processAnswer", processAnswer);
  form.append("encryptMode", encryptMode);
  form.append("objectiveShuffle", objectiveShuffle);
  form.append("optionShuffle", optionShuffle);
  form.append("audioPlayCount", audioPlayCount);
  form.append("fileName", fileName);
  form.append("file", file);
  return httpApp.post("/api/admin/exam/paper/import", form, {
    headers: {
      "Content-Type": "multipart/form-data",
      md5: await getMd5FromBlob(file),
    },
  });
}

export async function importExamStudent({
  examId,
  fileName,
  file,
  onUploadProgress,
}) {
  const form = new FormData();
  form.append("examId", examId);
  form.append("fileName", fileName);
  form.append("file", file);
  return httpApp.post("/api/admin/examStudent/import", form, {
    headers: {
      "Content-Type": "multipart/form-data",
      md5: await getMd5FromBlob(file),
    },
    onUploadProgress(progressEvent) {
      let percent = 0;
      if (progressEvent.total > 0 && progressEvent.loaded) {
        percent = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(
          0
        );
      }
      onUploadProgress && onUploadProgress(percent);
    },
  });
}

export async function importInvigilator({ examId, fileName, file }) {
  const form = new FormData();
  form.append("examId", examId);
  form.append("fileName", fileName);
  form.append("file", file);
  return httpApp.post("/api/admin/invigilateUser/import", form, {
    headers: {
      "Content-Type": "multipart/form-data",
      md5: await getMd5FromBlob(file),
    },
  });
}

export async function exportInvigilate({ examId, roomCode, userId }) {
  const form = new FormData();
  form.append("examId", examId);
  form.append("roomCode", roomCode);
  form.append("userId", userId);
  return httpApp.post("/api/admin/invigilateUser/export", form);
}
