import { removeTokenInfo } from "@dage/pc-components";
import { logoutApi } from "@/api";
import { Key } from "react";
import { AssIndexTreeItemType } from "@/types";
import { RcFile } from "antd/es/upload";
import { message } from "antd";

export const logout = async () => {
  await logoutApi();

  removeTokenInfo();
  globalThis.location.href = "#/login";
};

export const getSelectedNodes = (
  selectedKeys: Key[],
  treeData: AssIndexTreeItemType[],
  // 任意节点
  any = false
) => {
  let selectedNodes: AssIndexTreeItemType[] = [];

  const findNodes = (keys: Key[], data: AssIndexTreeItemType[]) => {
    data.forEach((node) => {
      if (keys.includes(node.id) && (any ? true : !node.children?.length)) {
        selectedNodes.push(node);
      }
      if (node.children) {
        findNodes(keys, node.children);
      }
    });
  };

  findNodes(selectedKeys, treeData);
  return selectedNodes;
};

export const getImgFullPath = (path: string) =>
  `${process.env.REACT_APP_API_URL}${process.env.REACT_APP_IMG_PUBLIC}${path}`;

export const downloadFile = async (url: string, name: string) => {
  try {
    const response = await fetch(url);
    const blob = await response.blob();
    const newUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = newUrl;
    link.download = name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error("下载失败:", error);
  }
};

export const beforeUpload = (suffix: string, file: RcFile) => {
  const arr = suffix.split(",");

  if (!arr.length) return true;
  const result = arr.findIndex((i) => file.name.indexOf(i) > -1) > -1;
  if (!result) {
    message.error("选择的文件类型不正确！");
  }
  return result;
};
