// @ts-ignore
import { router } from '@router';
import { WorkflowServiceApi } from '@openapi/wf';
import { ActionTree, GetterTree, MutationTree } from 'vuex';

const wfApi = new WorkflowServiceApi();

interface State {
  waitTraceId: any[];
}

export const state: State = {
  waitTraceId: [],
};

export const getters: GetterTree<State, State> = {
  waitTraceId(state) {
    return state.waitTraceId;
  },
};

export const mutations: MutationTree<State> = {
  addWaitTraceId(state, waitTraceId) {
    state.waitTraceId.push(waitTraceId);
  },
  removeWaitTraceId(state, waitTraceId) {
    state.waitTraceId = state.waitTraceId.filter(
      (itemId) => itemId !== waitTraceId
    );
  },
};

export const actions: ActionTree<State, State> = {
  dispatchProcess(
    { commit, rootGetters },
    {
      data = {},
      processKey,
      redirectUrl = router.currentRoute.fullPath, // ? src/components/statements/index.ts
      userId, // ? src/components/registries/unloading_list.vue src/components/statements/index.ts
    } = {}
  ) {
    return new Promise((resolve, reject) => {
      const requestBody = {
        processKey,
        userId,
      };

      data.redirectUrl = data.redirectUrl || redirectUrl;
      data.readonlyFields = data.readonlyFields || [];

      wfApi
        .start({
          ...requestBody,
          data,
        })
        .then(({ data }) => {
          if (data.traceId) {
            commit('addWaitTraceId', data.traceId);
          }
          return resolve(data);
        })
        .catch((error) => {
          return reject(error);
        });
    });
  },
};
