import { defineStore } from "pinia";
import { ref } from "vue";
import { store } from "@/store";
import { getPermissions } from "@/api/common/login";

export const useBtnPermissionStore = defineStore("btnPermission", () => {
  const btnPermissions = ref<string[]>([]);

  const fetchPermissions = async () => {
    const res = await getPermissions();
    btnPermissions.value = res.data;
  }

  const hasPermission = (permission: string) => {
    return btnPermissions.value.includes(permission);
  }

  /**
   * @description 从权限列表中解析出所有 shop:mode:数字 格式的权限，返回对应的数字列表
   * @returns 拥有 shopMode 权限的数字数组
   */
  const getShopModeList = () => {
    const pattern = /^shop:mode:(\d+)$/;
    return btnPermissions.value
      .map((permission) => {
        const match = permission.match(pattern);
        return match ? Number(match[1]) : null;
      })
      .filter((num): num is number => num !== null);
  }

  return {
    btnPermissions,
    fetchPermissions,
    hasPermission,
    getShopModeList,
  };
});


/**
 * @description 用于在 setup 外使用 store
 */
export function useBtnPermissionStoreOutside() {
  return useBtnPermissionStore(store)
}
