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

// 项目表 类型定义
export interface OrderProject {
  id?: number

  name?:  string

  code?:  string

  mainCode?:  string

  mainName?:  string

  quantity?:  string

  source?: number

  prodType?: number

  sourceId?:  string

  bomVersion?:  string

  specModel?:  string

  unit?:  string

  customerName?:  string

  version?:  string

  salesDept?:  string

  parentId?: number

  deliveryTime?:  string

  status?: number

  planFinishTime?:  string

  createTime?:  string

  createBy?:  string

  changeTime?:  string

  changeBy?:  string

}

/** 金蝶生产订单（树父节点） */
export interface KingdeePrdMo {
  productionOrderNo: string
  billNo: string
  workShopName: string
  materialCode: string
  quantity: number | null
  specModel: string | null
  unit: string | null
  materialName: string | null
  routingNo: string | null
  planStartTime: string | null
  planFinishTime: string | null
  pickMtrlStatus: string | null
  children: KingdeeProcessRoute[]
}

/** 金蝶工艺路线工序（树子节点） */
export interface KingdeeProcessRoute {
  /** 工序号 FOperNumber */
  operNumber: number | null
  /** 工作中心 FWorkCenterId.FName */
  workCenterName: string | null
  /** 生产车间 FDepartmentId.FName */
  departmentName: string | null
  /** 工序名称 FProcessProperty */
  processName: string | null
  /** 工序说明 FOperDescription */
  operDescription: string | null
  /** 活动单位 FActivity1UnitID.FName */
  activityUnit: string | null
  /** 工序控制码 FOptCtrlCodeId.FName */
  optCtrlCodeName: string | null
  /** 活动量 FActivity1Qty */
  activityQty: number | null
  /** 计划开始时间 yyyy-MM-dd HH:mm:ss */
  planStartTime: string | null
  /** 计划结束时间 yyyy-MM-dd HH:mm:ss */
  planFinishTime: string | null
}

/** 解析工序名称，兼容旧字段及后端误映射 */
export function resolveProcessName(route: Partial<KingdeeProcessRoute> & { processProperty?: string | null }) {
  const legacyName = typeof route.processProperty === 'string' ? route.processProperty.trim() : ''
  const processName = route.processName?.trim() || legacyName || ''
  const operDescription = route.operDescription?.trim() || ''

  if (processName) return processName
  // 兼容：FProcessProperty 被写入 operDescription 而 processName 为空
  if (operDescription) return operDescription
  return ''
}

/** 归一化金蝶工序字段，保证 processName / operDescription 各归其位 */
export function normalizeKingdeeProcessRoute(
  route: KingdeeProcessRoute & { processProperty?: string | null }
): KingdeeProcessRoute {
  const legacyName = typeof route.processProperty === 'string' ? route.processProperty.trim() : ''
  const processName = route.processName?.trim() || legacyName || ''
  const operDescription = route.operDescription?.trim() || ''

  if (processName) {
    return { ...route, processName, operDescription: operDescription || null }
  }
  if (operDescription) {
    return { ...route, processName: operDescription, operDescription: null }
  }
  return { ...route, processName: null, operDescription: null }
}

// 项目表 API
export const orderProjectApi = {
  // 分页查询
  page(params: { page: number; pageSize: number; id?: number; name?:  string; status?: number }) {
    return request({ url: '/biz/orderProject/page', method: 'get', params })
  },

  // 获取详情
  detail(id:  string) {
    return request({ url: `/biz/orderProject/${id}`, method: 'get' })
  },

  // 新增
  create(data: OrderProject) {
    return request({ url: '/biz/orderProject', method: 'post', data })
  },

  // 修改
  update(data: OrderProject) {
    return request({ url: '/biz/orderProject', method: 'put', data })
  },

  // 删除
  delete(ids:  string[]) {
    return request({ url: `/biz/orderProject/${ids.join(',')}`, method: 'delete' })
  },

  // 导出
  export(params?: { ids?:  string[]; id?: number; name?:  string; status?: number }) {
    const p: Record<string, any> = {}
    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?.status !== undefined && params?.status !== null) p.status = params.status
    return request({ url: `/biz/orderProject/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/orderProject/import`,
      method: 'post',
      data: formData,
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },

  // 下载导入模板
  downloadTemplate() {
    return request({ url: `/biz/orderProject/template`, method: 'get', responseType: 'blob' })
  },

  // 查询金蝶生产订单 (支持优先读取本地暂存)
  getKingdeeOrder(id: number, params:any) {
    return request<KingdeePrdMo[]>({ url: `/biz/orderProject/kingdee/order/${id}`, method: 'get', params })
  },
  
  // 暂存金蝶生产订单数据（草稿）
  saveKingdeeOrderDraft(id: number, data: KingdeePrdMo[]) {
    return request({ url: `/biz/orderProject/kingdee/order/${id}/draft`, method: 'post', data })
  },
  
  // 同步订单和计划表
  saveKingdeeOrderAndPlan(id: number, data: KingdeePrdMo[]) {
    return request({ url: `/biz/orderProject/kingdee/order/${id}/saveOrderAndPlan`, method: 'post', data })
  },
}
