import { defineStore } from "pinia";
import { AudioPlayTime, Store } from "@/types/student-client";

const initState: Store = {
  user: {} as Store["user"],
  menus: {} as Store["menus"],
  appDownload: {} as Store["appDownload"],
  exam: {} as Store["exam"],
  endedExamList: {} as Store["endedExamList"],
  examList: {} as Store["examList"],
  homeworkList: {} as Store["homeworkList"],
  practiceList: {} as Store["practiceList"],
  siteMessage: {} as Store["siteMessage"],
  siteMessagesTimeStamp: Date.now(),
  globalMaskCount: 0,
  QECSConfig: {} as Store["QECSConfig"],
  network: {} as Store["network"],
  sysTime: {} as Store["sysTime"],
} as Store;

const resetState: Omit<
  Store,
  "globalMaskCount" | "network" | "sysTime" | "QECSConfig" | "camera"
> = {
  user: {} as Store["user"],
  menus: {} as Store["menus"],
  appDownload: {} as Store["appDownload"],
  exam: {} as Store["exam"],
  endedExamList: {} as Store["endedExamList"],
  examList: {} as Store["examList"],
  homeworkList: {} as Store["homeworkList"],
  practiceList: {} as Store["practiceList"],
  siteMessage: {} as Store["siteMessage"],
  siteMessagesTimeStamp: Date.now(),
};

export function resetStore() {
  Object.assign(store.$state, resetState);
}

export const useStore = defineStore("ecs", {
  state: () => initState,
  getters: {
    /** 当前是否有globalMask */
    hasGlobalMask(): boolean {
      return store.globalMaskCount > 0;
    },
    /** 得到学生端正确的当前时间，考虑电脑的时钟误差 */
    getTimeStamp(): number {
      return Date.now() + store.sysTime.difference;
    },
    /** 练习过程中是否显示答案 */
    examShouldShowAnswer(): boolean {
      return store.exam.practiceType === "IN_PRACTICE";
    },
  },
  actions: {
    /** 增加当前的globalMaskCount */
    increaseGlobalMaskCount(byWho: string) {
      store.globalMaskCount++;
      console.debug(byWho, "increaseGlobalMaskCount", store.globalMaskCount);
    },
    /** 减少当前的globalMaskCount */
    decreaseGlobalMaskCount(byWho: string) {
      store.globalMaskCount--;
      console.debug(byWho, "decreaseGlobalMaskCount", store.globalMaskCount);
      if (store.globalMaskCount < 0) {
        console.error("store.globalMaskCount < 0");
        store.globalMaskCount = 0;
      }
    },
    /** 更新本机时间与服务器时间的差异 */
    updateTimeDifference(timeDiff: number) {
      store.sysTime.difference = timeDiff;
    },
    updateSiteMessagesTimeStamp() {
      store.siteMessagesTimeStamp = Date.now();
    },
    setQuestionQrCodeScanned(payload: { order: number }) {
      store.exam.questionQrCodeScanned = payload;
    },
    setQuestionFileAnswerUrl(payload: {
      order: number;
      fileUrl: string;
      transferFileType: string;
    }) {
      // 先清理之前保存过的记录
      store.exam.questionAnswerFileUrl =
        store.exam.questionAnswerFileUrl.filter((v) => !v.saved);
      const oldIndex = store.exam.questionAnswerFileUrl.findIndex(
        (v) => v.order === payload.order
      );
      if (oldIndex === -1) {
        store.exam.questionAnswerFileUrl.push(payload);
      } else {
        store.exam.questionAnswerFileUrl[oldIndex] = payload;
      }
    },
    /** 更新试题 */
    updateExamQuestion({
      order,
      studentAnswer,
      isStarred,
      audioPlayTimes,
      gotQuestionContent,
    }: {
      order: number;
      studentAnswer?: string;
      isStarred?: boolean;
      audioPlayTimes?: AudioPlayTime[];
      gotQuestionContent?: boolean;
    }) {
      store.exam.examQuestionList.map((eq) => {
        if (eq.order == order) {
          const upEq: typeof eq = {} as any;
          // 仅在设置gotQuestionContent时，不更新dirty
          if (gotQuestionContent === undefined) {
            upEq.dirty = true;
          } else {
            upEq.gotQuestionContent = gotQuestionContent;
          }
          if (studentAnswer !== undefined) {
            upEq.studentAnswer = studentAnswer;
          }

          if (audioPlayTimes !== undefined) {
            upEq.audioPlayTimes = audioPlayTimes;
          }
          if (isStarred !== undefined) {
            upEq.isStarred = isStarred;
          }
          return Object.assign(eq, upEq);
        }
        return eq;
      });
    },
    /** 更新音频播放次数 */
    updateQuestionAudioPlayTimes(payload: string) {
      let alreayHas = false;
      const allAudioPlayTimes = store.exam.allAudioPlayTimes.map((audio) => {
        if (audio.audioName === payload) {
          alreayHas = true;
          const times = audio.times + 1;
          return { audioName: payload, times: times };
        }
        return audio;
      });

      store.exam.allAudioPlayTimes = allAudioPlayTimes;

      if (!alreayHas) {
        allAudioPlayTimes.push({ audioName: payload, times: 1 });
      }
      store.exam.examQuestionList[0].audioPlayTimes = allAudioPlayTimes;
      store.exam.examQuestionList[0].dirty = true;
    },
  },
});

type GlobalStore = ReturnType<typeof useStore>;

export let store: GlobalStore;

export function setStore(s: GlobalStore) {
  store = s;
  storeListener();
}
function storeListener() {
  store?.$subscribe((_mutation, state) => {
    sessionStorage.setItem(
      "ecs",
      JSON.stringify(
        Object.assign(JSON.parse(JSON.stringify(state)), { globalMaskCount: 0 })
      )
    );
  });
  const cachedState = JSON.parse(sessionStorage.getItem("ecs") || "0");
  cachedState && (store.$state = cachedState);
}
