import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getAuthMenuListApi } from "@/api/modules/login";
import { getUserInfoApi } from "@/api/modules/common";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { patchRoutes } from "@/routers/modules/staticRouter";
import { useUserStore } from "./user";

export const useAuthStore = defineStore({
  id: "acupuncture-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: [],
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: ""
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList.concat(getPatchRoutes())),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList.concat(getPatchRoutes()))
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      const { data } = await getUserInfoApi();
      this.authButtonList = data.permissions;
      const userStore = useUserStore();
      userStore.setUserInfo({ name: data.user?.nickName });
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = await getAuthMenuListApi();
      data.forEach;
      const index = data.findIndex(item => item.path === "/");
      if (index > -1) {
        data.splice(index, 1, ...((data[index].children as Menu.MenuOptions[]) || []));
      }
      this.authMenuList = ruoyiMenuAdapter(data);
      console.log(111, this.authMenuList);
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});

function ruoyiMenuAdapter(menuList: any) {
  return menuList.map((menu: any) => {
    // 根菜单， ruoyi接口多返回了一层
    if (menu.path === "/" && menu.children?.length === 1) {
      menu = menu.children[0];
    }
    const clone: Menu.MenuOptions = {
      path: menu.path,
      name: menu.name,
      meta: {
        icon: menu.meta.icon,
        title: menu.meta.title,
        isLink: menu.meta.link,
        isHide: menu.hidden,
        isFull: false,
        isAffix: false,
        isKeepAlive: !menu.meta.noCache
      }
    };
    if (menu.children?.length > 0) {
      clone.children = ruoyiMenuAdapter(menu.children);
      clone.redirect = menu.children[0].path;
    } else {
      clone.component = menu.component;
    }
    return clone;
  });
}

// 基于用户权限
function getPatchRoutes(): Menu.MenuOptions[] {
  return patchRoutes.filter(item => {
    if (!item.permissions) return true;
    const { BUTTONS } = useAuthButtons({ hasAuth: item.permissions });
    return BUTTONS.value.hasAuth;
  });
}
