import { normalizeKingdeeProcessRoute, type KingdeePrdMo, type KingdeeProcessRoute } from '@/api/orderProject'

export type KingdeeMoTableRow = Omit<KingdeePrdMo, 'children'> & { processRoutes: KingdeeProcessRoute[] }

export function mapKingdeeMoListToTableRows(data: KingdeePrdMo[]): KingdeeMoTableRow[] {
  return (Array.isArray(data) ? data : []).map((mo) => {
    const { children, ...rest } = mo
    const routes = [...(children ?? [])]
      .sort((a, b) => (a.operNumber ?? 0) - (b.operNumber ?? 0))
      .map((r) => normalizeKingdeeProcessRoute({
        ...r,
        planStartTime: r.planStartTime ?? null,
        planFinishTime: r.planFinishTime ?? null,
      }))
    return { ...rest, processRoutes: routes }
  })
}

export function tableRowsToKingdeeDraft(rows: KingdeeMoTableRow[]): KingdeePrdMo[] {
  return rows.map((mo) => {
    const { processRoutes, ...rest } = mo
    return { ...rest, children: processRoutes } as KingdeePrdMo
  })
}

function parsePlanTime(val: string | null | undefined): number | null {
  if (!val) return null
  const ts = new Date(val.replace(' ', 'T')).getTime()
  return Number.isNaN(ts) ? null : ts
}

export function validateKingdeeSchedule(rows: KingdeeMoTableRow[]): string[] {
  const errors: string[] = []
  if (!rows.length) {
    errors.push('没有可同步的生产订单数据')
    return errors
  }

  rows.forEach((mo, moIdx) => {
    const moLabel = mo.billNo || mo.productionOrderNo || `第 ${moIdx + 1} 条`
    const moStart = parsePlanTime(mo.planStartTime)
    const moEnd = parsePlanTime(mo.planFinishTime)
    if (moStart == null || moEnd == null) {
      errors.push(`生产订单 ${moLabel}：计划开工/完工时间未填写`)
    } else if (moEnd <= moStart) {
      errors.push(`生产订单 ${moLabel}：计划完工须晚于计划开工`)
    }

    const routes = mo.processRoutes ?? []
    if (!routes.length) {
      errors.push(`生产订单 ${moLabel}：没有工序计划`)
    }

    routes.forEach((route, ri) => {
      const routeLabel = route.operNumber ?? ri + 1
      const rStart = parsePlanTime(route.planStartTime)
      const rEnd = parsePlanTime(route.planFinishTime)
      if (rStart == null || rEnd == null) {
        errors.push(`生产订单 ${moLabel} 工序 ${routeLabel}：计划开始/结束时间未填写`)
      } else if (rEnd <= rStart) {
        errors.push(`生产订单 ${moLabel} 工序 ${routeLabel}：结束时间须晚于开始时间`)
      } else if (moStart != null && moEnd != null && (rStart < moStart || rEnd > moEnd)) {
        errors.push(`生产订单 ${moLabel} 工序 ${routeLabel}：计划时间超出生产订单时间范围`)
      }
    })
  })

  return errors
}
