import request from '@/utils/request'

export interface MessageVO {
  msgId?: number
  sessionId: number
  msgNo: string
  senderType?: number
  senderId?: number
  senderName?: string
  senderAvatar?: string
  msgType: string
  content?: string
  fileUrl?: string
  fileName?: string
  fileSize?: number
  payload?: any
  sendTime?: string
  isRead?: number
}

export interface MessageQuery {
  sessionId: number
  pageNum: number
  pageSize: number
  beforeMsgId?: number
}

export const getMessageHistory = (query: MessageQuery) => {
  return request({
    url: '/main/message/history',
    method: 'get',
    params: query
  })
}

export const sendTextMessage = (data: Partial<MessageVO>) => {
  return request({
    url: '/main/message/send/text',
    method: 'post',
    data
  })
}

export const sendImageMessage = (sessionId: number, msgNo: string, file: File, senderId?: number) => {
  const formData = new FormData()
  formData.append('sessionId', sessionId.toString())
  formData.append('msgNo', msgNo)
  formData.append('file', file)
  if (senderId) {
    formData.append('senderId', senderId.toString())
  }
  return request({
    url: '/main/message/send/image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export const sendFileMessage = (sessionId: number, msgNo: string, file: File, senderId?: number) => {
  const formData = new FormData()
  formData.append('sessionId', sessionId.toString())
  formData.append('msgNo', msgNo)
  formData.append('file', file)
  if (senderId) {
    formData.append('senderId', senderId.toString())
  }
  return request({
    url: '/main/message/send/file',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export const sendJobCard = (data: Partial<MessageVO>) => {
  return request({
    url: '/main/message/send/job-card',
    method: 'post',
    data
  })
}

export const sendOrderCard = (data: Partial<MessageVO>) => {
  return request({
    url: '/main/message/send/order-card',
    method: 'post',
    data
  })
}

export const markMessageRead = (sessionId: number, lastReadMsgId: number) => {
  return request({
    url: '/main/message/read',
    method: 'put',
    data: { sessionId, lastReadMsgId }
  })
}
