export const STATUS_LABELS = {
  ACTIVE: "启用",
  ENABLED: "启用",
  INACTIVE: "停用",
  DISABLED: "停用",
  OPEN: "未开始",
  NEW: "新建",
  DRAFT: "草稿",
  SUBMITTED: "已提交",
  APPROVED: "已审批",
  PARTIAL: "部分完成",
  PARTIAL_RECEIVED: "部分收货",
  CLOSED: "已关闭",
  CANCELED: "已取消",
  CANCELLED: "已取消",
  ORDERED: "已下单",
  RECEIVED: "已收货",
  RELEASED: "已下达",
  IN_PROGRESS: "进行中",
  READY_TO_RECEIPT: "待成品入库",
  COMPLETED: "已完工",
  SETTLED: "已结单",
  DONE: "已完成",
  PENDING: "待处理",
  PENDING_QC: "待质检",
  PASSED: "已放行",
  REJECTED: "已拒收",
  POSTED: "已过账",
  AVAILABLE: "可用",
  LOCKED: "已锁单",
  DEPLETED: "已耗尽",
  CONFIRMED: "已确认",
  OVERRIDDEN: "已覆盖",
  CREATED: "已创建",
  IDLE: "空闲",
  READY: "就绪",
  ERROR: "异常",
  FAILED: "失败",
  EXPORTED: "已导出",
  IMPORTED: "已导入",
  SUPERSEDED: "已替代",
  MINIAPP_ONLY: "小程序清单",
  HAS_RETURN: "存在退货"
};

export const BOM_USAGE_LABELS = {
  WEIGHT: "重量"
};

export const PURCHASE_CALC_MODE_LABELS = {
  BY_WEIGHT: "按重量采购"
};

export const QUALITY_STATUS_LABELS = {
  PENDING_QC: "待质检",
  PASS: "已放行",
  PASSED: "已放行",
  REJECT: "已拒收",
  REJECTED: "已拒收",
  REWORK: "返工中",
  SCRAP: "已报废",
  PENDING: "待处理"
};

export const DISPOSAL_TYPE_LABELS = {
  SCRAP: "报废",
  REWORK: "返工"
};

export const INVENTORY_TXN_TYPE_LABELS = {
  OPENING_IN: "期初入库",
  PURCHASE_IN: "采购入库",
  CUSTOMER_SUPPLIED_IN: "客供料入库",
  MATERIAL_ISSUE: "生产领料",
  PRODUCTION_OUT: "生产出库",
  PRODUCTION_SURPLUS_IN: "生产余料入库",
  OUTSOURCING_SURPLUS_IN: "委外余料入库",
  WIP_IN: "产中入库",
  WIP_OUT: "产中出库",
  OUTSOURCING_IN: "委外入库",
  OUTSOURCING_OUT: "委外出库",
  PRODUCTION_FINISHED_IN: "生产入库",
  REWORK_FINISHED_IN: "返工入库",
  FG_IN: "成品入库",
  SALES_OUT: "发货出库",
  SCRAP_OUT: "报废出库",
  PRODUCTION_SCRAP_IN: "生产废料入库",
  REWORK_SCRAP_IN: "返工废料入库",
  OUTSOURCING_SCRAP_IN: "委外废料入库",
  SCRAP_SALE_OUT: "废料售卖出库",
  PURCHASE_RETURN_OUT: "采购退货出库",
  RETURN_IN: "退货入库",
  RETURN_SCRAP_IN: "退货废料入库",
  RETURN_OUT: "返工出库",
  STOCKTAKE_GAIN: "盘库盘盈",
  STOCKTAKE_LOSS: "盘库盘亏",
  STOCKTAKE_NEW_LOT: "盘库新增批次"
};

export const SOURCE_DOC_TYPE_LABELS = {
  OPENING_STOCK: "期初入库",
  PURCHASE_RECEIPT: "采购到货",
  PURCHASE_ORDER: "采购订单",
  CUSTOMER_SUPPLIED_IN: "客供料入库",
  WORK_ORDER: "生产工单",
  FG_RECEIPT: "成品入库",
  DELIVERY: "发货单",
  SALES_ORDER: "销售订单",
  PRODUCTION_OUT: "生产出库",
  PRODUCTION_SURPLUS_IN: "生产余料入库",
  OUTSOURCING_SURPLUS_IN: "委外余料入库",
  WIP_IN: "产中入库",
  WIP_OUT: "产中出库",
  OUTSOURCING_IN: "委外入库",
  OUTSOURCING_OUT: "委外出库",
  PRODUCTION_FINISHED_IN: "生产入库",
  REWORK_RECEIPT: "返工入库",
  REWORK_SCRAP_IN: "返工废料入库",
  SCRAP_OUT: "报废出库",
  PRODUCTION_SCRAP_IN: "生产废料入库",
  OUTSOURCING_SCRAP_IN: "委外废料入库",
  SCRAP_SALE_OUT: "废料售卖出库",
  PURCHASE_RETURN: "采购退货",
  RETURN_ORDER: "客户退货",
  RETURN_DISPOSITION: "退货处置",
  RETURN_OUT: "返工出库",
  STOCKTAKE: "盘库",
  STOCKTAKE_ADJUSTMENT: "盘库调整"
};

export const WAREHOUSE_TYPE_LABELS = {
  RAW: "原材料库",
  SEMI: "半成品库",
  FINISHED: "成品库",
  AUX: "辅料库",
  SCRAP: "废料库",
  RETURN: "退货库"
};

export const ITEM_TYPE_LABELS = {
  RAW_MATERIAL: "原材料",
  FINISHED_GOOD: "成品",
  PRODUCT: "产品",
  SEMI_FINISHED: "半成品",
  AUXILIARY: "辅料",
  CONSUMABLE: "辅料",
  SCRAP: "废料",
  SPARE_PART: "备件"
};

export const PURCHASE_SOURCE_TYPE_LABELS = {
  SALES_ORDER: "销售订单采购",
  STOCKING: "备料采购"
};

export const MAINTENANCE_TYPE_LABELS = {
  PERIODIC: "周期保养",
  PREVENTIVE: "周期保养",
  ROUTINE: "例行保养",
  REPAIR: "维修保养",
  INSPECTION: "点检保养",
  EMERGENCY: "紧急维修",
  MOULD: "模具保养",
  MOLD: "模具保养"
};

export const MINIAPP_ROLE_LABELS = {
  WORKER: "员工",
  MANAGER: "经理",
  ADMIN: "管理员"
};

export const STOCKTAKE_ROW_STATUS_LABELS = {
  READY: "可确认",
  ERROR: "异常",
  IGNORED: "已忽略"
};

export const DASHBOARD_NODE_TYPE_LABELS = {
  RAW_MATERIAL_LOT: "原材料库存批次",
  MATERIAL_ISSUE_BATCH: "生产出库批次",
  WORK_ORDER: "生产工单",
  WORK_ORDER_OPERATION: "工单工序",
  OPERATION_REPORT: "工序报工",
  COMPLETION_RECEIPT: "成品入库",
  DELIVERY: "销售出库",
  SALES_ORDER: "销售订单",
  SALES_ORDER_ITEM: "销售订单明细",
  MRP_DEMAND: "物料需求",
  PURCHASE_ORDER_ITEM: "采购订单明细",
  PURCHASE_RECEIPT_ITEM: "到货入库明细",
  SCRAP_REWORK: "报废返工",
  RETURN: "客户退货",
  RETURN_DISPOSITION: "退货处置"
};

export function normalizeDictionaryKey(value) {
  return String(value ?? "").trim().toUpperCase();
}

export function isEnumLikeValue(value) {
  const text = String(value ?? "").trim();
  return /^[A-Z][A-Z0-9_]*$/.test(text) || /^[a-z][a-z0-9_]*$/.test(text);
}

export function dictionaryFallback(value, fallback = "-", unknownLabel = "未识别类型") {
  if (value === null || value === undefined || value === "") {
    return fallback;
  }
  return isEnumLikeValue(value) ? unknownLabel : String(value);
}

export function getLabel(map, value, fallback = "-", unknownLabel = "未识别类型") {
  if (value === null || value === undefined || value === "") {
    return fallback;
  }
  const key = normalizeDictionaryKey(value);
  return map[key] || map[value] || dictionaryFallback(value, fallback, unknownLabel);
}

export function formatStatusLabel(value) {
  return getLabel(STATUS_LABELS, value, "-", "未识别状态");
}

export function formatUsageTypeLabel(value) {
  return getLabel(BOM_USAGE_LABELS, value, "-", "未识别用量类型");
}

export function formatPurchaseCalcModeLabel(value) {
  return getLabel(PURCHASE_CALC_MODE_LABELS, value, "-", "未识别采购方式");
}

export function formatQualityStatusLabel(value) {
  return getLabel(QUALITY_STATUS_LABELS, value, "-", "未识别质检状态");
}

export function formatDisposalTypeLabel(value) {
  return getLabel(DISPOSAL_TYPE_LABELS, value, "-", "未识别处置方式");
}

export function formatInventoryTxnTypeLabel(value) {
  return getLabel(INVENTORY_TXN_TYPE_LABELS, value, "-", "未识别流水类型");
}

export function formatSourceDocTypeLabel(value) {
  return getLabel(SOURCE_DOC_TYPE_LABELS, value, "-", "未识别来源");
}

export function formatWarehouseTypeLabel(value) {
  return getLabel(WAREHOUSE_TYPE_LABELS, value, "-", "未识别仓库");
}

export function formatItemTypeLabel(value) {
  return getLabel(ITEM_TYPE_LABELS, value, "-", "未识别物料类型");
}

export function formatPurchaseSourceTypeLabel(value) {
  return getLabel(PURCHASE_SOURCE_TYPE_LABELS, value, "-", "未识别采购来源");
}

export function formatMaintenanceTypeLabel(value) {
  return getLabel(MAINTENANCE_TYPE_LABELS, value, "-", "未识别保养类型");
}

export function formatMiniappRoleLabel(value) {
  return getLabel(MINIAPP_ROLE_LABELS, value, "-", "未识别角色");
}

export function formatStocktakeRowStatusLabel(value) {
  return getLabel(STOCKTAKE_ROW_STATUS_LABELS, value, "-", "未识别行状态");
}

export function formatDashboardNodeTypeLabel(value) {
  return getLabel(DASHBOARD_NODE_TYPE_LABELS, value, "-", "未识别节点类型");
}

export function formatStocktakeStatusLabel(status) {
  return {
    LOCKED: "盘库中",
    EXPORTED: "已导出",
    IMPORTED: "已导入",
    CONFIRMED: "已确认",
    CANCELED: "已取消"
  }[normalizeDictionaryKey(status)] || dictionaryFallback(status, "-", "未识别盘库状态");
}

export function formatStocktakeDiffTypeLabel(type) {
  return {
    MATCH: "一致",
    GAIN: "盘盈",
    LOSS: "盘亏",
    NEW_LOT: "新增批次",
    MISSING: "缺失批次"
  }[normalizeDictionaryKey(type)] || dictionaryFallback(type, "-", "未识别差异类型");
}

export function formatProductLabel(product) {
  if (!product) {
    return "-";
  }
  const code = product.item_code || product.product_code;
  const name = product.item_name || product.product_name;
  const version = product.version_no || product.product_version_no;
  const parts = [code, name];
  if (version) {
    parts.push(version);
  }
  return parts.filter(Boolean).join(" · ");
}

export function formatBomLabel(bom) {
  if (!bom) {
    return "-";
  }
  return [bom.bom_code, bom.version_no].filter(Boolean).join(" · ");
}

export function formatRouteLabel(route) {
  if (!route) {
    return "-";
  }
  return [route.route_code, route.route_name, route.version_no].filter(Boolean).join(" · ");
}

export function buildVersionedRows(rows, { codeKey, idKey }) {
  const groups = new Map();

  rows.forEach((row) => {
    const code = row[codeKey];
    if (!groups.has(code)) {
      groups.set(code, []);
    }
    groups.get(code).push(row);
  });

  return Array.from(groups.entries())
    .map(([code, versionRows]) => {
      const sortedRows = [...versionRows].sort((a, b) => Number(b[idKey] || 0) - Number(a[idKey] || 0));
      const activeRow = sortedRows.find((row) => row.is_default) || sortedRows[0];
      return {
        code,
        active_id: activeRow?.[idKey],
        rows: sortedRows
      };
    })
    .sort((a, b) => String(a.code || "").localeCompare(String(b.code || ""), "zh-CN", { numeric: true }));
}
