import { ref, reactive, computed, onMounted } from "vue";
import { message } from "@/utils/message";
import {
  getPermissionsGrouped,
  getRolePermissionIds,
  updateRolePermissions
} from "@/api/permission";
import { getAllRoles } from "@/api/role";

export function usePermission() {
  const loading = ref(false);
  const saving = ref(false);

  // 角色列表
  const roleList = ref<any[]>([]);
  const selectedRole = ref<any>(null);
  const roleSearch = ref("");

  // 权限数据 - 按模块分组的树形结构
  const permissionTree = ref<any[]>([]);
  const checkedIds = ref<Set<number>>(new Set());
  const originalCheckedIds = ref<number[]>([]);
  const hasChanges = ref(false);
  const permissionSearch = ref("");
  const expandedModules = ref<string[]>([]);

  // 计算所有权限ID（用于全选/取消全选）
  const allPermissionIds = computed(() => {
    const ids: number[] = [];
    const collect = (list: any[]) => {
      list.forEach(item => {
        if (item.id > 0) ids.push(item.id);
        if (item.children?.length) collect(item.children);
      });
    };
    collect(permissionTree.value);
    return ids;
  });

  // 已选权限数量
  const checkedCount = computed(() => checkedIds.value.size);

  // 筛选后的角色列表
  const filteredRoles = computed(() => {
    if (!roleSearch.value) return roleList.value;
    const q = roleSearch.value.toLowerCase();
    return roleList.value.filter(
      r => r.name?.toLowerCase().includes(q) || r.code?.toLowerCase().includes(q)
    );
  });

  // 筛选后的权限树
  const filteredPermissionTree = computed(() => {
    if (!permissionSearch.value) {
      return permissionTree.value;
    }
    const q = permissionSearch.value.toLowerCase();
    return permissionTree.value
      .map(module => ({
        ...module,
        children: module.children?.filter(
          (p: any) =>
            p.permissionName?.toLowerCase().includes(q) ||
            p.permissionCode?.toLowerCase().includes(q)
        )
      }))
      .filter(module => module.children?.length > 0);
  });

  // 获取角色列表
  async function fetchRoles() {
    try {
      const { data } = await getAllRoles();
      roleList.value = data || [];
    } catch (error) {
      console.error("获取角色列表失败:", error);
    }
  }

  // 获取权限树(按模块分组)
  async function fetchPermissionTree() {
    loading.value = true;
    try {
      const { data } = await getPermissionsGrouped();
      permissionTree.value = data || [];
      // 默认展开所有模块
      if (data?.length) {
        expandedModules.value = data.map((m: any) => String(m.id));
      }
    } catch (error) {
      console.error("获取权限树失败:", error);
    } finally {
      loading.value = false;
    }
  }

  // 选中角色，加载其权限
  async function selectRole(role: any) {
    if (selectedRole.value?.id === role.id) return;
    selectedRole.value = role;
    hasChanges.value = false;
    loading.value = true;

    try {
      const { data } = await getRolePermissionIds(role.id);
      const ids: number[] = data || [];
      originalCheckedIds.value = ids;
      checkedIds.value = new Set(ids);
    } catch (error) {
      console.error("获取角色权限失败:", error);
      checkedIds.value = new Set();
      originalCheckedIds.value = [];
    } finally {
      loading.value = false;
    }
  }

  // 切换单个权限选中状态
  function togglePermission(permissionId: number, moduleId: string) {
    const newSet = new Set(checkedIds.value);
    if (newSet.has(permissionId)) {
      newSet.delete(permissionId);
    } else {
      newSet.add(permissionId);
    }
    checkedIds.value = newSet;
    hasChanges.value = true;

    // 展开对应的模块
    if (!expandedModules.value.includes(moduleId)) {
      expandedModules.value.push(moduleId);
    }
  }

  // 全选/取消全选某个模块下的所有权限
  function toggleModule(module: any, checked: boolean) {
    const newSet = new Set(checkedIds.value);
    const modulePermissions = module.children || [];
    const moduleIds = modulePermissions
      .filter((p: any) => p.id > 0)
      .map((p: any) => p.id);

    if (checked) {
      moduleIds.forEach((id: number) => newSet.add(id));
    } else {
      moduleIds.forEach((id: number) => newSet.delete(id));
    }

    checkedIds.value = newSet;
    hasChanges.value = true;
  }

  // 检查某个模块是否全选
  function isModuleAllChecked(module: any): boolean {
    const modulePermissions = module.children || [];
    const moduleIds = modulePermissions
      .filter((p: any) => p.id > 0)
      .map((p: any) => p.id);
    if (moduleIds.length === 0) return false;
    return moduleIds.every(id => checkedIds.value.has(id));
  }

  // 检查某个模块是否部分选中
  function isModuleIndeterminate(module: any): boolean {
    const modulePermissions = module.children || [];
    const moduleIds = modulePermissions
      .filter((p: any) => p.id > 0)
      .map((p: any) => p.id);
    if (moduleIds.length === 0) return false;
    const checked = moduleIds.filter(id => checkedIds.value.has(id));
    return checked.length > 0 && checked.length < moduleIds.length;
  }

  // 保存权限
  async function handleSave() {
    if (!selectedRole.value) {
      message("请先选择一个角色", { type: "warning" });
      return;
    }
    if (!hasChanges.value) {
      message("没有需要保存的变更", { type: "info" });
      return;
    }

    saving.value = true;
    try {
      const permissionIds = Array.from(checkedIds.value);
      const res = await updateRolePermissions(selectedRole.value.id, permissionIds);
      if (res.code === 200) {
        message(`角色 ${selectedRole.value.name} 权限保存成功`, { type: "success" });
        originalCheckedIds.value = [...permissionIds];
        hasChanges.value = false;
      } else {
        message(res.message || "保存失败", { type: "error" });
      }
    } catch (error) {
      message("保存失败", { type: "error" });
    } finally {
      saving.value = false;
    }
  }

  // 重置当前角色的权限到保存状态
  function handleReset() {
    checkedIds.value = new Set(originalCheckedIds.value);
    hasChanges.value = false;
    message("已重置为保存状态", { type: "info" });
  }

  // 刷新所有数据
  async function refresh() {
    await Promise.all([fetchRoles(), fetchPermissionTree()]);
    // 如果有选中的角色，重新加载其权限
    if (selectedRole.value) {
      const role = selectedRole.value;
      selectedRole.value = null;
      await selectRole(role);
    }
  }

  onMounted(async () => {
    await Promise.all([fetchRoles(), fetchPermissionTree()]);
  });

  return {
    loading,
    saving,
    roleList,
    selectedRole,
    roleSearch,
    filteredRoles,
    permissionTree,
    filteredPermissionTree,
    checkedIds,
    checkedCount,
    hasChanges,
    permissionSearch,
    expandedModules,
    allPermissionIds,

    selectRole,
    togglePermission,
    toggleModule,
    isModuleAllChecked,
    isModuleIndeterminate,
    handleSave,
    handleReset,
    refresh
  };
}
