import { SYSTEM_SERVICE_PREFIX } from '@/constants/service';
import { request } from '../request';
import {
  type ServiceRequestResult,
  mapServiceResult,
  normalizeNullableStringId,
  normalizeStringId,
  safeJsonRequestConfig
} from './shared';
import UserManagementRelationQueryReqVO = Api.SystemManage.UserManagementRelationQueryReqVO;

const ROLE_PREFIX = `${SYSTEM_SERVICE_PREFIX}/role`;
const MENU_PREFIX = `${SYSTEM_SERVICE_PREFIX}/menu`;
const PERMISSION_PREFIX = `${SYSTEM_SERVICE_PREFIX}/permission`;
const USER_PREFIX = `${SYSTEM_SERVICE_PREFIX}/user`;
const DEPT_PREFIX = `${SYSTEM_SERVICE_PREFIX}/dept`;
const POST_PREFIX = `${SYSTEM_SERVICE_PREFIX}/post`;
const ORG_LEADER_PREFIX = `${SYSTEM_SERVICE_PREFIX}/org-leader`;
const USER_MANAGEMENT_RELATION_PREFIX = `${SYSTEM_SERVICE_PREFIX}/user-management-relation`;
const USER_SIGNATURE_PREFIX = `${SYSTEM_SERVICE_PREFIX}/user-signatures`;

function appendQueryValue(query: URLSearchParams, key: string, value: unknown) {
  if (value === null || value === undefined || value === '') {
    return;
  }

  if (Array.isArray(value)) {
    value.forEach(item => appendQueryValue(query, key, item));
    return;
  }

  query.append(key, String(value));
}

function buildQuery(params: object = {}) {
  const query = new URLSearchParams();

  Object.entries(params).forEach(([key, value]) => {
    appendQueryValue(query, key, value);
  });

  return query.toString();
}

function createRolePageQuery(params?: Api.SystemManage.RoleSearchParams) {
  const query = new URLSearchParams();

  if (!params) {
    return query.toString();
  }

  if (params.pageNo !== undefined) {
    query.append('pageNo', String(params.pageNo));
  }

  if (params.pageSize !== undefined) {
    query.append('pageSize', String(params.pageSize));
  }

  if (params.name) {
    query.append('name', params.name);
  }

  if (params.code) {
    query.append('code', params.code);
  }

  if (params.status !== undefined) {
    query.append('status', String(params.status));
  }

  params.createTime?.forEach(item => {
    if (item) {
      query.append('createTime', item);
    }
  });

  if (params.scopeType) {
    query.append('scopeType', params.scopeType);
  }

  if (params.objectType) {
    query.append('objectType', params.objectType);
  }

  return query.toString();
}

function createBatchDeleteQuery(ids: Array<string | number>) {
  const query = new URLSearchParams();

  ids.forEach(id => {
    query.append('ids', String(id));
  });

  return query.toString();
}

type UserSimpleResponse = Omit<Api.SystemManage.UserSimple, 'id'> & {
  id: string | number;
  deptId?: string | number | null;
};

type RoleResponse = Omit<Api.SystemManage.Role, 'id'> & {
  id: string | number;
};

type RolePageResponse = Api.SystemManage.PageResult<RoleResponse>;

type RoleSimpleResponse = Omit<Api.SystemManage.RoleSimple, 'id'> & {
  id: string | number;
};

type MenuResponse = Omit<Api.SystemManage.Menu, 'id' | 'parentId' | 'children'> & {
  id: string | number;
  parentId: string | number;
  children?: MenuResponse[] | null;
};

type MenuSimpleResponse = Omit<Api.SystemManage.MenuSimple, 'id' | 'parentId' | 'children'> & {
  id: string | number;
  parentId: string | number;
  children?: MenuSimpleResponse[] | null;
};

type UserManagementRelationResponse = Omit<
  Api.SystemManage.UserManagementRelation,
  'id' | 'managerUserId' | 'subordinateUserId'
> & {
  id: string | number | null;
  managerUserId: string | number | null;
  subordinateUserId: string | number | null;
};

type UserManagementRelationTreeResponse = Omit<
  Api.SystemManage.UserManagementRelationTreeRespVO,
  'id' | 'userId' | 'managerUserId' | 'children'
> & {
  id: string | number | null;
  userId: string | number;
  managerUserId: string | number | null;
  children?: UserManagementRelationTreeResponse[] | null;
};

type MySubordinateTreeNodeResponse = Omit<Api.SystemManage.MySubordinateTreeNode, 'userId' | 'children'> & {
  userId: string | number;
  children?: MySubordinateTreeNodeResponse[] | null;
};

type UserSignatureResponse = Omit<Api.SystemManage.UserSignature, 'id' | 'userId' | 'fileId'> & {
  id: string | number;
  userId: string | number;
  fileId: string | number;
};

function normalizeUserSimple(user: UserSimpleResponse): Api.SystemManage.UserSimple {
  return {
    ...user,
    id: normalizeStringId(user.id),
    deptId: normalizeNullableStringId(user.deptId)
  };
}

function normalizeRole(role: RoleResponse): Api.SystemManage.Role {
  return {
    ...role,
    id: normalizeStringId(role.id)
  };
}

function normalizeRoleSimple(role: RoleSimpleResponse): Api.SystemManage.RoleSimple {
  return {
    ...role,
    id: normalizeStringId(role.id)
  };
}

function normalizeMenu(menu: MenuResponse): Api.SystemManage.Menu {
  return {
    ...menu,
    id: normalizeStringId(menu.id),
    parentId: normalizeStringId(menu.parentId),
    children: menu.children?.map(normalizeMenu) ?? null
  };
}

function normalizeMenuSimple(menu: MenuSimpleResponse): Api.SystemManage.MenuSimple {
  return {
    ...menu,
    id: normalizeStringId(menu.id),
    parentId: normalizeStringId(menu.parentId),
    children: menu.children?.map(normalizeMenuSimple) ?? null
  };
}

function normalizeUserManagementRelation(
  relation: UserManagementRelationResponse
): Api.SystemManage.UserManagementRelation {
  return {
    ...relation,
    id: normalizeNullableStringId(relation.id),
    managerUserId: normalizeNullableStringId(relation.managerUserId),
    subordinateUserId: normalizeNullableStringId(relation.subordinateUserId)
  };
}

function normalizeUserManagementRelationTree(
  relation: UserManagementRelationTreeResponse
): Api.SystemManage.UserManagementRelationTreeRespVO {
  return {
    ...relation,
    id: normalizeNullableStringId(relation.id),
    userId: normalizeStringId(relation.userId),
    managerUserId: normalizeNullableStringId(relation.managerUserId),
    children: relation.children?.map(normalizeUserManagementRelationTree) ?? null
  };
}

function normalizeMySubordinateTreeNode(node: MySubordinateTreeNodeResponse): Api.SystemManage.MySubordinateTreeNode {
  return {
    ...node,
    userId: normalizeStringId(node.userId),
    children: node.children?.map(normalizeMySubordinateTreeNode) ?? null
  };
}

function normalizeUserSignature(signature: UserSignatureResponse): Api.SystemManage.UserSignature {
  return {
    ...signature,
    id: normalizeStringId(signature.id),
    userId: normalizeStringId(signature.userId),
    fileId: normalizeStringId(signature.fileId),
    fileName: signature.fileName ?? null,
    status: signature.status ?? null,
    remark: signature.remark ?? null,
    createTime: signature.createTime ?? null,
    updateTime: signature.updateTime ?? null
  };
}

/** 获取角色分页 */
export async function fetchGetRolePage(params?: Api.SystemManage.RoleSearchParams) {
  const query = createRolePageQuery(params);

  const result = await request<RolePageResponse>({
    ...safeJsonRequestConfig,
    url: query ? `${ROLE_PREFIX}/page?${query}` : `${ROLE_PREFIX}/page`,
    method: 'get'
  });

  return mapServiceResult(result as ServiceRequestResult<RolePageResponse>, data => ({
    ...data,
    list: data.list.map(normalizeRole)
  }));
}

/** 为兼容旧代码保留原函数名 */
export const fetchGetRoleList = fetchGetRolePage;

/** 获取角色详情 */
export async function fetchGetRole(id: string) {
  const result = await request<RoleResponse>({
    ...safeJsonRequestConfig,
    url: `${ROLE_PREFIX}/get`,
    method: 'get',
    params: { id }
  });

  return mapServiceResult(result as ServiceRequestResult<RoleResponse>, normalizeRole);
}

/** 创建角色 */
export async function fetchCreateRole(data: Api.SystemManage.SaveRoleParams) {
  const result = await request<string | number>({
    ...safeJsonRequestConfig,
    url: `${ROLE_PREFIX}/create`,
    method: 'post',
    data
  });

  return mapServiceResult(result as ServiceRequestResult<string | number>, normalizeStringId);
}

/** 更新角色 */
export function fetchUpdateRole(
  data: { id: string } & Omit<Api.SystemManage.SaveRoleParams, 'scopeType' | 'objectType'>
) {
  return request<boolean>({
    url: `${ROLE_PREFIX}/update`,
    method: 'put',
    data
  });
}

/** 删除角色 */
export function fetchDeleteRole(id: string) {
  return request<boolean>({
    url: `${ROLE_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 批量删除角色 */
export function fetchBatchDeleteRole(ids: string[]) {
  return request<boolean>({
    url: `${ROLE_PREFIX}/delete-list?${createBatchDeleteQuery(ids)}`,
    method: 'delete'
  });
}

/**
 * 获取全部角色
 *
 * 为当前用户页面保留 `roleName / roleCode` 字段，直到该页面完成重构
 */
export async function fetchGetAllRoles(): Promise<ServiceRequestResult<Api.SystemManage.AllRole[]>> {
  const result = await request<RoleSimpleResponse[]>({
    ...safeJsonRequestConfig,
    url: `${ROLE_PREFIX}/simple-list`,
    method: 'get'
  });

  if (result.error || !result.data) {
    return result as ServiceRequestResult<Api.SystemManage.AllRole[]>;
  }

  return {
    ...result,
    data: result.data.map(item => {
      const role = normalizeRoleSimple(item);

      return {
        ...role,
        roleName: role.name,
        roleCode: role.code
      };
    })
  };
}

/** 获取启用状态的角色简表 */
export async function fetchGetRoleSimpleList(params?: Api.SystemManage.ScopeQueryParams) {
  const result = await request<RoleSimpleResponse[]>({
    ...safeJsonRequestConfig,
    url: `${ROLE_PREFIX}/simple-list`,
    method: 'get',
    params
  });

  return mapServiceResult(result as ServiceRequestResult<RoleSimpleResponse[]>, data => data.map(normalizeRoleSimple));
}

/** 获取部门列表 */
export function fetchGetDeptList(params?: Api.SystemManage.DeptSearchParams) {
  return request<Api.SystemManage.DeptList>({
    url: `${DEPT_PREFIX}/list`,
    method: 'get',
    params
  });
}

/** 获取部门简表 */
export function fetchGetDeptSimpleList() {
  return request<Api.SystemManage.DeptSimpleList>({
    url: `${DEPT_PREFIX}/simple-list`,
    method: 'get'
  });
}

/** 获取部门自身及全部子部门 */
export async function fetchGetDeptSelfAndChildren(id: string) {
  const result = await request<Api.SystemManage.DeptSelfAndChildrenList>({
    ...safeJsonRequestConfig,
    url: `${DEPT_PREFIX}/list-self-and-children`,
    method: 'get',
    params: { id }
  });

  return mapServiceResult(result as ServiceRequestResult<Api.SystemManage.DeptSelfAndChildrenList>, data => data);
}

/** 创建部门 */
export function fetchCreateDept(data: Api.SystemManage.SaveDeptParams) {
  return request<number>({
    url: `${DEPT_PREFIX}/create`,
    method: 'post',
    data
  });
}

/** 更新部门 */
export function fetchUpdateDept(data: { id: number } & Api.SystemManage.SaveDeptParams) {
  return request<boolean>({
    url: `${DEPT_PREFIX}/update`,
    method: 'put',
    data
  });
}

/** 删除部门 */
export function fetchDeleteDept(id: number) {
  return request<boolean>({
    url: `${DEPT_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 根据部门获取组织负责人关系 */
export function fetchGetOrgLeaderListByDept(deptId: number) {
  return request<Api.SystemManage.OrgLeaderRelationList>({
    url: `${ORG_LEADER_PREFIX}/list-by-dept`,
    method: 'get',
    params: { deptId }
  });
}

/** 获取组织负责人的候选用户 */
export function fetchGetOrgLeaderCandidateUsers(deptId: number) {
  return request<Api.SystemManage.OrgLeaderCandidateUserList>({
    url: `${ORG_LEADER_PREFIX}/candidate-users`,
    method: 'get',
    params: { deptId }
  });
}

/** 创建组织负责人关系 */
export function fetchCreateOrgLeaderRelation(data: Api.SystemManage.SaveOrgLeaderRelationParams) {
  return request<number>({
    url: `${ORG_LEADER_PREFIX}/create`,
    method: 'post',
    data
  });
}

/** 更新组织负责人关系 */
export function fetchUpdateOrgLeaderRelation(data: { id: number } & Api.SystemManage.SaveOrgLeaderRelationParams) {
  return request<boolean>({
    url: `${ORG_LEADER_PREFIX}/update`,
    method: 'put',
    data
  });
}

/** 删除组织负责人关系 */
export function fetchDeleteOrgLeaderRelation(id: number) {
  return request<boolean>({
    url: `${ORG_LEADER_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 获取启用状态的岗位简表 */
export function fetchGetPostSimpleList() {
  return request<Api.SystemManage.PostSimpleList>({
    url: `${POST_PREFIX}/simple-list`,
    method: 'get'
  });
}

/** 获取岗位分页 */
export function fetchGetPostPage(params?: Api.SystemManage.PostSearchParams) {
  return request<Api.SystemManage.PostList>({
    url: `${POST_PREFIX}/page`,
    method: 'get',
    params
  });
}

/** 获取岗位详情 */
export function fetchGetPost(id: number) {
  return request<Api.SystemManage.Post>({
    url: `${POST_PREFIX}/get`,
    method: 'get',
    params: { id }
  });
}

/** 创建岗位 */
export function fetchCreatePost(data: Api.SystemManage.SavePostParams) {
  return request<number>({
    url: `${POST_PREFIX}/create`,
    method: 'post',
    data
  });
}

/** 更新岗位 */
export function fetchUpdatePost(data: { id: number } & Api.SystemManage.SavePostParams) {
  return request<boolean>({
    url: `${POST_PREFIX}/update`,
    method: 'put',
    data
  });
}

/** 删除岗位 */
export function fetchDeletePost(id: number) {
  return request<boolean>({
    url: `${POST_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 批量删除岗位 */
export function fetchBatchDeletePost(ids: number[]) {
  return request<boolean>({
    url: `${POST_PREFIX}/delete-list?${createBatchDeleteQuery(ids)}`,
    method: 'delete'
  });
}

/** 导出岗位 */
export function fetchExportPost(params: Api.SystemManage.PostSearchParams) {
  const query = buildQuery(params);

  return request<Blob, 'blob'>({
    url: query ? `${POST_PREFIX}/export-excel?${query}` : `${POST_PREFIX}/export-excel`,
    method: 'get',
    responseType: 'blob'
  });
}

/** 获取用户简单列表（用于用户选择下拉框） */
export async function fetchGetUserSimpleList() {
  return request<UserSimpleResponse[]>({
    ...safeJsonRequestConfig,
    url: `${USER_PREFIX}/simple-list`,
    method: 'get'
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<UserSimpleResponse[]>, data => data.map(normalizeUserSimple))
  );
}

/** 获取当前登录人的直属上级 */
export async function fetchGetLoginUserDirectManager() {
  return request<UserSimpleResponse | null>({
    ...safeJsonRequestConfig,
    url: `${USER_PREFIX}/profile/direct-manager`,
    method: 'get'
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<UserSimpleResponse | null>, data =>
      data ? normalizeUserSimple(data) : null
    )
  );
}

/** 获取用户分页 */
export function fetchGetUserPage(params?: Api.SystemManage.UserSearchParams) {
  return request<Api.SystemManage.UserList>({
    url: `${USER_PREFIX}/page`,
    method: 'get',
    params
  });
}

/** 为兼容旧代码保留原函数名 */
export const fetchGetUserList = fetchGetUserPage;

/** 通过部门id获取用户详情 */
export function fetchGetUserListByDeptId(deptId: any) {
  return request<UserSimpleResponse[]>({
    ...safeJsonRequestConfig,
    url: `${USER_PREFIX}/list-by-dept-id`,
    method: 'get',
    params: { deptId }
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<UserSimpleResponse[]>, data => data.map(normalizeUserSimple))
  );
}

/** 获取用户详情 */
export function fetchGetUser(id: number) {
  return request<Api.SystemManage.User>({
    url: `${USER_PREFIX}/get`,
    method: 'get',
    params: { id }
  });
}

/** 创建用户 */
export function fetchCreateUser(data: Api.SystemManage.SaveUserParams) {
  return request<number>({
    url: `${USER_PREFIX}/create`,
    method: 'post',
    data
  });
}

/** 更新用户 */
export function fetchUpdateUser(data: { id: number } & Api.SystemManage.SaveUserParams) {
  return request<boolean>({
    url: `${USER_PREFIX}/update`,
    method: 'put',
    data
  });
}

/** 更新用户状态 */
export function fetchUpdateUserStatus(data: Api.SystemManage.UpdateUserStatusParams) {
  return request<boolean>({
    url: `${USER_PREFIX}/update-status`,
    method: 'put',
    data
  });
}

/** 重置用户密码 */
export function fetchUpdateUserPassword(data: Api.SystemManage.UpdateUserPasswordParams) {
  return request<boolean>({
    url: `${USER_PREFIX}/update-password`,
    method: 'put',
    data
  });
}

/** 删除用户 */
export function fetchDeleteUser(id: number) {
  return request<boolean>({
    url: `${USER_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 批量删除用户 */
export function fetchBatchDeleteUser(ids: number[]) {
  return request<boolean>({
    url: `${USER_PREFIX}/delete-list?${createBatchDeleteQuery(ids)}`,
    method: 'delete'
  });
}

/** 导出用户 */
export function fetchExportUser(params: Api.SystemManage.UserSearchParams) {
  const query = buildQuery(params);

  return request<Blob, 'blob'>({
    url: query ? `${USER_PREFIX}/export-excel?${query}` : `${USER_PREFIX}/export-excel`,
    method: 'get',
    responseType: 'blob'
  });
}

/** 获取菜单列表 */
export async function fetchGetMenuList(params?: Api.SystemManage.MenuSearchParams) {
  const result = await request<MenuResponse[]>({
    ...safeJsonRequestConfig,
    url: `${MENU_PREFIX}/list`,
    method: 'get',
    params
  });

  return mapServiceResult(result as ServiceRequestResult<MenuResponse[]>, data => data.map(normalizeMenu));
}

/** 获取菜单详情 */
export async function fetchGetMenu(id: string) {
  const result = await request<MenuResponse>({
    ...safeJsonRequestConfig,
    url: `${MENU_PREFIX}/get`,
    method: 'get',
    params: { id }
  });

  return mapServiceResult(result as ServiceRequestResult<MenuResponse>, normalizeMenu);
}

/** 创建菜单 */
export async function fetchCreateMenu(data: Api.SystemManage.SaveMenuParams) {
  const result = await request<string | number>({
    ...safeJsonRequestConfig,
    url: `${MENU_PREFIX}/create`,
    method: 'post',
    data
  });

  return mapServiceResult(result as ServiceRequestResult<string | number>, normalizeStringId);
}

/** 更新菜单 */
export function fetchUpdateMenu(
  data: { id: string } & Omit<Api.SystemManage.SaveMenuParams, 'scopeType' | 'objectType'>
) {
  return request<boolean>({
    url: `${MENU_PREFIX}/update`,
    method: 'put',
    data
  });
}

/** 删除菜单 */
export function fetchDeleteMenu(id: string) {
  return request<boolean>({
    url: `${MENU_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 批量删除菜单 */
export function fetchBatchDeleteMenu(ids: string[]) {
  return request<boolean>({
    url: `${MENU_PREFIX}/delete-list?${createBatchDeleteQuery(ids)}`,
    method: 'delete'
  });
}

/** 获取启用状态的菜单简表 */
export async function fetchGetMenuSimpleList(params?: Api.SystemManage.ScopeQueryParams) {
  const result = await request<MenuSimpleResponse[]>({
    ...safeJsonRequestConfig,
    url: `${MENU_PREFIX}/simple-list`,
    method: 'get',
    params
  });

  return mapServiceResult(result as ServiceRequestResult<MenuSimpleResponse[]>, data => data.map(normalizeMenuSimple));
}

/** 获取角色关联的菜单 ID 列表 */
export async function fetchGetRoleMenuIds(roleId: string) {
  const result = await request<Array<string | number>>({
    ...safeJsonRequestConfig,
    url: `${PERMISSION_PREFIX}/list-role-menus`,
    method: 'get',
    params: { roleId }
  });

  return mapServiceResult(result as ServiceRequestResult<Array<string | number>>, data => data.map(normalizeStringId));
}

/** 分配角色菜单 */
export function fetchAssignRoleMenus(data: Api.SystemManage.AssignRoleMenuParams) {
  return request<boolean>({
    url: `${PERMISSION_PREFIX}/assign-role-menu`,
    method: 'post',
    data
  });
}

/** 获取用户关联的角色 ID 列表 */
export async function fetchGetUserRoleIds(userId: number) {
  const result = await request<Array<string | number>>({
    ...safeJsonRequestConfig,
    url: `${PERMISSION_PREFIX}/list-user-roles`,
    method: 'get',
    params: { userId }
  });

  return mapServiceResult(result as ServiceRequestResult<Array<string | number>>, data => data.map(normalizeStringId));
}

/** 分配用户角色 */
export function fetchAssignUserRoles(data: Api.SystemManage.AssignUserRoleParams) {
  return request<boolean>({
    url: `${PERMISSION_PREFIX}/assign-user-role`,
    method: 'post',
    data
  });
}

export async function fetchGetUserSignature(userId: string) {
  const result = await request<UserSignatureResponse | null>({
    ...safeJsonRequestConfig,
    url: `${USER_SIGNATURE_PREFIX}/get`,
    method: 'get',
    params: { userId }
  });

  return mapServiceResult(result as ServiceRequestResult<UserSignatureResponse | null>, data =>
    data ? normalizeUserSignature(data) : null
  );
}

export function fetchSaveUserSignature(data: Api.SystemManage.SaveUserSignatureParams) {
  return request<boolean>({
    ...safeJsonRequestConfig,
    url: `${USER_SIGNATURE_PREFIX}/save`,
    method: 'post',
    data
  });
}

export function fetchDeleteUserSignature(userId: string) {
  return request<boolean>({
    ...safeJsonRequestConfig,
    url: `${USER_SIGNATURE_PREFIX}/delete`,
    method: 'delete',
    params: { userId }
  });
}

export async function fetchGetMyUserSignature() {
  const result = await request<UserSignatureResponse | null>({
    ...safeJsonRequestConfig,
    url: `${USER_SIGNATURE_PREFIX}/my`,
    method: 'get'
  });

  return mapServiceResult(result as ServiceRequestResult<UserSignatureResponse | null>, data =>
    data ? normalizeUserSignature(data) : null
  );
}

// ==================== 用户管理链路相关 API ====================
/**
 * 获取用户管理链路树形结构
 *
 * 用于树形控件展示，包含用户的上下级层级关系
 * 树形结构特点：
 * - 根节点：最高领导，没有上级
 * - 中间节点：有上级也有下级
 * - 叶子节点：基层员工，没有下级
 */
export async function fetchGetUserManagementRelationTree(query: UserManagementRelationQueryReqVO) {
  return request<UserManagementRelationTreeResponse[]>({
    ...safeJsonRequestConfig,
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/tree`,
    method: 'get',
    params: query
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<UserManagementRelationTreeResponse[]>, data =>
      data.map(normalizeUserManagementRelationTree)
    )
  );
}

/**
 * 通过搜索框的查询条件，获取用户管理链路树形结构
 * 用于树形控件展示，包含用户的上下级层级关系
 */
export async function fetchGetUserManagementRelationQuery(query: UserManagementRelationQueryReqVO) {
  return request<UserManagementRelationTreeResponse[]>({
    ...safeJsonRequestConfig,
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/query`,
    method: 'get',
    params: query
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<UserManagementRelationTreeResponse[]>, data =>
      data.map(normalizeUserManagementRelationTree)
    )
  );
}

/** 获取当前登录用户下属树 */
export async function fetchGetMySubordinateTree() {
  return request<MySubordinateTreeNodeResponse>({
    ...safeJsonRequestConfig,
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/my-subordinate-tree`,
    method: 'get'
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<MySubordinateTreeNodeResponse>, normalizeMySubordinateTreeNode)
  );
}

/** 获取某用户当前生效的直属下级列表 */
export async function fetchGetDirectSubordinates(userId: string) {
  const result = await request<UserSimpleResponse[]>({
    ...safeJsonRequestConfig,
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/direct-subordinates`,
    method: 'get',
    params: { userId }
  });

  return mapServiceResult(result as ServiceRequestResult<UserSimpleResponse[]>, data => data.map(normalizeUserSimple));
}

/**
 * 获取用户管理链路详情
 *
 * 根据主键 ID 查询单条用户管理链路记录
 *
 * @param id 关系记录主键 ID
 */
export async function fetchGetUserManagementRelation(id: string) {
  return request<UserManagementRelationResponse>({
    ...safeJsonRequestConfig,
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/get`,
    method: 'get',
    params: { id }
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<UserManagementRelationResponse>, normalizeUserManagementRelation)
  );
}

/**
 * 创建用户管理链路
 *
 * 创建新的用户管理链路记录
 *
 * @param data 创建请求参数
 */
export async function fetchCreateUserManagementRelation(data: Api.SystemManage.UserManagementRelationSaveReqVO) {
  return request<string | number>({
    ...safeJsonRequestConfig,
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/create`,
    method: 'post',
    data
  }).then(result => mapServiceResult(result as ServiceRequestResult<string | number>, normalizeStringId));
}

/**
 * 更新用户管理链路
 *
 * 更新已有的用户管理链路记录
 *
 * @param data 更新请求参数（包含 id）
 */
export function fetchUpdateUserManagementRelation(
  data: { id: string } & Api.SystemManage.UserManagementRelationSaveReqVO
) {
  return request<boolean>({
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/update`,
    method: 'put',
    data
  });
}

/**
 * 删除用户管理链路
 *
 * 根据主键 ID 删除单条用户管理链路记录
 *
 * @param id 关系记录主键 ID
 */
export function fetchDeleteUserManagementRelation(id: string | null) {
  return request<boolean>({
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/**
 * 批量删除用户管理链路
 *
 * 根据主键 ID 列表批量删除用户管理链路记录
 *
 * @param ids 关系记录主键 ID 列表
 */
export function fetchBatchDeleteUserManagementRelation(ids: string[]) {
  return request<boolean>({
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/delete-list?${createBatchDeleteQuery(ids)}`,
    method: 'delete'
  });
}

/**
 * 获取未绑定直属上级的候选下级用户列表
 *
 * 用于获取尚未绑定直属上级的用户列表，供选择使用
 *
 * @returns 候选下级用户列表
 */
export async function fetchGetCandidateSubordinateUsers() {
  return request<UserSimpleResponse[]>({
    ...safeJsonRequestConfig,
    url: `${USER_MANAGEMENT_RELATION_PREFIX}/candidate-users`,
    method: 'get'
  }).then(result =>
    mapServiceResult(result as ServiceRequestResult<UserSimpleResponse[]>, data => data.map(normalizeUserSimple))
  );
}
