/**
 * KRA - Authority API Service
 */
import request from '@/utils/request';

export interface Authority {
  authorityId: number | string;
  authorityName: string;
  parentId?: number | string;
  defaultRouter?: string;
  children?: Authority[];
  dataAuthorityId?: Authority[];
}

/** 获取角色列表 */
export const getAuthorityList = (data?: { page?: number; pageSize?: number }) => {
  return request.post('/authority/getAuthorityList', data || {});
};

/** 删除角色 */
export const deleteAuthority = (data: { authorityId: number | string }) => {
  return request.post('/authority/deleteAuthority', { authorityId: Number(data.authorityId) });
};

/** 创建角色 */
export const createAuthority = (data: Authority) => {
  return request.post('/authority/createAuthority', {
    ...data,
    authorityId: Number(data.authorityId),
    parentId: data.parentId ? Number(data.parentId) : 0,
  });
};

/** 拷贝角色 */
export const copyAuthority = (data: { authority: Authority; oldAuthorityId: number | string }) => {
  return request.post('/authority/copyAuthority', {
    authority: {
      ...data.authority,
      authorityId: Number(data.authority.authorityId),
      parentId: data.authority.parentId ? Number(data.authority.parentId) : 0,
    },
    oldAuthorityId: Number(data.oldAuthorityId),
  });
};

/** 设置角色资源权限 */
export const setDataAuthority = (data: { authorityId: number | string; dataAuthorityId: Authority[] }) => {
  return request.post('/authority/setDataAuthority', {
    authorityId: Number(data.authorityId),
    dataAuthorityId: data.dataAuthorityId?.map(item => ({
      ...item,
      authorityId: Number(item.authorityId),
    })),
  });
};

/** 修改角色 */
export const updateAuthority = (data: Authority) => {
  return request.put('/authority/updateAuthority', {
    ...data,
    authorityId: Number(data.authorityId),
    parentId: data.parentId ? Number(data.parentId) : 0,
  });
};

export default {
  getAuthorityList,
  deleteAuthority,
  createAuthority,
  copyAuthority,
  setDataAuthority,
  updateAuthority,
};
