import store from "@/store";
import { baseUpUrl } from "./http";
import { getTokenFu } from "./storage";
import { domShowFu } from "./domShow";

// 携带token，转换成文件流
export const urlChangeFu = (
  url: string,
  flag: boolean,
  type?: "img" | "video" | "audio" | "pdf",
  name?: string
) => {
  // 打开加载中
  domShowFu("#AsyncSpinLoding", true);

  // flag true 为 生成 a标签 下载

  let xhr = new XMLHttpRequest();

  xhr.open("get", baseUpUrl.replace("api/", "api") + url, true);

  xhr.responseType = "blob";
  xhr.onload = function (res) {
    // 取消加载中状态
    domShowFu("#AsyncSpinLoding", false);

    if (this.status === 200) {
      let blob = this.response;

      // 转为为Blob格式的
      const srcRes = window.URL.createObjectURL(blob);

      if (flag) {
        // 创建a标签下载
        let link = document.createElement("a"); //创建a标签
        link.style.display = "none"; //使其隐藏
        link.href = srcRes; //赋予文件下载地址
        link.setAttribute("download", name!); //设置下载属性 以及文件名
        document.body.appendChild(link); //a标签插至页面中
        link.click(); //强制触发a标签事件
        document.body.removeChild(link);
      } else {
        if (type === "img") {
          store.dispatch({
            type: "layout/lookBigImg",
            payload: {
              url: srcRes,
              show: true,
            },
          });
        } else if (type === "pdf") {
          window.open(srcRes);
        } else if (type === "audio" || type === "video") {
          store.dispatch({
            type: "layout/lookDom",
            payload: {
              src: srcRes,
              type,
              flag: true,
            },
          });
        }
      }
    }
  };

  // 携带token
  xhr.setRequestHeader("token", getTokenFu());

  xhr.send();
};

// 查看 权限 图片 /视频 、音频
export const authFilesLookFu = (name: string, url?: string) => {
  let flag = false;

  const nameRes = name ? name : "";

  if (nameRes.toLowerCase().endsWith(".pdf")) {
    if (url) urlChangeFu(url, false, "pdf");
    flag = true;
  }

  const arr1 = [".png", ".jpg", ".jpeg", ".gif"];
  arr1.forEach((v) => {
    if (nameRes.toLowerCase().endsWith(v)) {
      if (url) urlChangeFu(url, false, "img");

      flag = true;
    }
  });

  let type: "" | "video" | "audio" = "";

  const arr2 = [".mp3", ".wav"];

  arr2.forEach((v) => {
    if (nameRes.toLowerCase().endsWith(v)) {
      type = "audio";
      flag = true;
    }
  });

  if (nameRes.toLowerCase().endsWith(".mp4")) {
    type = "video";
    flag = true;
  }

  if (type && url) urlChangeFu(url, false, type);

  return flag;
};
