import { ref, onMounted } from "vue";
import { getAllPermissions, getPermissionsGrouped } from "@/api/permission";
import type { PermissionItem, PermissionModule } from "./types";

export function usePermission() {
  const loading = ref(false);
  const permissionList = ref<PermissionItem[]>([]);
  const permissionModules = ref<PermissionModule[]>([]);
  const activeModule = ref("");

  // 获取所有权限
  async function fetchAllPermissions() {
    loading.value = true;
    try {
      const { data } = await getAllPermissions();
      permissionList.value = data || [];
    } catch (error) {
      console.error("获取权限列表失败:", error);
    } finally {
      loading.value = false;
    }
  }

  // 获取分组权限
  async function fetchPermissionsGrouped() {
    loading.value = true;
    try {
      const { data } = await getPermissionsGrouped();
      permissionModules.value = data || [];
      if (data && data.length > 0) {
        activeModule.value = data[0].code;
      }
    } catch (error) {
      console.error("获取权限分组失败:", error);
    } finally {
      loading.value = false;
    }
  }

  // 获取权限类型标签
  function getPermissionTypeTag(type: number) {
    switch (type) {
      case 1:
        return { text: "菜单", type: "primary" };
      case 2:
        return { text: "按钮", type: "success" };
      default:
        return { text: "未知", type: "info" };
    }
  }

  // 刷新数据
  async function refresh() {
    await Promise.all([fetchAllPermissions(), fetchPermissionsGrouped()]);
  }

  onMounted(() => {
    refresh();
  });

  return {
    loading,
    permissionList,
    permissionModules,
    activeModule,
    getPermissionTypeTag,
    refresh
  };
}
