const Server = require("../model/ServerModel");

export const compareVersions = (v1: string, v2: string) => {
  const parts1 = v1.split(".").map(Number);
  const parts2 = v2.split(".").map(Number);

  for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
    const num1 = parts1[i] || 0;
    const num2 = parts2[i] || 0;

    if (num1 > num2) return 1;
    if (num1 < num2) return -1;
  }

  return 0;
};

/**
 * 获取客户端真实IP地址
 * @param ctx Koa上下文对象
 * @returns 客户端IP地址
 */
export const getClientIp = (ctx) => {
  let ip = ctx.request.ip;

  // 处理IPv6格式的IPv4地址
  if (ip.startsWith("::ffff:")) {
    ip = ip.substring("::ffff:".length);
  }

  // 如果是本地地址，尝试从请求头获取真实IP
  if (ip === "127.0.0.1") {
    const forwardedIps = ctx.get("X-Forwarded-For")?.split(",");
    const clientIP = forwardedIps ? forwardedIps[0].trim() : null;
    // 若 X-Forwarded-For 不存在，尝试 X-Real-IP
    ip = clientIP || ctx.get("X-Real-IP") || ctx.ip;
  }

  return ip;
};

export const generateOrderNumber = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  const dateString = `${year}${month}${day}${hours}${minutes}${seconds}`;
  const randomString1 = Math.floor(Math.random() * 1090000000800)
    .toString()
    .slice(0, 4);
  const randomString2 = Math.floor(Math.random() * 1090000000800)
    .toString()
    .slice(0, 4);
  return "CP" + dateString + randomString1 + randomString2;
};

export const formatDate = (now: Date) => {
  const formattedDateTime =
    now.getFullYear() +
    "-" +
    (now.getMonth() + 1) +
    "-" +
    now.getDate() +
    " " +
    now.getHours() +
    ":" +
    now.getMinutes() +
    ":" +
    now.getSeconds();
  return formattedDateTime;
};

//根据区服id获取地址
export const getServerList = async (serverId, tag = 1) => {
  const servers = await Server.getServerList(tag);
  for (let i = 0; i < servers.length; i++) {
    // if (serverId == 999) {
    //   return "ws://" + servers[i].ip + ":9500";
    // }

    if (servers[i].sid == serverId) {
      return "ws://" + servers[i].ip + ":" + servers[i].port;
    }
  }
};

//根据区服id获取地址，内网调用
export const getServerAddr = async (serverId, tag = 1) => {
  const servers = await Server.getServerList(tag);
  for (let i = 0; i < servers.length; i++) {
    if (servers[i].sid == serverId) {
      return "ws://127.0.0.1:" + servers[i].port;
    }
  }
};
