import axios from './axios'
import type { BasePaginationData, BaseRespData } from '@/types/api'
import type {
  BatchManageData,
  FactoryOrderNewListData,
  LogListData,
  operateOrderListData,
  OrderInventoryData,
  PickCompleteData,
  ProductListData,
  RestockData,
  SearchForm,
  StatusTreeNode,
} from '@/types/api/factoryOrderNew'
import { ResultInfoDataItem } from '@/types/api/order/common'
import { ExportParams } from '@/types/api/order/factoryOrderNew'
import type { OrderData } from '@/types/api/podMakeOrder'
import type { LogisticsData } from '@/types/api/podCnOrder'
import type { PrintData } from '@/types/api/podOrder'
function normalizePodOrderQueryPayload(
  data: Record<string, unknown>,
): Record<string, unknown> {
  const { receiverCountry, ...rest } = data
  if (!Array.isArray(receiverCountry)) {
    return data
  }
  return {
    ...rest,
    ...(receiverCountry.length
      ? { receiverCountry: receiverCountry.join(',') }
      : {}),
  }
}

export function getPodOrderStateGroupListApi() {
  return axios.get<never, BaseRespData<StatusTreeNode[]>>(
    'factory/podOrder/findStateGroupList',
  )
}

export function getFactoryOrderNewListApi(
  data: SearchForm,
  currentPage: number,
  pageSize: number,
  status?: string,
  subStatus?: number,
  pauseReason?: number,
  cancelSubType?: number,
) {
  const body = normalizePodOrderQueryPayload({ ...data } as Record<
    string,
    unknown
  >)
  return axios.post<never, BasePaginationData<FactoryOrderNewListData>>(
    'factory/podOrder/list_page',
    {
      ...body,
      currentPage,
      pageSize,
      status,
      acceptedStatus: subStatus,
      pauseReason,
      cancelSubType,
    },
  )
}

/** 请求体与 `factory/podOrder/list_page` 一致 */
export function getPodOrderAcceptedStatisticsApi(
  data: SearchForm,
  currentPage: number,
  pageSize: number,
  status?: string,
  subStatus?: number,
) {
  return axios.post<
    never,
    BaseRespData<{
      acceptedOutOfStockCount?: number
      pendingCount?: number
      totalCount?: number
    }>
  >('factory/podOrder/acceptedStatistics', {
    ...normalizePodOrderQueryPayload({ ...data } as Record<string, unknown>),
    currentPage,
    pageSize,
    status,
    acceptedStatus: subStatus,
  })
}

export function getFactoryOrderNewDetailApi(id: number | string) {
  return axios.get<never, BaseRespData<ProductListData[]>>(
    'factory/podOrderProduct/getListByPodOrderId',
    {
      params: { id },
    },
  )
}

export function getFactoryOrderNewOperateDetailApi(id: number | string) {
  return axios.get<never, BaseRespData<operateOrderListData>>(
    'factory/podOrderOperation/get',
    {
      params: { id },
    },
  )
}

export function getFactoryOrderNewLogApi(id: number | string) {
  return axios.get<never, BaseRespData<LogListData[]>>(
    'factory/podOrderLog/getPodOrderLog',
    {
      params: { id },
    },
  )
}
export function getOperationOrderByIdApi(id: number | string) {
  return axios.get<never, BaseRespData<operateOrderListData[]>>(
    'factory/podOrderOperation/getByPodOrderId',
    {
      params: { podOrderId: id },
    },
  )
}

export function refreshProductInfoApi(data: {
  orderIds?: number | string
  productIds?: number | string
}) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrderProduct/refreshProductInfo',
    data,
  )
}

export function transferOldFlowApi(ids: (number | string)[]) {
  return axios.post<never, BaseRespData<void>>(
    'factory/orderNew/transferOldFlow',
    { ids },
  )
}

export function confirmOrderWithWarehouseApi(
  ids: (number | string)[],
  warehouseId: number | string,
  warehouseName: string,
) {
  return axios.post<never, BaseRespData<ResultInfoDataItem[]>>(
    'factory/podOrder/ordersAccepted',
    {
      podOrderIds: ids,
      warehouseId,
      warehouseName,
    },
  )
}

export function cancelOrderWithReasonApi(
  ids: (number | string)[],
  reason: string,
) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrder/cancelOrders',
    {
      podOrderIds: ids,
      cancelReason: reason,
    },
  )
}

export function suspendOrderApi(
  ids: (number | string)[],
  reason: string,
  pauseType: string,
) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrder/suspendOrders',
    {
      podOrderIds: ids,
      pauseReason: reason,
      pauseType,
    },
  )
}

export function cancelSuspendApi(ids: (number | string)[]) {
  return axios.post<never, BaseRespData<void>>('factory/podOrder/unSuspend', {
    podOrderIds: ids,
  })
}

export function archiveOrderApi(ids: number | string) {
  return axios.get<never, BaseRespData<void>>('factory/podOrder/archiving', {
    params: { ids },
  })
}

export function printPickOrderApi(ids: (number | string)[]) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrderOperation/printPickPdf',
    { ids: ids.join(',') },
  )
}

export function applyReplenishApi(ids: (number | string)[]) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrderOperation/applyForReplenishment',
    ids,
  )
}

export function batchDeleteApi(ids: (number | string)[]) {
  return axios.get<never, BaseRespData<never>>(
    'factory/podOrderBatchDownload/delete',
    {
      params: { ids: ids.join(',') },
    },
  )
}

export function restockCheckApi(
  factoryId: number | string,
  warehouseSku: string,
  warehouseId: number | string,
) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrder/outOfStock/autoMark',
    { factoryId, warehouseSku, warehouseId },
  )
}

/** 按仓库标记缺货：同一仓库一次请求，多个 SKU 传 warehouseSkuList */
export function markStockOutOfApi(data: {
  warehouseId: number | string
  warehouseSkuList: string[]
}) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrder/outOfStock/batchAutoMark',
    data,
  )
}

export function pickCompleteByIdsDataApi(ids: (number | string)[]) {
  return axios.post<
    never,
    BaseRespData<{
      overallMessage?: string
      pickingSituationList?: PickCompleteData[]
      allAvailableOrderIds?: number[]
      partialAvailableOrderIds?: number[]
      unavailableOrderIds?: number[]
    }>
  >('factory/podOrderOperation/getPickingSituation', ids)
}

export function pickCompleteApi(ids: (number | string)[]) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrderOperation/pickingComplete',
    ids,
  )
}

export function replenishmentCompleteApi(ids: (number | string)[]) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrderOperation/replenishmentComplete',
    ids,
  )
}

export function getCardLayoutListApi(
  data: Record<string, unknown>,
  currentPage: number,
  pageSize: number,
) {
  const body = normalizePodOrderQueryPayload({ ...data })
  return axios.post<never, BasePaginationData<FactoryOrderNewListData>>(
    'factory/podOrderOperation/list_page',
    { ...body, currentPage, pageSize },
  )
}

export function getSuspendListApi(
  data: SearchForm,
  currentPage: number,
  pageSize: number,
  pauseReason?: number,
) {
  const body = normalizePodOrderQueryPayload({ ...data } as Record<
    string,
    unknown
  >)
  return axios.post<never, BasePaginationData<FactoryOrderNewListData>>(
    'factory/podOrderPauseControl/list_page',
    { ...body, currentPage, pageSize, pauseReason },
  )
}

export function getSuspendStatisticsApi(
  data: SearchForm,
  currentPage: number,
  pageSize: number,
  pauseReason?: number,
) {
  const body = normalizePodOrderQueryPayload({ ...data } as Record<
    string,
    unknown
  >)
  return axios.post<never, BaseRespData<Record<string, number>>>(
    'factory/podOrderPauseControl/suspendStatistics',
    { ...body, currentPage, pageSize, pauseReason },
  )
}

/** 已取消列表子 tab 数量统计（与挂起 suspendStatistics 用法一致） */
export function getCancelledOrderStatisticsApi(
  data: SearchForm,
  currentPage: number,
  pageSize: number,
  cancelSubType?: number,
) {
  const body = normalizePodOrderQueryPayload({ ...data } as Record<
    string,
    unknown
  >)
  return axios.post<never, BaseRespData<Record<string, number>>>(
    'factory/podOrder/cancelledStatistics',
    { ...body, currentPage, pageSize, cancelSubType },
  )
}

export function getSuspendDetailApi(id: number | string) {
  return axios.get<never, BaseRespData<ProductListData[]>>(
    'factory/podOrderPauseControl/get',
    { params: { id } },
  )
}

export function getSuspendLogApi(id: number | string) {
  return axios.get<never, BaseRespData<LogListData[]>>(
    'factory/podOrderPauseControl/getLog',
    { params: { id } },
  )
}

export function getRestockListApi(
  data: Record<string, unknown>,
  currentPage: number,
  pageSize: number,
) {
  return axios.post<never, BasePaginationData<RestockData>>(
    'factory/podOrder/awaitingRestockListPage',
    { ...data, currentPage, pageSize },
  )
}

export function getBatchManageListApi(
  data: Record<string, unknown>,
  currentPage: number,
  pageSize: number,
) {
  return axios.post<never, BasePaginationData<BatchManageData>>(
    'factory/podOrderBatchDownload/list_page',
    { ...data, currentPage, pageSize },
  )
}
// 获取跟踪号
export function getTrackingNumberApi(orderIds: (string | number)[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/getTrackingNumber',
    orderIds,
  )
}
// 获取打印面单
export function getfaceSimplexFileApi(orderIds: (string | number)[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/getfaceSimplexFile',
    orderIds,
  )
}
// 取消物流订单
export function cancelLogisticsOrderApi(orderIds: (string | number)[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/cancelLogisticsOrder',
    orderIds,
  )
}

/** 待创建物流 → 待排单 */
export function updateLogisticsToArrangeApi(params: { ids: string }) {
  return axios.get<never, BaseRespData<unknown>>(
    'factory/podOrder/updateLogisticsToArrange',
    { params },
  )
}
export function arrangeFinishApi(params: {
  productIdList: number[]
  templateWidth?: number
  type?: string
}) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrderOperation/arrangeFinish',
    {
      operationIdList: params.productIdList,
      templateWidth: params.templateWidth,
      type: params.type,
    },
  )
}
export function batchDownloadDesignImagesApi(params: {
  id: number
  templateWidth?: number
  type?: string
}) {
  return axios.get<never, BaseRespData<never>>(
    'factory/podOrderBatchDownload/reComposingDesignImages',
    {
      params,
    },
  )
}

export function printPickPdfByBatchNumberApi(params: {
  batchArrangeNumber: string
}) {
  return axios.get<never, BaseRespData<never>>(
    `factory/podOrderOperation/printPickPdfByBatchNumber`,
    {
      params,
    },
  )
}
// 打印生产单item
export function printProductionPdfByBatchNumberApi(params: {
  batchArrangeNumber: string
}) {
  return axios.get<never, BaseRespData<never>>(
    `factory/podOrderOperation/printProductionPdfByBatchNumber`,
    {
      params,
    },
  )
}

export function downloadMaterialApi(id: number[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/downloadDesignImages',
    id,
  )
}

export function downloadOperationMaterialApi(id: number[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrderOperation/downloadDesignImages',
    id,
  )
}

export function downloadBatchMaterialApi(id: number | string, type?: string) {
  return axios.get<never, BaseRespData<never>>(
    'factory/podOrderBatchDownload/download',
    { params: { id, type } },
  )
}

export function composingNewPodOrderDesignImages(
  data: number[],
  type?: string,
  templateWidth?: number,
) {
  return axios.post<never, BaseRespData<never>>(
    `factory/podOrderOperation/replenishmentComposingDesignImages?type=${type}&templateWidth=${templateWidth}`,
    data,
  )
}

export function printNewPodOrderProductionOrderApi(ids: number[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrderOperation/printProducePdf',
    ids,
  )
}

export function syncReceiverAddress(data: number[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/syncReceiverAddress',
    data,
  )
}

export function getLogisticsCalculation(id: number) {
  return axios.get<never, BaseRespData<never>>(
    'factory/podOrder/getLogisticsCalculation',
    { params: { id } },
  )
}

export function changeLogisticsApi(params: {
  updateByIdParam: {
    id: string | number
    dataVersion: number
  }
  logisticsTrialCalculation: LogisticsData
}) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/changeLogistics',
    params,
  )
}

export function updateReceiverAddressApi(data: object) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/updateReceiverAddress',
    data,
  )
}

export function updateRemarkApi(id: number | string, remark: string) {
  return axios.post<never, BaseRespData<void>>(
    'factory/podOrderProduct/addRemark',
    { id, content: remark },
  )
}

export function applyForReplenishByIdApi(
  ids: (number | string)[],
  url: string,
) {
  return axios.post<never, BaseRespData<operateOrderListData[]>>(url, ids)
}

export function completeDeliveryApi(ids: (number | string)[]) {
  return axios.post<never, BaseRespData<ResultInfoDataItem[]>>(
    'factory/podOrderOperation/completeDelivery',
    ids,
  )
}

// 生产扫码
export function productionScanApi(id: number | string, status: string) {
  return axios.get<never, BaseRespData<never>>(
    'factory/podOrderOperation/scan-produce',
    { params: { id, status } },
  )
}

export function applyForProductByIdApi(id: string, url: string) {
  return axios.get<never, BaseRespData<operateOrderListData[]>>(url, {
    params: { podProductId: id },
  })
}

export function getByOperationNoLogApi(operationNo: string) {
  return axios.get<never, BaseRespData<operateOrderListData>>(
    'factory/podOrderOperation/getByOperationNoLog',
    {
      params: { operationNo },
    },
  )
}

// 校验库存
export function checkInventoryApi(id: number | string, status: string) {
  return axios.get<never, BaseRespData<never>>(
    'factory/podOrderOperation/check-inventory',
    { params: { id, status } },
  )
}
export function listByNoPodOrderApi(params: {
  type: string
  no: string
  logisticsCompanyCode?: string
}) {
  return axios.get<never, BaseRespData<never>>('factory/podOrder/listByNo', {
    params,
  })
}

export function orderWeighingPodOrderApi(params: unknown) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/orderWeighing',
    params as {
      podOrderWeighingParams: { id?: string; outWarehouseWeight?: string }[]
    },
  )
}

// 单件打单：根据 SKU/单号查询明细
export function getSingleQueryPodOrderApi(
  code: string,
  factoryNo: number,
  warehouseId: number | string,
) {
  return axios.get<never, BaseRespData<OrderData>>(
    'factory/podOrder/getDetailsBySkuOrNo',
    {
      params: {
        podOrderNo: code,
        factoryNo,
        warehouseId,
      },
    },
  )
}

// 单件打单完成
export function submitPodPrintOrderCompleteApi(
  data: { orderParamList: { id: number }[] },
  warehouseId: number | string,
  boxIndex: number | null = 0,
) {
  const params = new URLSearchParams()
  params.set('warehouseId', String(warehouseId))
  if (boxIndex !== undefined && boxIndex !== null) {
    params.set('box', String(boxIndex))
  }

  return axios.post<never, BaseRespData<never>>(
    `factory/podOrderPacking/podPrintOrderComplete?${params.toString()}`,
    data,
  )
}

export function statusPushApi(ids: (string | number)[]) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/statusPush',
    ids,
  )
}

export function batchCheckPrintPodOrder(ids: string) {
  return axios.get<never, BaseRespData<PrintData[]>>(
    `/factory/podOrder/batchCheckPrintPodOrder?operationIds=${ids}`,
  )
}

export function getCustomTagListPodOrderApi() {
  return axios.get<never, BaseRespData<never>>(
    `factory/podOrder/getCustomTagList`,
  )
}

export function exportFactoryOrderInfo(data: ExportParams) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/exportPodOrder',
    data,
  )
}

export function interceptUpdateApi(ids: (string | number)[]) {
  return axios.post<never, BaseRespData<ResultInfoDataItem[]>>(
    'factory/podOrder/factoryOrderUnblock',
    ids,
  )
}

export function interceptSuccessApi(
  data: { factoryOrderNumber: string; suspendSussessType: number }[],
) {
  return axios.post<never, BaseRespData<ResultInfoDataItem[]>>(
    'factory/podOrder/factoryOrderBlockSuccess',
    data,
  )
}

export function getOrderInventoryListApi(
  data: Record<string, unknown>,
  currentPage: number,
  pageSize: number,
) {
  return axios.post<never, BasePaginationData<OrderInventoryData>>(
    'factory/podOrder/outOfStock/stock-out-statistics',
    { ...data, currentPage, pageSize },
  )
}

export function exportOrderInventoryApi(data: Record<string, unknown>) {
  return axios.post<never, BaseRespData<never>>(
    'factory/podOrder/outOfStock/export-stock-out-statistics',
    data,
  )
}

// 配货完成 按钮
export function deliveryCompleteApi(data: { id: number; version?: number }[]) {
  return axios.post<never, BaseRespData<ResultInfoDataItem[]>>(
    'factory/podOrder/podPrintOrderShipmentComplete',
    { orderParamList: data },
  )
}
