import {
  invigilateCount,
  invigilationWarningCount,
  reexamPendingCount,
  getLiveDomains,
} from "@/api/invigilation";

const state = {
  navTips: {
    RealtimeMonitoring: {
      val: "",
      classes: "nav-item-tips-popover",
    },
    WarningManage: {
      val: "",
      classes: "nav-item-tips-num",
    },
    ReexamPending: {
      val: "",
      classes: "nav-item-tips-num",
    },
  },
  detailIds: [],
  liveDomains: [],
  selectedExamId: null,
};

const mutations = {
  setRealtimeMonitoring(state, val) {
    state.navTips.RealtimeMonitoring.val = val ? "考试" : null;
  },
  setWarningManage(state, val) {
    state.navTips.WarningManage.val = val;
  },
  setReexamPending(state, val) {
    state.navTips.ReexamPending.val = val;
  },
  setDetailIds(state, detailIds) {
    state.detailIds = detailIds;
  },
  setLiveDomains(state, liveDomains) {
    state.liveDomains = liveDomains;
  },
  setSelectedExamId(state, selectedExamId) {
    state.selectedExamId = selectedExamId;
  },
};

const actions = {
  async fetchRealtimeMonitoringCount({ commit }, datas) {
    const res = await invigilateCount(datas);
    commit("setRealtimeMonitoring", res.data.data.length);
  },
  async fetchWarningManageCount({ commit }, datas) {
    const res = await invigilationWarningCount(datas);
    commit("setWarningManage", res.data.data.count);
  },
  async fetchReexamPendingCount({ commit }, datas) {
    const res = await reexamPendingCount(datas);
    commit("setReexamPending", res.data.data.count);
  },
  async updateDetailIds({ commit }, { filterData, fetchFunc }) {
    const res = await fetchFunc({
      ...filterData,
      pageNumber: 1,
      pageSize: 1000,
    });
    const ids = res.data.data.records.map((item) => item.examRecordId);
    commit("setDetailIds", [...new Set(ids)]);
  },
  async fetchLiveDomains({ commit }) {
    const res = await getLiveDomains();
    commit("setLiveDomains", res.data.data || []);
  },
  updateSelectedExamId(
    { commit },
    { exams, selectedExamId, defaultExamId = null }
  ) {
    if (!exams.length) return;
    const firstExamId = exams[0].id;
    const selectedExam = exams.find((item) => item.id === selectedExamId);
    const defaultExam = exams.find((item) => item.id === defaultExamId);
    const newSelectedExamId =
      (defaultExam && defaultExam.id) ||
      (selectedExam && selectedExam.id) ||
      firstExamId;
    commit("setSelectedExamId", newSelectedExamId);
  },
};

export default { namespaced: true, state, mutations, actions };
