import request from '@/utils/request'
import type {
  Ticket,
  TicketReply,
  TicketSubmitForm,
  TicketReplyForm,
  TicketAssignForm,
  TicketStatusForm,
  TicketQueryParams,
  TicketStats,
} from './model'

const BASE = '/api/app/ticket'

/** 分页查询工单列表（客户端：查自己的） */
export async function getMyTickets(params: TicketQueryParams) {
  return request.get<{ list: Ticket[]; count: number }>(`${BASE}/my`, { params })
}

/** 分页查询工单列表（技术人员：查所有/分配给自己的） */
export async function getAllTickets(params: TicketQueryParams) {
  return request.get<{ list: Ticket[]; count: number }>(`${BASE}/list`, { params })
}

/** 获取工单详情 */
export async function getTicketDetail(ticketId: number) {
  return request.get<Ticket>(`${BASE}/${ticketId}`)
}

/** 提交工单 */
export async function submitTicket(data: TicketSubmitForm) {
  return request.post<Ticket>(`${BASE}/submit`, data)
}

/** 更新工单状态（技术人员） */
export async function updateTicketStatus(data: TicketStatusForm) {
  return request.put(`${BASE}/status`, data)
}

/** 分配工单给技术人员（管理员） */
export async function assignTicket(data: TicketAssignForm) {
  return request.put(`${BASE}/assign`, data)
}

/** 关闭工单（提交人） */
export async function closeTicket(ticketId: number) {
  return request.put(`${BASE}/${ticketId}/close`)
}

/** 获取工单回复列表 */
export async function getTicketReplies(ticketId: number) {
  return request.get<TicketReply[]>(`${BASE}/${ticketId}/replies`)
}

/** 提交工单回复 */
export async function replyTicket(data: TicketReplyForm) {
  return request.post(`${BASE}/reply`, data)
}

/** 获取工单统计 */
export async function getTicketStats(params?: { productId?: number }) {
  return request.get<TicketStats>(`${BASE}/stats`, { params })
}

/** 获取技术人员列表（用于分配） */
export async function getTechStaffList() {
  return request.get<{ userId: number; nickname: string; avatar: string }[]>(`${BASE}/staff-list`)
}
