import { defineStore } from 'pinia';
import { UserMenuItem } from '@/api/types/user';
import { getUserPrivilegeMenu } from '@/api/user';
import { AppState, AppMenuItem } from './types';

// import { sysAdminMenus as menus } from './menuData';
import { adminMenus as menus } from './menuData';

function getMenu(privilegeData: UserMenuItem[]): {
  menuList: AppMenuItem[];
  validRoutes: string[];
} {
  const map = new Map<string, AppMenuItem>();
  const menuList: AppMenuItem[] = [];
  const validRoutes: string[] = [];

  // 创建节点映射
  privilegeData.forEach((item) => {
    const node: AppMenuItem = { ...item, url: item.code, children: [] };
    map.set(item.code, node);
    validRoutes.push(item.code);
  });

  // 构建树形结构
  privilegeData.forEach((item) => {
    const node = map.get(item.code);
    if (!node) return;
    if (item.parentCode && map.has(item.parentCode)) {
      map.get(item.parentCode).children.push(node);
    } else {
      menuList.push(node);
    }
  });

  return { menuList, validRoutes };
}

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

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

  actions: {
    resetInfo() {
      this.$reset();
    },
    setInfo(partial: Partial<AppState>) {
      this.$patch(partial);
    },
    fetchLocalMenu() {
      const userMenus = menus;
      const { menuList, validRoutes } = getMenu(userMenus);
      this.appMenus = menuList;
      this.validRoutes = validRoutes;
    },
    async fetchServerMenu() {
      const userMenus = await getUserPrivilegeMenu();
      const { menuList, validRoutes } = getMenu(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 };
    },
    getSubMenuFirstRouter(subMenuUrl: string) {
      let firstRouteName = subMenuUrl;
      let subMenu = this.appMenus.find((item) => item.url === subMenuUrl);

      while (subMenu && subMenu.children?.length) {
        firstRouteName = subMenu.children?.[0].url ?? '';
        subMenu = subMenu.children?.[0];
      }

      return { name: firstRouteName };
    },
    checkCurRouteInSubMenu(subMenuUrl: string, routeName: string) {
      const subMenu = this.appMenus.find((item) => item.url === subMenuUrl);
      if (!subMenu) return false;
      return subMenu.children?.some((item) => item.url === routeName);
    },
    toggleDevice(device: string) {
      this.device = device;
    },
  },
  persist: {
    storage: sessionStorage,
  },
});

export default useAppStore;
