// 工单（对齐 PC /developer/tickets 与 /admin/tickets，基址走 websopy-api）
import { get, post } from '@/utils/request'
import { WebsopyBaseUrl } from '@/config/app'

const BASE = '/app/ticket'

export interface Ticket {
  ticketId?: number
  ticketNo?: string
  title?: string
  productId?: number
  productName?: string
  status?: string
  priority?: string
  category?: string
  assigneeName?: string
  submitUserName?: string
  replyCount?: number
  hasUnread?: boolean
  createTime?: string
  [key: string]: any
}

export async function getMyTickets(params: any) {
  const res = await get<any>(`${BASE}/my`, params, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

export async function getAllTickets(params: any) {
  const res = await get<any>(BASE, params, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

export async function getTicketDetail(id: number) {
  const res = await get<any>(`${BASE}/${id}`, undefined, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

export async function getTicketReplies(id: number) {
  const res = await get<any>(`${BASE}/${id}/replies`, undefined, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

export async function submitTicket(data: any) {
  const res = await post<any>(BASE, data, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '提交失败'))
}

export async function replyTicket(id: number, content: string) {
  const res = await post<any>(`${BASE}/${id}/reply`, { content }, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '回复失败'))
}

export async function updateTicketStatus(id: number, status: string) {
  const res = await post<any>(`${BASE}/${id}/status`, { status }, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.message
  return Promise.reject(new Error(res?.message || '操作失败'))
}

export async function assignTicket(id: number, assigneeId: number) {
  const res = await post<any>(`${BASE}/${id}/assign`, { assigneeId }, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.message
  return Promise.reject(new Error(res?.message || '操作失败'))
}

export async function getTicketStats() {
  const res = await get<any>(`${BASE}/stats`, undefined, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

export async function getTechStaffList() {
  const res = await get<any>(`${BASE}/staffs`, undefined, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}
