import { http } from '@/utils/request'

// 工单详情接口
export interface WorkOrderDetail {
  id: string
  orderNo: string
  statusName: string
  status: string
  createBy: string
  ticketTypeName: string
  createTime: string
  stationName?: string
  contact?: string
  phone?: string
  content?: string
  attachments?: string
  attachmentsUrl?: string[]
}

// 工单流程记录接口
export interface WorkOrderRecord {
  id: string
  orderId: string
  operationContent: string
  status: string
  operatorName: string
  operationTime: string
  operationType: string
  approveName?: string
  workOrderProcessRecords?: Array<{
    processContent: string
    attachmentsUrl?: string
  }>
  workOrderDelay?: Array<{
    delayReason: string
    delayDuration: string
    approveRemark: string
    approveStatus: string
    approveTime: string
    attachmentsUrl?: string
  }>
  message?: string
}

// 获取工单详情
export async function getWorkOrderDetail(id: string): Promise<WorkOrderDetail> {
  const response = await http.get<WorkOrderDetail>(`/workOrder/order/${id}`)
  return response || {}
}

// 获取工单流程记录
export async function getWorkOrderRecords(orderId: string): Promise<WorkOrderRecord[]> {
  const response = await http.get<WorkOrderRecord[]>('/workOrderRecord/record/list', {
    orderId: orderId
  })
  return response.rows || []
}

// 处理工单
export async function handleWorkOrder(params: {
  taskId: string
  processContent: string
  attachments: string
}): Promise<any> {
  return await http.put('/workOrder/order/handle', params)
}

// 延时申请
export async function delayWorkOrder(params: {
  taskId: string
  delayDuration: string
  delayReason: string
  applyFile: string
}): Promise<any> {
  return await http.put('/workOrder/order/delay', params)
}

// 抄送工单
export async function ccWorkOrder(params: {
  taskId: string
  ccUserIds: string
}): Promise<any> {
  return await http.put('/workOrder/order/cc', params)
}

// 退回工单
export async function backWorkOrder(taskId: string): Promise<any> {
  return await http.post('/workflow/task/backProcess', {
    taskId: taskId
  })
}

// 编辑工单
export function editWorkOrder(id: string): void {
  uni.navigateTo({
    url: '/pages/archive/order/creatOrder?id=' + id
  })
}

// 删除工单
export async function deleteWorkOrder(id: string): Promise<any> {
  return await http.delete(`/workOrder/order/${id}`)
}

// 提交工单
export async function submitWorkOrder(id: string): Promise<any> {
  return await http.put(`/workOrder/order/submit/${id}`)
}

export async function approveDelayWorkOrder(params: {
  delayId: string
  approveStatus: number
  approveRemark: string
  newDeadline: string
}): Promise<any> {
  return await http.put('/workOrder/order/approveDelay', {
    delayId: params.delayId,
    approveStatus: params.approveStatus,
    approveRemark: params.approveRemark,
    newDeadline: params.newDeadline
  })
}
