import request from '@/config/axios'

export interface MaterialRequisitionVO {
  id: number
  code: string
  orderId: number
  orderCode: string
  requisitionTime: string
  status: number
  remark?: string
  items: MaterialRequisitionItemVO[]
  applicantId?: number
  applicantName?: string
  approverId?: number
  approverName?: string
  createTime: string
  updateTime: string
  creator: string
  updater: string
}

export interface MaterialRequisitionItemVO {
  id?: number
  materialId: number
  materialCode: string
  materialName: string
  unit: string
  planQuantity: number
  actualQuantity?: number
  warehouseId: number
  warehouseName: string
  remark?: string
}

// 查询生产领料分页
export const getMaterialRequisitionPage = async (params: any) => {
  return await request.get({ url: '/mes/material-requisition/page', params })
}

// 查询生产领料详情
export const getMaterialRequisition = async (id: number) => {
  return await request.get({ url: '/mes/material-requisition/get', params: { id } })
}

// 新增生产领料
export const createMaterialRequisition = async (data: any) => {
  return await request.post({ url: '/mes/material-requisition/create', data })
}

// 修改生产领料
export const updateMaterialRequisition = async (data: any) => {
  return await request.put({ url: '/mes/material-requisition/update', data })
}

// 删除生产领料
export const deleteMaterialRequisition = async (id: number) => {
  return await request.delete({ url: '/mes/material-requisition/delete', params: { id } })
}

// 提交生产领料审核
export interface MaterialRequisitionSubmitReqVO {
  id: number
  applicantId: number
  applicantName: string
}

export const submitMaterialRequisition = async (submitReqVO: MaterialRequisitionSubmitReqVO) => {
  return await request.put({
    url: '/mes/material-requisition/submit',
    data: submitReqVO
  })
}

// 审核生产领料
export const approveMaterialRequisition = async (data: {
  id: number
  approved: boolean
  approverId: number
  approverName: string
  remark?: string
}) => {
  return await request.put({
    url: '/mes/material-requisition/approve',
    data
  })
}

// 确认领料完成
export const completeMaterialRequisition = async (data: {
  id: number
  items: { id: number; actualQuantity: number; remark?: string }[]
}) => {
  const { id, items } = data
  return await request.put({
    url: '/mes/material-requisition/complete',
    params: { id },
    data: items
  })
}

// 反审核生产领料
export const reverseMaterialRequisition = async (data: {
  id: number
  reverserId: number
  reverserName: string
  remark?: string
}) => {
  return await request.put({
    url: '/mes/material-requisition/reverse',
    data
  })
}

// 取消生产领料
export const cancelMaterialRequisition = async (data: { id: number; remark: string }) => {
  const { id, remark } = data
  return await request.put({
    url: '/mes/material-requisition/cancel',
    params: { id },
    data: { remark }
  })
}
