/** 将 commonComment/getListBySourceType 等接口的单条评论转为列表展示用结构（兼容旧 storeComment 模板字段） */
export function normalizeCommonCommentListItem(row: any): any {
  if (!row || typeof row !== "object") return row;
  const children = row.childCommonComments ?? row.storeComment ?? [];
  const normalizedChildren = Array.isArray(children) ? children.map(normalizeCommonCommentListItem) : [];
  return {
    ...row,
    userAvatar: row.userAvatar ?? row.headImg,
    userName: row.userName ?? row.headName ?? row.headPhone ?? "用户",
    commentContent: row.commentContent ?? row.content ?? "",
    isLiked: row.isLiked === true || row.isLiked === 1 || row.isLike === "1" || row.isLike === 1,
    userImage: row.userImage ?? row.headImg,
    storeComment: normalizedChildren
  };
}

/**
 * 解析列表接口 data：支持 data 为数组，或分页 records
 */
export function normalizeCommonCommentListResponse(resData: unknown): any[] {
  if (Array.isArray(resData)) return resData.map(normalizeCommonCommentListItem);
  const rec = (resData as { records?: unknown })?.records;
  if (Array.isArray(rec)) return rec.map(normalizeCommonCommentListItem);
  return [];
}

export function countTopAndNestedComments(list: { storeComment?: unknown[] }[]): number {
  return list.reduce((n, c) => n + 1 + (Array.isArray(c.storeComment) ? c.storeComment.length : 0), 0);
}
