export * from "./hander";
import { AddGraph } from "@/api/systemDesigner";
import { GraphType } from "@/enum";

/**
 * 打印图片
 * @param imgUri 图片地址
 */
export const printHandle = (imgUri: string) => {
  const iframe = document.createElement("iframe");
  iframe.style.height = "0";
  iframe.style.visibility = "hidden";
  iframe.style.width = "0";
  const str = `<html>
            <style media='print'>
                 @page{size:A4 landscape};margin:0mm;padding:0}
            </style>
            <body>
                 <img src="${imgUri}"/>
            </body>
	</html>
	`;
  iframe.setAttribute("srcdoc", str);
  document.body.appendChild(iframe);
  iframe.addEventListener("load", () => {
    iframe?.contentWindow?.print();
  });
  iframe?.contentWindow?.addEventListener("afterprint", function () {
    iframe?.parentNode?.removeChild(iframe);
  });
};

/* 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);
  });
}

/**
 * 创建新的图形
 */
export const createNew = async (type: string, folderId: string = "root") => {
  const res = await AddGraph({ type, folderId });
  const id = res?.result?.graph?.id;
  if (!id) return false;
  const { origin, pathname } = window.location;
  const enterpriseCode = sessionStorage.getItem("enterpriseCode");
  if (type === GraphType.mindmap) {
    window.open(
      `${origin}${pathname}#/mindmap/${id}?enterpriseCode=${enterpriseCode}`
    );
  } else {
    window.open(
      `${origin}${pathname}#/flow/${id}?enterpriseCode=${enterpriseCode}`
    );
  }
  return id;
};

type TreeNode = {
  id: string;
  parentId?: string;
  name: string;
  children?: TreeNode[];
} & Record<string, any>;

/**
 * 列表转树结构
 * @param list
 * @param pid
 * @param parentKey
 */
export const listToTree = (list: TreeNode[], parent: TreeNode): TreeNode => {
  const map: { [key: string]: TreeNode } = {
    [parent.id]: parent,
  };

  // 首先将所有节点放入 map 中
  list.forEach((node) => {
    map[node.id] = { ...node, children: [] };
  });
  // 再次遍历列表，构建树结构
  list.forEach((node) => {
    const currentNode = map[node.id];
    if (node.parentId && map[node.parentId]) {
      // 如果有父节点，则将当前节点添加到父节点的 children 中
      map?.[node.parentId]?.children?.push(currentNode);
    }
  });
  return parent;
};

/**
 * 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;
}

/**
 * 获取token
 */
export const getToken = () => {
  const enterpriseCode = sessionStorage.getItem("enterpriseCode");
  const token = localStorage.getItem("token_" + enterpriseCode);

  return token;
};
