import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getAuthButtonListApi, getAuthMenuListApi } from "@/api/modules/login";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList, localGet } from "@/utils";
import { usePermission } from "@/utils/permission";
export const useAuthStore = defineStore({
  id: "geeker-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),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      const { data } = await getAuthButtonListApi();
      this.authButtonList = data;
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = (await getAuthMenuListApi()) as any;

      const hasPermission = await usePermission();
      const hideMenuNames = ["storeDecoration", "financialManagement", "licenseManagement", "dynamicManagement"];

      // 获取用户信息和 businessSection（经营板块）、mealsFlag（是否提供餐食）、storeId、storeTickets
      const userInfo = localGet("geeker-user")?.userInfo || {};
      const businessSection = Number(userInfo.businessSection || localGet("businessSection") || 0);
      const mealsFlag = Number(userInfo.mealsFlag || localGet("mealsFlag") || 0);
      const storeId = userInfo.storeId ?? localGet("createdId");
      const storeTickets = Number(localGet("storeTickets") || 0);

      // 递归处理菜单的显示/隐藏状态
      const processMenus = (menuList: any[]) => {
        menuList.forEach(menu => {
          // 根据菜单名称判断是否需要处理
          if (menu.name && hideMenuNames.includes(menu.name)) {
            if (!hasPermission) {
              // 如果没有权限，隐藏菜单
              menu.meta.isHide = true;
            } else {
              // 如果有权限，确保菜单显示（移除 isHide 或设置为 false）
              if (menu.meta) {
                menu.meta.isHide = false;
              } else {
                menu.meta = { isHide: false };
              }
            }
          }

          // 根据 businessSection 判断菜单显示
          if (menu.meta && menu.meta.title) {
            switch (menu.meta.title) {
              case "菜单管理":
                // 只在特色美食(1) 时显示菜单管理
                menu.meta.isHide = businessSection !== 1;
                break;
              case "酒单管理":
                // 只在酒吧(2) 时显示酒单管理
                menu.meta.isHide = businessSection !== 2;
                break;
              case "设施与服务":
                // 特色美食(1) 不显示设施与服务
                menu.meta.isHide = businessSection == 1;
                break;
              case "门店基础信息":
              case "门店头图":
              case "官方相册":
              case "收款账号":
                // 所有业务类型都显示
                menu.meta.isHide = false;
                break;
              case "人员配置":
                menu.meta.isHide = !storeId;
                break;
              case "食品经营许可证":
                // 特色美食(1) 和 酒吧(2)：正常显示
                // KTV(3)、洗浴汗蒸(4)、按摩足疗(5)、丽人美发(6)、运动健身(7)：仅提供餐食时显示
                if ([1, 2].includes(businessSection)) {
                  // 酒吧和特色美食无条件显示
                  menu.meta.isHide = false;
                } else if ([3, 4, 5, 6, 7].includes(businessSection)) {
                  // KTV等业态需要提供餐食才显示
                  menu.meta.isHide = mealsFlag !== 1;
                }
                break;
              case "其他资质证明":
                // 只有酒吧(businessSection=2) 和 KTV(businessSection=3) 显示其他资质证明
                menu.meta.isHide = ![2, 3].includes(businessSection);
                break;
              case "子账号与角色管理":
                // 有 storeId 时显示，无 storeId 时不显示
                menu.meta.isHide = !storeId;
                break;
              case "价目表":
                // 有店铺的商家才显示价目表
                menu.meta.isHide = !storeId;
                break;
              case "演出":
                // 有店铺且为休闲娱乐(businessSection=2) 时显示演出
                menu.meta.isHide = !storeId || businessSection !== 2;
                break;
              case "门店装修":
                // 仅父级：子项 decorationManagement 同 title，若在此处理会覆盖 storeTickets 下的 isHide
                if (menu.name === "storeDecorationManagement") {
                  menu.meta.isHide = !storeId;
                }
                break;
            }
          }

          // 门店装修：根据 storeTickets 只显示其一，0=只显示「门店装修」，1=只显示「装修公司」
          if (menu.name === "storeDecorationManagement" && menu.children?.length) {
            if (storeTickets != 0 && storeTickets != 1) {
              menu.meta.isHide = true;
              menu.meta.flattenSingleChild = false;
            } else {
              menu.children.forEach((child: any) => {
                if (child.name === "decorationManagement") {
                  child.meta.isHide = storeTickets !== 0;
                } else if (child.name === "decorationCompany") {
                  child.meta.isHide = storeTickets !== 1;
                }
              });
              // 仅装修公司模式：侧栏只出现一项「装修公司」，并重定向到装修公司页
              if (storeTickets === 1) {
                menu.meta.title = "装修公司";
                menu.meta.flattenSingleChild = true;
                menu.redirect = "/storeDecorationManagement/decorationCompany";
              } else if (storeTickets === 0) {
                menu.meta.title = "门店装修";
                menu.meta.flattenSingleChild = false;
                menu.redirect = "/storeDecorationManagement/decorationManagement";
              }
            }
          }

          // 递归处理子菜单：switch 按 meta.title 匹配，子级（如「设施与服务」在「基础设施服务」下）否则永远走不到
          if (menu.children?.length) {
            processMenus(menu.children);
          }
        });
      };

      processMenus(data);

      this.authMenuList = data;
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});
