import html2canvas from "html2canvas";
import { showImagePreview, showToast } from "vant";
import { getToken, setToken } from "@/utils/storage";
import router from "@/router";
import JsPDF from "jspdf";
import { getTestTeachTokenRequest } from "@/api/login";

/**
 * 获取图片地址
 */
export function getImageUrl(name: string) {
  return new URL(`../assets/images/${name}.png`, import.meta.url).href;
}

/**
 * 调用app方法
 */
export function callAppFc(event: any, params = {}) {
  console.log(event, params, "callAppFc");
  try {
    window[event].postMessage(JSON.stringify(params));
  } catch (err) {
    console.log(err, event);
  }
}

/**
 * 在APP中跳转APP页面的方法
 */
export function navAppPage(route: string, callback = "", replace = false) {
  callAppFc("navAppPage", { route, callback, replace });
}

/**
 * c端在APP中返回上一页
 */
export function popPage() {
  callAppFc("popPage");
}

/**
 * 家园共育返回上一页
 */
export function returnAppPage() {
  try {
    (window as any).returnAppPage.postMessage(JSON.stringify({}));
  } catch (err) {
    router.go(-1);
  }
}

/**
 * 通知 app
 */
export function noticeApp(babyId: string, recordId: string) {
  callAppFc("sendToParent", {
    title: "发送给家长",
    babyId,
    recordId,
  });
}

/**
 * 字符串限制长度
 */
export function limitLength(val: any, limitLength = 3) {
  if (typeof val === "string" && val.length > limitLength) {
    return val.substr(0, limitLength) + "...";
  }
  return val;
}

/**
 * 图片全屏预览
 */
export function imagePreview(imgArr: string[] | string, startPosition?: number) {
  if (Array.isArray(imgArr)) {
    showImagePreview({
      images: imgArr,
      startPosition,
      loop: false,
    });
  } else {
    showImagePreview({
      images: [imgArr],
      startPosition: 0,
      loop: false,
    });
  }
}

export async function getTestTeachToken() {
  const { status, data, msg } = await getTestTeachTokenRequest("18210827464");
  if (status === 200) {
    setToken(data.accessToken);
  } else {
    showToast(msg);
  }
}

/**
 * 向 app 请求 token
 */
export function getAppToken() {
  // getTestTeachToken()

  const token = getToken();
  if (token?.length) {
    return token;
  }

  return new Promise<string>((resolve) => {
    (window as any).getToken = (token: string) => {
      if (token) {
        setToken(token);
        resolve(token);
      }
    };
  });
}

export async function convertToImage(element: HTMLElement) {
  return html2canvas(element, {
    scale: 4,
    width: element.offsetWidth,
    height: element.offsetHeight,
    useCORS: true,
    allowTaint: true,
    backgroundColor: "#fff",
  }).then((canvas: any) => {
    return canvas.toDataURL("image/png");
  });
}
/**
 * 下载 dom 截图
 */
export async function downloadScreenshotFn(id = "poster") {
  const element = document.getElementById(id);
  // console.log(element, "element");
  if (element) {
    const imgBlobData = await convertToImage(element);
    const el = document.createElement("a");
    el.href = imgBlobData;
    el.download = "poster.png";
    const event = new MouseEvent("click");
    el.dispatchEvent(event);
  }
}

/**
 * 下载 pdf
 */
export function downloadPDF(id = "poster") {
  const dom = document.getElementById(id) as HTMLElement | null;

  if (!dom) return;

  html2canvas(dom, {
    scale: 4,
    width: dom.offsetWidth,
    height: dom.offsetHeight,
    useCORS: true,
    allowTaint: false,
    backgroundColor: "#fff",
  })
    .then((canvas) => {
      let contentWidth = canvas.width;
      let contentHeight = canvas.height;
      let pageHeight = (contentWidth / 592.28) * 841.89;
      let leftHeight = contentHeight;
      let position = 0;
      let imgWidth = 595.28;
      let imgHeight = (592.28 / contentWidth) * contentHeight;
      let pageData = canvas.toDataURL("image/jpeg", 1.0);
      let PDF = new JsPDF("portrait", "pt", "a4");
      if (leftHeight < pageHeight) {
        PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
      } else {
        while (leftHeight > 0) {
          PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          if (leftHeight > 0) {
            PDF.addPage();
          }
        }
      }
      // todo pdf数据已经准备好了，就差给app，让app处理了
      let arraybuffer = PDF.output("arraybuffer");
      let blob = PDF.output("blob");
      let bloburl = PDF.output("bloburl");
      let datauristring = PDF.output("datauristring");

      console.log(arraybuffer, "arraybuffer");
      console.log(blob, "blob");
      console.log(bloburl);
      console.log(datauristring, "datauristring");

      // 下载
      PDF.save("测试" + ".pdf");
    })
    .catch((e) => {
      console.log(e);
    });
}

/**
 * 分享
 */
export function shareToFriendForReward(title: string, imgUrl: string, inviteCode: string) {
  callAppFc("shareToFriendForReward", { title, imgUrl, inviteCode });
}

/**
 * 分享
 * @param image 分享海报
 * @param title 分享标题
 * @param scene 0微信好友 1微信朋友圈
 * @param description 分享描述
 */
export function shareToWechat(image: string, title: string, scene: 0 | 1, description: string, url: string) {
  callAppFc("shareToWechat", { image, title, scene, description, url });
}
