import request from '@/utils/request'
import { buildZtree, extractCheckedKeys, postForm } from '@/utils/legacyRequest'

// 查询角色列表
export function listRole(query) {
  return postForm('/system/role/list', query)
}

// 查询角色详细
export function getRole(roleId) {
  return request({
    url: '/system/role/' + roleId,
    method: 'get'
  })
}

// 新增角色
export function addRole(data) {
  return postForm('/system/role/add', data)
}

// 修改角色
export function updateRole(data) {
  return postForm('/system/role/edit', data)
}

// 角色数据权限
export function dataScope(data) {
  return postForm('/system/role/authDataScope', data)
}

// 角色状态修改
export function changeRoleStatus(roleId, status) {
  return postForm('/system/role/changeStatus', {
    roleId,
    status
  })
}

// 删除角色
export function delRole(roleId) {
  return postForm('/system/role/remove', { ids: roleId })
}

// 查询角色已授权用户列表
export function allocatedUserList(query) {
  return postForm('/system/role/authUser/allocatedList', query)
}

// 查询角色未授权用户列表
export function unallocatedUserList(query) {
  return postForm('/system/role/authUser/unallocatedList', query)
}

// 取消用户授权角色
export function authUserCancel(data) {
  return postForm('/system/role/authUser/cancel', data)
}

// 批量取消用户授权角色
export function authUserCancelAll(data) {
  return postForm('/system/role/authUser/cancelAll', data)
}

// 授权用户选择
export function authUserSelectAll(data) {
  return postForm('/system/role/authUser/selectAll', data)
}

// 根据角色ID查询部门树结构
export function deptTreeSelect(roleId) {
  return request({
    url: '/system/role/deptTreeData',
    method: 'get',
    params: { roleId }
  }).then(response => {
    const treeList = Array.isArray(response) ? response : (response.data || [])
    return {
      depts: buildZtree(treeList),
      checkedKeys: extractCheckedKeys(treeList)
    }
  })
}
