import {
  ref,
  watch,
  onBeforeMount,
  Ref,
  computed,
  nextTick,
  ComputedRef,
} from "vue";
import * as API from "@/api";
import { Howl, Howler } from "howler";
import { useRoute } from "vue-router";

//答题模式切换
export function useTopicMode() {
  const answerTypeList = ref([
    { name: "顺序练习" },
    { name: "随机练习" },
    { name: "背题模式" },
  ]);
  const currentType = ref(0);
  const typeParams = ref({
    order: true, //顺序练习
    answerShow: false, //背题模式
  });
  watch(currentType, (currentVal) => {
    switch (currentVal) {
      case 0:
        typeParams.value.order = true;
        typeParams.value.answerShow = false;
        break;
      case 1:
        typeParams.value.order = false;
        typeParams.value.answerShow = false;
        break;
      case 2:
        typeParams.value.order = true;
        typeParams.value.answerShow = true;
        break;
    }
  });
  return {
    answerTypeList,
    currentType,
    typeParams,
  };
}

//语音设置
export function useAudioSet(currentSubject: ComputedRef<any>) {
  const aotuPlayFlag = ref(false);

  let sound: Howl;
  /**
   * 播放音频
   * @param audioUrl
   */
  const audioPlay = (audioUrl: string | string[]) => {
    audioPause();
    sound = new Howl({
      src: audioUrl,
    });
    sound.once("load", function () {
      sound.play();
    });
    if (typeof audioUrl === "object") {
      sound.once("end", () => {
        sound = new Howl({
          src: audioUrl[1],
        });
        sound.once("load", function () {
          sound.play();
        });
      });
    }
  };

  /**
   * 读题
   */
  const subjectAudioPlay = (
    type: "读题" | "读官方解释" | "读技巧解释" | "读题+答案"
  ) => {
    switch (type) {
      case "读题":
        audioPlay(currentSubject.value.issuemp3);
        break;
      case "读官方解释":
        audioPlay(currentSubject.value.explainjsmp3);
        break;
      case "读技巧解释":
        audioPlay(currentSubject.value.explainMp3);
        break;
      case "读题+答案":
        audioPlay([
          currentSubject.value.issuemp3,
          currentSubject.value.answermp3,
        ]);
        break;
      default:
        break;
    }
  };

  /**
   * 停止播放
   */
  const audioPause = () => {
    sound && sound.pause();
  };

  //音频模块end
  const aotuPlaySet = () => {
    aotuPlayFlag.value = !aotuPlayFlag.value;
    aotuPlayFlag.value ? subjectAudioPlay("读题") : audioPause();
  };

  //自动读题
  watch(currentSubject, () => {
    if (aotuPlayFlag.value) subjectAudioPlay("读题"); //自动读题
  });

  return {
    aotuPlayFlag,
    aotuPlaySet,
    subjectAudioPlay,
  };
}

const useSubjectList = () => {
  const subjectList = ref<any[]>([]); //题目列表
  const subjectTotal = ref(0); //题目总数
  const pageNum = ref(1); //当前请求页码
  const pageSize = ref(100); //当前请求每页数据
  const query = useRoute().query; //路由query参数
  onBeforeMount(async () => {
    const res = await API.getTopicList({
      ...query,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      isRand: true,
    });
    subjectList.value = res.list;
    subjectTotal.value = 100;
  });
  //加载下一页数据
  const loadNewSubject = async () => {
    if (subjectList.value.length == subjectTotal.value) return;
    pageNum.value++;
    const res = await API.getTopicList({
      ...query,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
    subjectList.value = subjectList.value.concat(res.list);
  };
  const currentSubjectIndex = ref(0); //当前题目下标
  //当前题目内容
  const currentSubject = computed(() => {
    return subjectList.value[currentSubjectIndex.value];
  });
  return {
    subjectList,
    subjectTotal,
    loadNewSubject,
    currentSubject,
    currentSubjectIndex,
  };
};

const useSubjectCheck = (nextSubject: () => Promise<void>) => {
  const trueNum = ref(0); //正确数量
  const falseNum = ref(0); //错误数量
  const isJumpNext = ref(false); //答对跳转下一题

  /**
   * 选择答案后进行校验
   */
  const userAnswerChange = (currentSubject: any) => {
    try {
      if (!currentSubject.userAnswer) return;

      currentSubject.optsBack = currentSubject.opts.map((val: String) => {
        let status;
        if (currentSubject.answer.includes(val)) {
          status = 1;
        } else {
          status = 0;
        }
        if (currentSubject.userAnswer.includes(val)) {
          status += 2;
        }
        return { opt: val, status };
      });
      if (
        JSON.stringify(currentSubject.answer) ==
        JSON.stringify(currentSubject.userAnswer)
      ) {
        console.log("答案正确");
        currentSubject.isTrue = true;
        trueNum.value++;
        if (isJumpNext.value) {
          nextTick(() => {
            nextSubject();
          });
        }
      } else {
        console.log("错误");
        currentSubject.isTrue = false;
        falseNum.value++;
      }
    } catch (error) {
      console.log(error);
    }
  };

  return {
    trueNum,
    falseNum,
    isJumpNext,
    userAnswerChange,
  };
};

export const useSubjectShowLogic = () => {
  const {
    subjectList,
    subjectTotal,
    loadNewSubject,
    currentSubject,
    currentSubjectIndex,
  } = useSubjectList(); //获取题目列表

  const nextBtnState = ref(true); //下一题数据请求锁

  /**
   * 展示下一题
   */
  const nextSubject = async () => {
    if (currentSubjectIndex.value < subjectList.value.length - 1) {
      currentSubjectIndex.value++;
    }
  };
  /**
   * 展示上一题
   */
  const lastSubject = () => {
    if (currentSubjectIndex.value > 0) {
      currentSubjectIndex.value--;
    }
  };

  const { trueNum, falseNum, isJumpNext, userAnswerChange } =
    useSubjectCheck(nextSubject);

  return {
    currentSubject,
    currentSubjectIndex,
    subjectTotal,
    nextSubject,
    lastSubject,
    trueNum,
    falseNum,
    isJumpNext,
    subjectList,
    userAnswerChange,
  };
};
