import {
  PaggingReq,
  PaggingRes,
  axios,
  detailRole,
  getListByDeptId,
  getPageList,
  getRoleTree,
  removeRole,
  userperInfo,
} from "@/request";
import { changSaveLocal, getLocal } from "@/util/localUtil";
import { ref } from "vue";
import { UserPermission, setPermission } from "./permission";
import { user } from "./user";

export type Role = {
  createTime: string;
  deptId: string;
  deptName: string;
  level: number;
  nickName: string;
  perm: RoleMenuTreeItem[];
  roleDesc: string;
  roleKey: string;
  roleName: string;
  sort: 1;
  updateTime: string;
  id: string;
  creatorId: string;
  type: number;
  perms: string;
  roleId: string;
};

export enum RoleLevel {
  tourist = 0,
  systemAdmin = 1,
  admin = 2,
  corps = 3,
  detachment1 = 4,
  detachment2 = 5,
}

export enum DataScope {
  none = 0,
  all = 1,
  selfLower = 3,
  selfInner = 4,
  personCreate = 5,
}

export type RoleMenuTreeItem = {
  id: string;
  permissionId: string;
  name: string;
  parentId: string;
  dataScope: DataScope;
  perms: string;
  type: "menu" | "button";
  children: RoleMenuTree;
};
export type RoleMenuTree = RoleMenuTreeItem[];

export const roleId = ref(getLocal("roleId", ""));
export const roleLevel = ref<RoleLevel>(getLocal("role", RoleLevel.tourist));
export const roleMenuTree = ref<RoleMenuTree>([]);

changSaveLocal("roleId", () => roleId.value);
changSaveLocal("role", () => roleLevel.value);

export const refreshRoleMenuTree = async () => {
  const res = await axios.get(getRoleTree);
  roleMenuTree.value = res.data;
};

export const getRole = async (roleId: string): Promise<Role> => {
  const data = (await axios.get(detailRole + roleId)).data;
  return {
    ...data,
    perm: data.perm.map((item: any) => ({
      ...item,
      dataScope: Number(item.dataScope),
    })),
  };
};

export const delRole = async (roleId: string) =>
  axios.post(removeRole + roleId, { id: roleId });

// 服务端permission转客户端
const serviceCoverUserPermission = (
  roles: RoleMenuTreeItem[]
): UserPermission[] =>
  roles.map((s) => ({
    resourceKey: s.perms,
    type: s.type,
    dataScope: Number(s.dataScope),
  }));

const userPermListCover = (perms: string[]): UserPermission[] => {
  const uPerms: UserPermission[] = [];
  const addedMenus = [...perms];
  for (const perm of perms) {
    const permChild = perm.split(":");
    const menu = permChild.length > 1 ? permChild[0] : null;

    if (menu && !addedMenus.includes(menu)) {
      uPerms.push({
        resourceKey: menu,
        type: "menu",
        dataScope: DataScope.all,
      });
      addedMenus.push(menu);
    }
    uPerms.push({
      resourceKey: perm,
      type: menu ? "button" : "menu",
      dataScope: DataScope.all,
    });
  }
  return uPerms;
};

// 刷新权限
export const refreshRole = async () => {
  roleLevel.value = user.value.info.isAdmin
    ? RoleLevel.systemAdmin
    : RoleLevel.corps;
  // console.log(, user.value.info.permsList);
  // setPermission(userPermListCover(user.value.info.permsList));

  // const { perm, level } = await getRole(roleId.value);
  // setPermission(serviceCoverUserPermission(perm as any));
  // roleLevel.value = level;
};

type RolePaggingParams = Pick<Role, "deptId"> & { searchKey: string };
export const getRolePagging = async (params: RolePaggingParams) =>
  (await axios.get<PaggingRes<Role>>(getPageList, { params })).data;

export const getRolesByDetpId = async (deptId: string) =>
  (await axios.get<Role[]>(getListByDeptId, { params: { deptId } })).data;
