export * from "./hander";
import { AddGraph } from "@/api/systemDesigner";
import { GraphType } from "@/enum";
import type { MessageInstance } from "antd/lib/message/interface";
import { uuid } from "@repo/utils";

/**
 * 打印图片
 * @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);
  });
};

/**
 * 创建新的图形
 */
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;
};

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

  return token;
};

// Mermaid 流程图检测
export function isMermaidFlowchart(code: string): boolean {
  const flowchartRegex = /^\s*graph|flowchart\s+(TD|LR|RL|TB)\s*\n/i;
  const nodeRegex = /(\w+)\[(.*?)\]|\{|\}/;
  return flowchartRegex.test(code) && nodeRegex.test(code);
}

function regexExtractJSON(markdown: string) {
  const jsonRegex = /```(?:json)?\n([\s\S]*?)\n```/g;
  const matches = [];
  let match;

  while ((match = jsonRegex.exec(markdown)) !== null) {
    try {
      const jsonObj = JSON.parse(match[1]);
      matches.push(jsonObj);
    } catch (e) {
      console.warn("无效JSON:", match[0]);
    }
  }
  return matches;
}

/**
 * AI生成的数据id可能有问题，重试生成id
 */
export const replaceFlowId = (data: any) => {
  if(Object.prototype.toString.call(data) === "[object Object]") {
    if(data?.id) {
      data.id = uuid();
    }
    data?.ports?.items?.forEach((item: any) => {
      if(item?.id) {
        item.id = uuid();
      }
    });
  }
  if(Object.prototype.toString.call(data) === "[object Array]") {
    data.forEach((item: any) => {
      const id = uuid();
      const originalId = item.id;
      item.id = id;
      data.forEach((cell: any) => {
        if(cell?.source?.cell === originalId ) { cell.source.cell = id; }
        if(cell?.target?.cell === originalId ) { cell.target.cell = id; }
      });
      item?.ports?.items?.forEach((port: any) => {
        const id = uuid();
        const originalId = port.id;
        port.id = id;
        data.forEach((cell: any) => {
          if(cell?.source?.port === originalId ) { cell.source.port = id; }
          if(cell?.target?.port === originalId ) { cell.target.port = id; }
        });
      });
    });
  }
  return data;
};

/**
 * 转换解析出ai数据
 * @param content
 * @param message
 * @param onSuccess
 * @param onError
 */
export const handleParseFowlAIData = ({
  content,
  message,
  onSuccess,
  onError
}: {
  content: string;
  message: {
    key: string;
    instance: MessageInstance;
  };
  onSuccess?: (data: any) => void;
  onError?: (err: Error) => void;
}) => {
  try {
    // 根据markdown格式取出json部分数据
    let json: string;
    if (content.includes("```json")) {
      json = regexExtractJSON(content)?.[0];
    } else {
      json = JSON.parse(content);
    }

    onSuccess?.(json);
    
  } catch (error) {
    message.instance.open({
      key: message.key,
      type: "error",
      content: "AI创作失败",
      duration: 2,
      style: {
        marginTop: 300,
      },
    });
    console.error(error);
    onError?.(new Error("AI创作失败"));
  }
};