import { httpApp } from "@/plugins/axiosApp";
import { store } from "@/store/store";
import { AudioPlayTime } from "@/types/student-client";
import { doEnc } from "@/utils/encDec";
import { MD5 } from "@/utils/md5";
import { getKey } from "@/utils/utils";
import { onUnmounted, getCurrentInstance } from "vue";
import axios from "axios";

function resetExamQuestionDirty() {
  store.exam.examQuestionList = store.exam.examQuestionList.map((eq) => {
    return Object.assign({}, eq, { dirty: false });
  });
}

type Answer = {
  order: number;
  studentAnswer: string;
  audioPlayTimes: AudioPlayTime[];
  isStarred: boolean;
};

export const useAnswerQuestions = () => {
  let abortcontroller: AbortController | null;

  function cancel() {
    if (abortcontroller && !abortcontroller.signal.aborted) {
      abortcontroller.abort();
      abortcontroller = null;
    }
  }
  if(getCurrentInstance()){
    onUnmounted(cancel);
  }
  return async function answerAllQuestions(
    ignoreDirty?: boolean
  ): Promise<boolean> {
    // 根据线上错误排查：可能已经退出页面了，没有数据了
    if (!store.exam.examQuestionList) return false;

    const answers: Answer[] = store.exam.examQuestionList
      .filter((eq) => (ignoreDirty ? true : eq.dirty))
      .filter((eq) => eq.gotQuestionContent)
      .map((eq) => {
        return Object.assign(
          {
            order: eq.order,
            studentAnswer: eq.studentAnswer,
          },
          eq.audioPlayTimes && {
            audioPlayTimes: JSON.stringify(eq.audioPlayTimes) as any,
          },
          eq.isStarred && { isStarred: eq.isStarred }
        ) as Answer;
      });
    if (answers.length > 0) {
      const timestamp = Date.now();
      const rawStr = MD5(JSON.stringify(answers));

      const key = getKey(timestamp);

      const sign = doEnc(rawStr, key);

      cancel();

      abortcontroller = new AbortController();

      try {
        await httpApp.post(
          "/api/ecs_oe_student/examControl/submitQuestionAnswer",
          { answers: JSON.stringify(answers), sign },
          {
            "axios-retry": { retries: 4 },
            noErrorMessage: true,
            headers: { timestamp },
            signal: abortcontroller.signal,
          }
        );
        resetExamQuestionDirty();
      } catch (error) {
        if (!axios.isCancel(error)) {
          logger({
            cnl: ["server", "local"],
            pgu: "AUTO",
            act: "提交答案失败",
            possibleError: error,
          });
          $message.error("提交答案失败");
        }
        return false;
      }
    }
    // 提交成功，返回true，供最后提交时判断。自动提交失败，不暂停。
    return true;
  };
};
