import { waitExamTaskCount, stmmsTaskCount, analysisTaskCount } from "./api";
import { calcSum } from "@/plugins/utils";

const state = {
  waitTaskCount: 0,
  waitTask: {
    flow: 0,
    stmms: 0,
    analysis: 0
  },
  // createExamAndPrintTask
  infoExamTask: {},
  infoExamTaskDetail: {},
  infoExamPrintPlan: {},
  infoPrintTask: {}
};

const mutations = {
  setWaitTaskCount(state, waitTaskCount) {
    state.waitTaskCount = waitTaskCount;
  },
  setWaitTask(state, waitTask) {
    state.waitTask = waitTask;
  },
  updateWaitTask(state, data) {
    const waitTask = Object.assign({}, state.waitTask, data);
    state.waitTask = waitTask;
    const count = calcSum(Object.values(state.waitTask));
    state.waitTaskCount = count;
  },
  // createExamAndPrintTask
  updateTaskInfo(state, data) {
    Object.entries(data).forEach(([key, val]) => {
      state[key] = Object.assign({}, state[key], val);
    });
  },
  resetTaskInfo(state) {
    state.infoExamTask = {};
    state.infoExamTaskDetail = {};
    state.infoExamPrintPlan = {};
    state.infoPrintTask = {};
  }
};

const actions = {
  async updateWaitTaskCount({ commit }) {
    const task = [
      {
        type: "flow",
        func: waitExamTaskCount
      },
      {
        type: "stmms",
        func: stmmsTaskCount
      },
      {
        type: "analysis",
        func: analysisTaskCount
      }
    ];
    let countAll = task.map(item => item.func());
    const counts = await Promise.all(countAll).catch(() => {});

    if (!counts) return;

    let waitTask = {};
    counts.forEach((count, index) => {
      waitTask[task[index].type] = count;
    });
    commit("setWaitTask", waitTask);

    const count = calcSum(counts);
    commit("setWaitTaskCount", count || 0);
  }
};

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