import { objTypeOf } from "@/plugins/utils";
import {
  waitExamTaskCount,
  stmmsWaitTaskCount,
  analysisWaitTaskCount,
  markWaitTaskCount,
  savePreviewLog,
} from "./api";

const state = {
  waitTask: {
    flow: 0,
    stmms: 0,
    analysis: 0,
    mark: 0,
  },
  waitTypes: [],
  // createExamAndPrintTask
  infoExamTask: {},
  infoExamTaskDetail: {},
  infoExamPrintPlan: {},
  infoPrintTask: {},
  // apply-task
  editType: "",
  examTask: {},
  curTaskApply: {},
  taskStatus: {},
  auditLogCache: { paper: {}, card: {} },
};

const mutations = {
  setWaitTask(state, waitTask) {
    state.waitTask = waitTask;
  },
  setWaitTypes(state, waitTypes) {
    state.waitTypes = waitTypes;
  },
  // createExamAndPrintTask
  updateTaskInfo(state, data) {
    Object.entries(data).forEach(([key, val]) => {
      if (objTypeOf(val) === "array") {
        state[key] = [...val];
      } else {
        state[key] = Object.assign({}, state[key], val);
      }
    });
  },
  resetTaskInfo(state) {
    state.infoExamTask = {};
    state.infoExamTaskDetail = {};
    state.infoExamPrintPlan = {};
    state.infoPrintTask = {};
  },
  // apply-task
  setTaskStatus(state, taskStatus) {
    state.taskStatus = taskStatus;
  },
  setEditType(state, editType) {
    state.editType = editType;
  },
  setExamTask(state, examTaskPartial) {
    state.examTask = Object.assign({}, state.examTask, examTaskPartial);
  },
  setCurTaskApply(state, curTaskApplyPartial) {
    state.curTaskApply = Object.assign(
      {},
      state.curTaskApply,
      curTaskApplyPartial
    );
  },
  setAuditLogCache(state, auditLogCache) {
    state.auditLogCache = auditLogCache;
  },
};

const actions = {
  async updateWaitTaskCount({ state, commit }) {
    const task = [
      {
        type: "flow",
        func: waitExamTaskCount,
      },
      {
        type: "stmms",
        func: stmmsWaitTaskCount,
      },
      {
        type: "analysis",
        func: analysisWaitTaskCount,
      },
      {
        type: "mark",
        func: markWaitTaskCount,
      },
    ];
    const taskList = task.filter((item) => state.waitTypes.includes(item.type));
    const countAll = taskList.map((item) => item.func());
    const counts = await Promise.all(countAll).catch(() => {});

    if (!counts) return;

    const waitTask = {};
    counts.forEach((count, index) => {
      waitTask[taskList[index].type] = count;
    });

    commit("setWaitTask", waitTask);
  },
  async addPreviewLog({ state, commit }, { attachment, type }) {
    if (!state.taskStatus.IS_AUDIT) return;
    const id = type === "paper" ? attachment.attachmentId : attachment.cardId;
    if (!Object.prototype.hasOwnProperty.call(state.auditLogCache[type], id))
      return;

    state.auditLogCache[type][id] = true;
    await savePreviewLog({
      examTaskId: state.curTaskApply.examTaskId,
      paperType: attachment.name,
      type,
    });
  },
};

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