import { getConnection, Between } from "typeorm";
import { Request } from "express";

type paginationType<T> = {
  list: T[] | any[];
  total: number;
  pageSize: number;
  pageNumber: number;
};

const filterKeys = ["pwd"];
const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;

/**
 * 处理日期查询参数
 */
function processDateParams(params: { [key: string]: any }): {
  [key: string]: any;
} {
  const processed = {} as Record<string, any>;

  for (const [key, value] of Object.entries(params)) {
    if (typeof value === "string" && DATE_REGEX.test(value)) {
      // 处理日期范围
      const start = new Date(`${value}T00:00:00`);
      const end = new Date(`${value}T23:59:59`);
      processed[key] = Between(start, end);
    } else {
      processed[key] = value;
    }
  }

  return processed;
}

/**
 * 获取分页参数
 */
function getPaginationParams(req: Request): {
  pageSize: number;
  pageNumber: number;
} {
  const { pageSize = 10, pageNumber = 1 } =
    req.method === "GET" ? req.query : req.body;

  return {
    pageSize: Math.max(1, parseInt(pageSize as string, 10)),
    pageNumber: Math.max(1, parseInt(pageNumber as string, 10)),
  };
}

/**
 * 分页查询封装
 */
export default async function getPagination<T>(
  entity: Function,
  req: Request,
  queryParams?: { [key: string]: any }
): Promise<paginationType<T>> {
  try {
    const { pageSize, pageNumber } = getPaginationParams(req);
    const repository = getConnection().manager.getRepository(entity);

    // 处理日期查询参数
    const processedWhere = queryParams ? processDateParams(queryParams) : {};

    const [list, total] = await repository.findAndCount({
      where: processedWhere,
      order: { createDate: "DESC" },
      skip: (pageNumber - 1) * pageSize,
      take: pageSize,
    });

    // 过滤敏感字段
    list.forEach((item) => {
      filterKeys.forEach((key) => delete item[key]);
    });

    return { list, total, pageSize, pageNumber };
  } catch (err) {
    throw new Error(`分页查询出错: ${err.message}`);
  }
}
