import dayjs from "dayjs";
import { Request, Response } from "express";

export function filterObjEmptyVal(obj: { [key: string]: any }) {
  if (!obj) return {};
  if (Array.isArray(obj))
    throw Error("你传入了一个数组，需要的是一个Object对象");

  let emptyObj = {};

  for (let [key, value] of Object.entries(obj)) {
    if (value || value === 0) emptyObj[key] = value;
  }
  return emptyObj;
}

export function getNowDateStr() {
  return dayjs().format("YYYY-MM-DD HH:mm:ss");
}

export function buildTree(items, parentId = 0) {
  return items
    .filter((item) => item.parentId === parentId)
    .map((item) => ({
      ...item,
      children: buildTree(items, item.id),
    }));
}

export 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 function handleError(res: Response, error: any) {
  const message = error instanceof Error ? error.message : "未知错误";
  res.status(500).json({
    code: 500,
    msg: message,
  });
}

/** 处理日期参数 */
export default function parseRangDate(req: Request) {
  let { startDate: reqStart, endDate: reqEnd } =
    req.method === "GET" ? req.query : req.body;
  const dateFormat = "YYYY-MM-DD HH:mm:ss";

  if (!reqStart && !reqEnd) return {};

  // 验证必填参数
  if (!reqStart) reqStart = dayjs().startOf("day").toDate();

  // 处理起始日期
  const start = dayjs(reqStart as string, dateFormat);
  if (!start.isValid()) throw new Error("起始日期格式错误");

  // 处理结束日期
  let end = start;
  if (reqEnd) {
    end = dayjs(reqEnd as string, dateFormat);
    if (!end.isValid()) throw new Error("结束日期格式错误");
    if (end.isBefore(start)) throw new Error("结束日期不能早于起始日期");
  }

  // 生成时间范围

  return {
    startDate: start.format("YYYY-MM-DD HH:mm:ss"),
    endDate: (reqEnd ? end : dayjs()).format("YYYY-MM-DD HH:mm:ss"),
  };
}
