function isSameOrigin(url: string): boolean {
  try {
    return new URL(url).origin === window.location.origin;
  } catch {
    return false;
  }
}

/**
 * 获取全局的样式
 * @returns 样式
 */
export const getClassRules = (): string => {
  let rules = "";
  const { styleSheets } = document;
  for (let i = 0; i < styleSheets.length; i++) {
    const sheet = styleSheets[i];
    // 这里是为了过滤掉不同源 css 脚本，防止报错终止导出
    const ownerNode = sheet.ownerNode;
    // 处理同源或者内部css
    if (
      ownerNode instanceof HTMLStyleElement ||
      (ownerNode instanceof HTMLLinkElement && isSameOrigin(ownerNode.href))
    ) {
      try {
        for (let j = 0; j < sheet.cssRules.length; j++) {
          rules += sheet.cssRules[j].cssText;
        }
      } catch (error) {
        console.log(
          "CSS scripts from different sources have been filtered out"
        );
      }
    }
  }
  console.log("getClassRules", rules);
  return rules;
};

/**
 * base64 转 file
 * @param base64String
 * @param fileName
 * @param fileType
 * @returns
 */
export function base64ToFile(
  base64String: string,
  fileName: string,
  fileType: string
): File {
  // 移除Base64字符串中的前缀（如"data:image/png;base64,"）
  const base64Data = base64String.split(",")[1];

  // 解码Base64字符串
  const byteCharacters = atob(base64Data);

  // 创建一个Uint8Array来存储二进制数据
  const byteArrays = new Uint8Array(byteCharacters.length);

  for (let i = 0; i < byteCharacters.length; i++) {
    byteArrays[i] = byteCharacters.charCodeAt(i);
  }

  // 创建Blob对象
  const blob = new Blob([byteArrays], { type: fileType });

  // 创建File对象
  const file = new File([blob], fileName, { type: fileType });

  return file;
}

/* uuid */
export function uuid() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

/**
 * 获取日期格式化分组
 * @param dateVal 日期
 * @returns 
 */
export function getDateGroupString(dateVal: Date | string): string {
  const normalizeDate = (date: Date | string): Date => {
    const d = new Date(date);
    d.setHours(0, 0, 0, 0);
    return d;
  };

  const now = normalizeDate(new Date()); // 当前日期归一化

  const itemDate = normalizeDate(new Date(dateVal));
  const diffTime = now.getTime() - itemDate.getTime();
  const diffDays = Math.floor(diffTime / (1000 * 3600 * 24));

  if (diffDays === 0) {
    return "今日";
  } else if (diffDays === 1) {
    return "昨日";
  } else if (diffDays <= 6) {
    return "7日内";
  } else if (diffDays <= 29) {
    return "30日内";
  } else {
    return "更久~";
  }
}
