import { defineStore } from "pinia";
import router from "@/router";
import { adminLogout, heatBeatApi } from "@/ap/system";
import HeatBeatWorker from "@/utils/heatbeat.worker?worker";

const heatBeatWorker = new HeatBeatWorker();
interface RecogFillSetType {
  fillColor: string;
  fillShow: boolean;
  unfillColor: string;
  unfillShow: boolean;
  borderWidth: number;
}

export const useUserStore = defineStore<
  "user",
  {
    heatBeatWorker: Worker | null;
    curExam: Exam | null;
    imageCheckLoopTime: number;
    userInfo: any;
    recogFillSet: RecogFillSetType;
  },
  any,
  any
>("user", {
  persist: [
    {
      storage: sessionStorage,
      paths: ["userInfo"],
    },
    {
      storage: localStorage,
      paths: ["curExam", "imageCheckLoopTime", "recogFillSet"],
    },
  ],
  state: () => ({
    heatBeatWorker: null,
    heatBeatIsActive: false,
    userInfo: null,
    curExam: null,
    imageCheckLoopTime: 0,
    recogFillSet: {
      fillColor: "#f53f3f ",
      fillShow: true,
      unfillColor: "#165DFF",
      unfillShow: false,
      borderWidth: 2,
    },
  }),
  actions: {
    initHeatBeat() {
      this.heatBeatWorker = new HeatBeatWorker();
      this.heatBeatWorker.onmessage = (e: any) => {
        const data = e.data;
        if (typeof e.data === "boolean") {
          this.heatBeatIsActive = !!data;
        } else if (e.data === "") {
          heatBeatApi();
        }
      };
    },
    startHeatBeat() {
      this.heatBeatWorker.postMessage(true);
    },
    setUserInfo(info: any) {
      this.userInfo = info;
      if (!info) {
        this.heatBeatWorker.postMessage(false);
      } else {
        this.heatBeatWorker.postMessage(true);
      }
    },
    setCurExam(exam: Exam) {
      this.curExam = exam;
    },
    setImageCheckLoopTime(imageCheckLoopTime: number) {
      this.imageCheckLoopTime = imageCheckLoopTime;
    },
    setRecogFillSet(recogFillSet: RecogFillSetType) {
      this.recogFillSet = recogFillSet;
    },
    setState(data: any) {
      this.$patch(data);
    },
    resetUserInfo() {
      this.$reset();
    },
    async logout() {
      await adminLogout();
      this.setUserInfo(null);
      router.push({ name: "Login" });
      window.electronApi?.changeWinSize("small");
    },
  },
});
