import { Question } from "@/types";
import { store } from "@/store/store";
import { watch } from "vue";

const scrollToQuestionOfBoard = async (question: Question) => {
  const node = document.querySelector(
    `#bq-${question.mainNumber}-${question.subNumber}`
  );
  const questionNode = document.querySelector(
    `#q-${question.mainNumber}-${question.subNumber}`
  );
  if (!questionNode) {
    // 非多媒体阅卷
    node && node.scrollIntoView({ block: "center", behavior: "smooth" });
    return;
  }
  // console.log(node);
  // node && node.scrollIntoView({ behavior: "smooth" });
  // if (node) node.scrollBy({ top: -50 });
  // setTimeout(() => {
  //   if (node) node.parentElement?.scrollTo({ top: 50, left: 0 });
  //   // node && node.scrollTop = 50//node.scrollIntoView({ behavior: "auto", block: "center" });
  //   if(node.)
  // }, 1500);
  async function checkIfEleMoving(ele: Element) {
    const { top: oldTop } = ele.getBoundingClientRect();
    await new Promise((res) => setTimeout(res, 200));
    // console.log(ele.getBoundingClientRect().top, oldTop);
    return ele.getBoundingClientRect().top - oldTop !== 0;
  }
  if (questionNode) {
    let isMoving = await checkIfEleMoving(questionNode);
    while (isMoving) {
      isMoving = await checkIfEleMoving(questionNode);
    }
    node && node.scrollIntoView({ block: "center", behavior: "smooth" });
  }
};

export function chooseQuestion(question: Question) {
  store.currentQuestion = question;
  // FIXME: maybe should be an async function, temp fix for eslint
  void scrollToQuestionOfBoard(question);
}

/** chooseQuestion 当currentTask改变是，自动选择第一题 */
export function autoChooseFirstQuestion() {
  watch(
    () => store.currentTask,
    () => {
      // FIXed ME: 此时取到的还是score:null，但是 chooseQuestion之后就变成了score:0
      const firstQuestion = store.currentTask?.questionList[0];
      if (firstQuestion) {
        chooseQuestion(firstQuestion);
      }
    }
  );

  return { chooseQuestion };
}
