import { http } from '@/api/request'
import type { FlowTask, ApprovalAction, NextNode } from '@/types/flow'
import type { PageQuery, PageResult } from '@/types/api'
import type { User } from '@/types/system'

export function listTodo(
  params?: PageQuery & { processName?: string; formFilters?: string; currentNodeId?: string }
): Promise<PageResult<FlowTask>> {
  return http.get('/flow/task/todo', { params })
}

export function listHandled(params?: PageQuery): Promise<PageResult<FlowTask>> {
  return http.get('/flow/task/handled', { params })
}

export function getTask(id: number): Promise<FlowTask> {
  return http.get(`/flow/task/${id}`)
}

export function approveTask(id: number, data: ApprovalAction): Promise<void> {
  return http.post(`/flow/task/${id}/approve`, data)
}

export function rejectTask(id: number, data: ApprovalAction): Promise<void> {
  return http.post(`/flow/task/${id}/reject`, data)
}

export function batchApproveTask(taskIds: number[], data: ApprovalAction): Promise<void> {
  return http.post('/flow/task/batch-approve', {
    taskIds,
    comment: data.comment,
    attachmentUrls: data.attachmentUrls,
    targetNodeId: data.targetNodeId,
  })
}

export function batchRejectTask(taskIds: number[], data: ApprovalAction): Promise<void> {
  return http.post('/flow/task/batch-reject', { taskIds, comment: data.comment, attachmentUrls: data.attachmentUrls })
}

export function returnTask(id: number, data: ApprovalAction): Promise<void> {
  return http.post(`/flow/task/${id}/return`, data)
}

export function transferTask(id: number, data: ApprovalAction): Promise<void> {
  return http.post(`/flow/task/${id}/transfer`, data)
}

export function todoCount(): Promise<number> {
  return http.get('/flow/task/todo-count')
}

export function addSignTask(taskId: number, assigneeId: number): Promise<void> {
  return http.post(`/flow/task/${taskId}/add-sign?assigneeId=${assigneeId}`)
}

export function listCc(params?: PageQuery): Promise<PageResult<FlowTask>> {
  return http.get('/flow/task/cc', { params })
}

export function readCc(taskId: number): Promise<void> {
  return http.post(`/flow/task/cc/${taskId}/read`)
}

export function listNextNodes(taskId: number): Promise<NextNode[]> {
  return http.get(`/flow/task/${taskId}/next-nodes`)
}

/** 获取可转办/加签的用户列表（按当前节点审批角色过滤） */
export function getTransferableUsers(taskId: number): Promise<User[]> {
  return http.get(`/flow/task/${taskId}/transferable-users`)
}
