import { defineStore } from 'pinia';
import { omit } from 'lodash';
import { menus } from './menuData';

import { AppState, AppMenuItem, UserMenuItem } from './types';
import { RoleType } from '../../../constants/enumerate';

function transformMenu(list: typeof menus): UserMenuItem[] {
  return list.map((menu) => omit(menu, ['roles']));
}

function getMenu(privilegeData: UserMenuItem[]): {
  menuList: AppMenuItem[];
  validRoutes: string[];
} {
  const getChildren = (id: number) => {
    return privilegeData
      .filter((item) => item.parentId === id)
      .map((item) => {
        const nitem: AppMenuItem = { ...item, children: [] };
        return nitem;
      });
  };
  let menuList = getChildren(-1);
  const validRoutes: string[] = [];
  const toTree = (data: AppMenuItem[]) => {
    data.forEach((menu) => {
      const children = getChildren(menu.id);
      if (children.length) {
        menu.children = children;
        toTree(menu.children);
      } else {
        validRoutes.push(menu.url);
      }
    });
  };
  toTree(menuList);

  menuList = menuList.filter((item) => item.children && item.children.length);

  return { menuList, validRoutes };
}

const useAppStore = defineStore('app', {
  state: (): AppState => ({
    version: '',
    appMenus: [],
    validRoutes: [],
    breadcrumbs: [],
    device: 'desktop',
  }),

  getters: {
    appInfo(state: AppState): AppState {
      return { ...state };
    },
  },

  actions: {
    resetInfo() {
      this.$reset();
    },
    setInfo(partial: Partial<AppState>) {
      this.$patch(partial);
    },
    fetchServerMenu(type: RoleType | null) {
      const userMenus = type
        ? menus.filter((menu) => !menu.roles || menu.roles.includes(type))
        : ([] as typeof menus);
      // // 开发时不管权限
      // console.log(type);
      // const userMenus = menus;
      const { menuList, validRoutes } = getMenu(transformMenu(userMenus));
      this.appMenus = menuList;
      this.validRoutes = validRoutes;
    },
    getMenuFirstRouter() {
      let firstRouteName = '';
      let menu = this.appMenus[0];

      while (menu) {
        firstRouteName = menu.url;
        menu = menu.children && menu.children[0];
      }

      return { name: firstRouteName };
    },
    toggleDevice(device: string) {
      this.device = device;
    },
  },
  persist: {
    storage: sessionStorage,
  },
});

export default useAppStore;
