import { defineStore } from "pinia";
import { StudentPage } from "@/views/DataCheck/types";
import { ImageType } from "@/constants/enumerate";
import {
  DataCheckListItem,
  DataCheckOmrFieldEditParams,
} from "@/ap/types/dataCheck";
import { dataCheckOmrFieldEdit } from "@/ap/dataCheck";

interface DataCheckState {
  imageType: ImageType;
  curPage: StudentPage | null;
  curPageIndex: number;
  curStudent: DataCheckListItem | null;
}

type UpdateFieldParams = Pick<DataCheckOmrFieldEditParams, "field" | "value">;

interface UpdateSheetData {
  paperIndex: number;
  paperId?: number;
  pageIndex: number;
  uri: string;
}
interface UpdateSliceData extends UpdateSheetData {
  index: number;
}

export const useDataCheckStore = defineStore("dataCheck", {
  state: (): DataCheckState => ({
    imageType: "ORIGIN",
    curPage: null,
    curPageIndex: -1,
    curStudent: null,
  }),

  getters: {
    dataInfo(state: DataCheckState): DataCheckState {
      return { ...state };
    },
  },

  actions: {
    setInfo(partial: Partial<DataCheckState>) {
      this.$patch(partial);
    },
    resetInfo() {
      this.$reset();
    },
    async updateField(data: UpdateFieldParams) {
      if (!this.curPage || !this.curStudent) return;

      const params = {
        examId: this.curPage.examId,
        examNumber: this.curStudent.examNumber,
        paperNumber: this.curPage.paperNumber,
        pageIndex: this.curPage.pageIndex,
        subjectCode: this.curStudent.subjectCode,
        ...data,
      };
      await dataCheckOmrFieldEdit(params).catch(() => {});
    },
    modifySliceUri(data: UpdateSliceData) {
      if (!this.curStudent) return;
      const { uri, pageIndex, index, paperIndex } = data;
      this.curStudent.papers[paperIndex].pages[pageIndex].sliceUri[index] = uri;
    },
    modifySheetUri(data: UpdateSheetData) {
      if (!this.curStudent) return;
      const { uri, pageIndex, paperIndex } = data;
      this.curStudent.papers[paperIndex].pages[pageIndex].sheetUri = uri;
    },
  },
  persist: {
    storage: sessionStorage,
  },
});
