import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import ApiConstant from "@/api/ApiConstant";
import { triggerHookSync } from "@mega-apps/utils";

Vue.use(Vuex);

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context("./modules", true, /\.js$/);

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
// eslint-disable-next-line
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
  const value = modulesFiles(modulePath);
  // eslint-disable-next-line
  modules[moduleName] = value.default;
  return modules;
}, {});

const store = () =>
  new Vuex.Store({
    modules,
    getters: {
      modules(state) {
        return (
          state.account.menus?.map((item) => {
            const { children, ...rest } = item;
            return { ...rest };
          }) || []
        );
      },
      menuData(state, getters) {
        return (
          (state.activatedModule &&
            getters["account/menuMap"].get &&
            getters["account/menuMap"].get(state.activatedModule)) ||
          []
        );
      },
      firstMenu(state, getters) {
        return getters.menuData.map((item) => {
          const { children, ...rest } = item;
          return { ...rest };
        });
      },
      subMenu(state, getters) {
        return (
          (state.activatedFirst &&
            getters["account/menuMap"].get &&
            getters["account/menuMap"].get(state.activatedFirst)) ||
          []
        );
      },
      headMenuData(state, getters) {
        const [data] = triggerHookSync("store:headMenuData", [state, getters]);
        if (data) return data;
        return [];
      },
      sideMenuData(state, getters) {
        const { menuData, subMenu } = getters;
        const { layout } = state.setting;
        return layout === "mix" ? subMenu : menuData;
      },
    },
    state: {
      adminAuthorityMark: "*", // 管理员权限标识
      activatedModule: undefined,
      activatedFirst: undefined,
      activatedSite: undefined, // 所在工厂
    },
    mutations: {
      setActivatedModule(state, activatedModule) {
        // eslint-disable-next-line no-param-reassign
        state.activatedModule = activatedModule;
      },
      setActivatedFirst(state, activatedFirst) {
        // eslint-disable-next-line no-param-reassign
        state.activatedFirst = activatedFirst;
      },
      setActivatedSite(state, activatedSite) {
        // eslint-disable-next-line no-param-reassign
        state.activatedSite = activatedSite;
      },
    },
    actions: {
      fetchSysInfoByToken(ctx, http) {
        const $axios = http || this.$axios || null;
        return new Promise((resolve, reject) => {
          if ($axios) {
            // 系统编码规则
            $axios
              .get(
                `${ApiConstant.PREFIX_CORE}/api/sys/code-rule/get-all-table-rule`
              )
              .then(({ data }) => {
                ctx.commit("app/SET_SYSTEM_CODE_RULE", data.data);
              });

            // 系统菜单 Client_Code：pc端传PC，pda端传PDA
            $axios
              .get(`${ApiConstant.PREFIX_CORE}/api/sys/menu/user-menu`, {
                headers: { Client_Code: "PC" },
              })
              .then(({ data }) => {
                if (data.code === 200) {
                  ctx.dispatch("account/getUserMenuInfo", data.data);
                  !data.data?.menus?.find(
                    (item) => item.id === ctx.state.activatedModule
                  ) &&
                    ctx.commit("setActivatedModule", data.data?.menus?.[0]?.id);
                  ctx.commit(
                    "setActivatedFirst",
                    ctx.getters.headMenuData?.[0]?.id
                  );
                  !ctx.state.auth?.user?.sitePermission?.find(
                    (item) => item.siteCode === ctx.state.activatedSite
                  ) &&
                    ctx.commit(
                      "setActivatedSite",
                      ctx.state.auth?.user?.sitePermission?.[0]?.siteCode
                    );
                  resolve();
                }
              })
              .catch(() => {
                reject();
              });
          } else {
            reject();
          }
        });
      },
    },
    plugins: [
      createPersistedState({
        key: "vuex",
        paths: ["app", "tagsView", "setting", "pagination", "account"],
        // eslint-disable-next-line
        reducer(state) {
          return {
            app: {
              locale: state.app.locale,
              systemConfig: state.app.systemConfig,
              systemCodeRule: state.app.systemCodeRule,
            },
            tagsView: {
              visitedViews: state.tagsView.visitedViews,
              cachedViews: state.tagsView.cachedViews,
            },
            pagination: {
              pageSize: state.pagination.pageSize,
            },
            account: {
              menus: state.account.menus,
              permissions: state.account.permissions,
              sitePermission: state.account.sitePermission,
              prevUserId: state.account.prevUserId,
              userId: state.account.userId,
              tenantId: state.account.tenantId,
              isReset: state.account.isReset,
            },
            activatedSite: state.activatedSite,
            activatedModule: state.activatedModule,
            activatedFirst: state.activatedFirst,
          };
        },
      }),
    ],
  });
export default store;
