/*
 * @Author: your name
 * @Date: 2020-11-26 16:48:54
 * @LastEditTime: 2021-06-01 11:07:46
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \precise_delivery_distribution_front\src\store\modules\app\actions.ts
 */
import { ActionTree } from "vuex";
import { Actions, ActionType, MutationType, State } from "./_type";
import { RootState } from "@/store";
import asyncRoutes from "@/router/async";
import { filterRoutesByRoles } from "@/helper/permission";
import { formatSelectOptions } from "@/helper/index";

import { doLogin, getOfficialSimpleAccount, getPlatforms } from "@/api";

type userData = {
  account: string;
  passwd: string;
};

const actions: ActionTree<State, RootState> & Actions = {
  [ActionType.generatorRoutes]({ commit }, roles) {
    return new Promise(async (resolve) => {
      let resultRoutes = filterRoutesByRoles(asyncRoutes, roles) || [];
      await commit(MutationType.setRoutes, resultRoutes);
      resolve(resultRoutes);
    });
  },
  [ActionType.getUserRoles]({ commit }) {
    return new Promise(async (resolve) => {
      const roles = ["admin"];
      await commit(MutationType.setRoles, roles);
      resolve(roles);
    });
  },
  async [ActionType.doLogin]({ commit }, user: userData) {
    try {
      const { data } = await doLogin<userData>(user);
      commit(MutationType.setUser, data);
    } catch (e) {
      console.log("error", e);
    }
  },
  async [ActionType.doSaveOfficial]({ commit }) {
    try {
      const { data } = await getOfficialSimpleAccount();
      const storeOfficials = formatSelectOptions<number>(data, "name", "id");
      commit(MutationType.setOfficial, storeOfficials);
    } catch (e) {
      console.log("error", e);
    }
  },
  async [ActionType.doSavePlatforms]({ commit }) {
    try {
      const { data } = await getPlatforms();
      const storePlatforms = formatSelectOptions<string>(data, "desc", "name");
      commit(MutationType.setPlatforms, storePlatforms);
    } catch (e) {
      console.log("error", e);
    }
  },
};

export default actions;
