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



/** 工序计划实体（新增/修改/派工） */

export interface OrderProcessPlan {

  id?: number

  name?: string

  code?: string

  sort?: number

  orderItemId?: number

  beginTime?: string

  endTime?: string

  procurement?: number

  outsource?: number

  quantity?: number

  transferNum?: number

  transferOutNum?: number

  createTime?: string

  createBy?: string

  qualityInspection?: number

  storageEntry?: number

}



/** 派工明细 */

export interface AssignWorkItem {

  userId?: number | string

  quantity?: number | string

  assingStatus?: number

  [key: string]: unknown

}



/** 工序计划明细 VO（processList 项） */

export interface ProcessPlanItemVO {

  planId?: number

  workOrderCode?: string

  processCode?: string

  operNumber?: number

  workCenterName?: string

  departmentName?: string

  processName?: string

  operDescription?: string

  activityUnit?: string

  optCtrlCodeName?: string

  activityQty?: number

  planStartTime?: string

  planFinishTime?: string

  /** 计划开始（部分接口直接返回 beginTime） */
  beginTime?: string

  /** 计划结束（部分接口直接返回 endTime） */
  endTime?: string

  actualStartTime?: string | null

  actualFinishTime?: string | null

  quantity?: number

  transferInQty?: number

  transferOutQty?: number

  completedQty?: number

  scrapQty?: number

  reworkQty?: number

  procurement?: number

  outsource?: number

  qualityInspection?: number

  storageEntry?: number

  assign?: number

  assignByName?: string | null

  assignTime?: string | null

  processStatus?: number

  prevPlanId?: number | null

  nextPlanId?: number | null

  assignWorkList?: AssignWorkItem[]

}



/** 按生产订单分组的工序计划 VO（分页/详情） */

export interface OrderProcessPlanVO {

  orderItemId?: number

  mainCode?: string

  materialCode?: string

  materialName?: string

  orderCode?: string

  quantity?: number

  routeCode?: string

  proWorkshop?: string

  beginTime?: string

  endTime?: string

  actualStartTime?: string | null

  actualEndTime?: string | null

  completedQty?: number

  orderStatus?: number

  currentProcessName?: string

  currentOperNumber?: number

  processList?: ProcessPlanItemVO[]

}



export const ORDER_STATUS_MAP: Record<number, { label: string; type: 'default' | 'info' | 'success' | 'warning' | 'error' }> = {

  0: { label: '未开始', type: 'default' },

  1: { label: '进行中', type: 'info' },

  2: { label: '已完成', type: 'success' },

}



export const PROCESS_STATUS_MAP: Record<number, { label: string; type: 'default' | 'info' | 'success' | 'warning' | 'error' }> = {

  0: { label: '待派工', type: 'default' },

  1: { label: '待执行', type: 'info' },

  2: { label: '执行中', type: 'warning' },

  3: { label: '质检中', type: 'warning' },

  4: { label: '已完成', type: 'success' },

}



export const ASSIGN_STATUS_MAP: Record<number, { label: string; type: 'default' | 'info' | 'success' | 'warning' | 'error' }> = {

  1: { label: '待执行', type: 'info' },

  2: { label: '执行中', type: 'warning' },

  3: { label: '质检中', type: 'warning' },

  4: { label: '已汇报', type: 'success' },

  5: { label: '已关闭', type: 'default' },

}



/** 工序 VO 转实体（编辑/派工提交用） */

export function processItemToEntity(

  item: ProcessPlanItemVO,

  orderItemId?: number,

): OrderProcessPlan {

  return {

    id: item.planId,

    name: item.processName,

    code: item.processCode,

    sort: item.operNumber,

    orderItemId,

    beginTime: item.planStartTime || item.beginTime,

    endTime: item.planFinishTime || item.endTime,

    procurement: item.procurement,

    outsource: item.outsource,

    quantity: item.quantity,

    transferNum: item.transferInQty,

    transferOutNum: item.transferOutQty,

    qualityInspection: item.qualityInspection,

    storageEntry: item.storageEntry,
    
    workCenterName:item.workCenterName

  }

}



/** 提交前剔除展示字段，保留 OrderProcessPlan 实体 */

export function toOrderProcessPlanPayload(data: Record<string, unknown>): OrderProcessPlan {

  const payload = { ...data }

  const displayKeys = [

    'mainCode', 'materialCode', 'materialName', 'orderCode', 'routeCode', 'proWorkshop',

    'actualStartTime', 'actualEndTime', 'completedQty', 'orderStatus', 'currentProcessName',

    'currentOperNumber', 'processList', 'planId', 'processName', 'processCode', 'operNumber',

    'workCenterName', 'departmentName', 'operDescription', 'activityUnit', 'optCtrlCodeName',

    'activityQty', 'planStartTime', 'planFinishTime', 'actualFinishTime', 'transferInQty',

    'transferOutQty', 'scrapQty', 'reworkQty', 'assign', 'assignByName', 'assignTime',

    'processStatus', 'prevPlanId', 'nextPlanId', 'assignWorkList',

  ]

  for (const key of displayKeys) {

    delete payload[key]

  }

  return payload as OrderProcessPlan

}



// 工序计划 API

export const orderProcessPlanApi = {

  // 分页查询（按生产订单分组）

  page(params: {

    page: number

    pageSize: number

    id?: number | string

    name?: string

    code?: string

    orderItemId?: number | string

  }) {

    return request<{ list: OrderProcessPlanVO[]; total: number; page: number; pageSize: number }>({

      url: '/biz/orderProcessPlan/page',

      method: 'get',

      params,

    })

  },



  // 获取详情（路径参数为生产订单 id）

  detail(orderItemId: number | string) {

    return request<OrderProcessPlanVO>({

      url: `/biz/orderProcessPlan/${orderItemId}`,

      method: 'get',

    })

  },



  // 新增

  create(data: OrderProcessPlan) {

    return request({ url: '/biz/orderProcessPlan', method: 'post', data })

  },



  // 修改

  update(data: OrderProcessPlan) {

    return request({ url: '/biz/orderProcessPlan', method: 'put', data })

  },



  // 删除（工序计划 id）

  delete(ids: (number | string)[]) {

    return request({ url: `/biz/orderProcessPlan/${ids.join(',')}`, method: 'delete' })

  },



  // 派工

  assignWork(data: OrderProcessPlan & { list?: AssignWorkItem[] }) {

    return request({ url: '/biz/orderProcessPlan/assignWork', method: 'put', data })

  },



  // 导出

  export(params?: { ids?: string[]; id?: number; name?: string; code?: string; orderItemId?: number }) {

    const p: Record<string, unknown> = {}

    if (params?.ids?.length) p.ids = params.ids.join(',')

    if (params?.id !== undefined && params?.id !== null) p.id = params.id

    if (params?.name !== undefined && params?.name !== null) p.name = params.name

    if (params?.code !== undefined && params?.code !== null) p.code = params.code

    if (params?.orderItemId !== undefined && params?.orderItemId !== null) p.orderItemId = params.orderItemId

    return request({ url: '/biz/orderProcessPlan/export', method: 'get', params: p, responseType: 'blob' })

  },



  // 导入

  importData(file: File) {

    const formData = new FormData()

    formData.append('file', file)

    return request<{ success: number; fail: number; errors: string[] }>({

      url: '/biz/orderProcessPlan/import',

      method: 'post',

      data: formData,

      headers: { 'Content-Type': 'multipart/form-data' },

    })

  },



  // 下载导入模板

  downloadTemplate() {

    return request({ url: '/biz/orderProcessPlan/template', method: 'get', responseType: 'blob' })

  },

  /** 委外第一步：获取可选工序 */
  getOutsourcingOptions(processPlanId: number) {
    return request<OutsourcingOptions>({
      url: `/biz/orderProcessPlan/outsourcing/options/${processPlanId}`,
      method: 'get',
    })
  },

  /** 委外第二步：创建委外单 */
  createOutsourcing(data: OutsourcingCreate) {
    return request<number>({
      url: '/biz/orderProcessPlan/outsourcing',
      method: 'post',
      data,
    })
  },

}

/** 委外可选工序项 */
export interface OutsourcingProcessOption {
  planId?: number
  workOrderCode?: string
  processCode?: string
  operNumber?: number
  processName?: string
  quantity?: number
  outsource?: number
  planStartTime?: string
  planFinishTime?: string
  current?: boolean
}

/** 委外可选工序（第一步） */
export interface OutsourcingOptions {
  orderItemId?: number
  mainCode?: string
  materialCode?: string
  materialName?: string
  orderCode?: string
  quantity?: number
  currentProcessPlanId?: number
  processList?: OutsourcingProcessOption[]
}

/** 创建委外单（第二步） */
export interface OutsourcingCreate {
  processPlanId: number
  supplierId?: number
  supplierName: string
  quantity: number
  unitPrice?: number
  planStartTime?: string
  planEndTime?: string
  remark?: string
}

