import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Role, RoleParam } from './model';
import type { Menu } from '../menu/model';
import {SERVER_API_URL} from "@/utils/server";

/**
 * 分页查询角色
 */
export async function pageRoles(params: RoleParam) {
  const res = await request.get<ApiResult<PageResult<Role>>>(
    SERVER_API_URL + '/system/role/page',
    { params }
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询角色列表
 */
export async function listRoles(params?: RoleParam) {
  const res = await request.get<ApiResult<Role[]>>(
    SERVER_API_URL + '/system/role',
    {
      params
    }
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加角色
 */
export async function addRole(data: Role) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/system/role',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改角色
 */
export async function updateRole(data: Role) {
  const res = await request.put<ApiResult<unknown>>(
    SERVER_API_URL + '/system/role',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除角色
 */
export async function removeRole(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    SERVER_API_URL + '/system/role/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除角色
 */
export async function removeRoles(data: (number | undefined)[]) {
  const res = await request.del<ApiResult<unknown>>(
    SERVER_API_URL + '/system/role/batch',
    {
      data
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取角色分配的菜单
 */
export async function listRoleMenus(roleId?: number) {
  const res = await request.get<ApiResult<Menu[]>>(
    SERVER_API_URL + '/system/role-menu/' + roleId
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改角色菜单
 */
export async function updateRoleMenus(roleId?: number, data?: number[]) {
  const res = await request.put<ApiResult<unknown>>(
    SERVER_API_URL + '/system/role-menu/' + roleId,
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
