import { request } from '@/api/request'

/**
 * 后端要求 status 为字符串数组；统一为 string[]（单选、逗号分隔写法也转成多项）。
 */
function normalizeTicketListStatusParam(params: Record<string, any>) {
  const raw = params.status
  if (raw === undefined || raw === null) return
  let arr: string[]
  if (Array.isArray(raw)) {
    arr = raw.map((s) => String(s).trim()).filter(Boolean)
  } else {
    const s = String(raw).trim()
    if (!s) {
      delete params.status
      return
    }
    arr = s.includes(',') ? s.split(',').map((x) => x.trim()).filter(Boolean) : [s]
  }
  if (arr.length === 0) delete params.status
  else params.status = arr
}

/** GET query：`status` 重复键 status=a&status=b（与后端 []string 绑定一致） */
function serializeFeedbackTicketListParams(params: Record<string, any>): string {
  const usp = new URLSearchParams()
  const keys = Object.keys(params).sort()
  for (const key of keys) {
    const value = params[key]
    if (value === undefined || value === null || value === '') continue
    if (key === 'status' && Array.isArray(value)) {
      for (const item of value) {
        const t = String(item).trim()
        if (t) usp.append('status', t)
      }
      continue
    }
    usp.append(key, String(value))
  }
  return usp.toString()
}

/** 避免 undefined / null / 空串进入 query（部分运行时下发异常键名） */
function stripEmptyQueryValues(params: Record<string, any>) {
  Object.keys(params).forEach((k) => {
    const v = params[k]
    if (v === undefined || v === null || v === '') {
      delete params[k]
    }
  })
}

/** 获取工单列表 GET /Feedback/v1/tickets（分页与多条件筛选） */
export const fetchFeedbackTickets = (data?: {
  page?: number
  page_size?: number
  size?: number
  /** 单状态、逗号分隔、或 string[]（将统一为数组并以重复 query 键序列化） */
  status?: string | string[]
  type?: string
  priority?: string
  creator_id?: number
  assignee_id?: number
  category_id?: number
  keyword?: string
  /** 格式 YYYY-MM-DD HH:MM:SS */
  start_time?: string
  /** 格式 YYYY-MM-DD HH:MM:SS */
  end_time?: string
}) => {
  const params: any = data ? { ...data } : {}
  if (params.size !== undefined && params.page_size === undefined) {
    params.page_size = params.size
    delete params.size
  }
  normalizeTicketListStatusParam(params)
  stripEmptyQueryValues(params)
  const config =
    Object.keys(params).length > 0
      ? {
          params,
          paramsSerializer: {
            serialize: (p: Record<string, any>) => serializeFeedbackTicketListParams(p),
          },
        }
      : undefined
  return request.get('/Feedback/v1/tickets', config)
}

/** 创建 工单 */
export const createFeedbackTicket = (data: any) => request.post("/Feedback/v1/tickets", data);

/** 更新 工单 */
export const updateFeedbackTicket = (id: number, data: any) => request.put(`/Feedback/v1/tickets/${id}`, data);

/** 删除 工单 */
export const deleteFeedbackTicket = (id: number) => request.delete(`/Feedback/v1/tickets/${id}`);

/** 获取 工单详情 */
export const fetchFeedbackTicketDetail = (id: number) => request.get(`/Feedback/v1/tickets/${id}`);

/** 根据工单编号获取详情 */
export const fetchFeedbackTicketByNo = (no: string) => request.get(`/Feedback/v1/tickets/no/${no}`);

/** 接单 */
export const acceptFeedbackTicket = (id: number) => request.post(`/Feedback/v1/tickets/${id}/accept`);

/** 转交 */
export const transferFeedbackTicket = (id: number, data: { assignee_id: number, assignee_name: string, reason?: string }) => request.post(`/Feedback/v1/tickets/${id}/transfer`, data);

/** 撤回 */
export const cancelFeedbackTicket = (id: number) => request.post(`/Feedback/v1/tickets/${id}/cancel`);

/** 挂起 */
export const suspendFeedbackTicket = (id: number, data: { content: string }) => request.post(`/Feedback/v1/tickets/${id}/suspend`, data);

/** 重启 */
export const resumeFeedbackTicket = (id: number) => request.post(`/Feedback/v1/tickets/${id}/resume`);

/** 解决 */
export const resolveFeedbackTicket = (id: number, data: { content: string }) => request.post(`/Feedback/v1/tickets/${id}/resolve`, data);

/** 关闭 */
export const closeFeedbackTicket = (id: number, data: { remarks?: string }) => request.post(`/Feedback/v1/tickets/${id}/close`, data);

/** 添加评论 */
export const commentFeedbackTicket = (id: number, data: { content: string }) => request.post(`/Feedback/v1/tickets/${id}/comment`, data);

/** 获取操作日志 */
export const fetchFeedbackTicketLogs = (id: number) => request.get(`/Feedback/v1/tickets/${id}/logs`);

/** 获取关联关系 */
export const fetchFeedbackTicketRelations = (id: number) => request.get(`/Feedback/v1/tickets/${id}/relations`);

/** 创建关联 */
export const createFeedbackTicketRelation = (id: number, data: { target_ticket_id: number, relation_type: string, description?: string }) => request.post(`/Feedback/v1/tickets/${id}/relations`, data);

/** 删除关联 */
export const deleteFeedbackTicketRelation = (relationId: number) => request.delete(`/Feedback/v1/tickets/relations/${relationId}`);

/** 获取 工单统计数据 */
export const fetchFeedbackTicketStatistics = () => request.get("/Feedback/v1/tickets/statistics");
