import Vue from "vue";
import { AES } from "./crypto";
import { pick } from "lodash";
import { DEVICE_ID, PLATFORM } from "@/constants/app";
import { randomCode } from "./utils";

export function getDownloadURLScheme(downloadSet = null, apiUrl = null) {
  let user = Vue.ls.get("user");
  const schoolId = Vue.ls.get("schoolId");
  const curSchoolInfo = user.schoolInfo.find((item) => item.id === schoolId);
  user.curSchoolInfo = curSchoolInfo;
  user = pick(user, [
    "id",
    "loginName",
    "realName",
    "sessionId",
    "accessToken",
    "orgInfo",
    "curSchoolInfo",
  ]);
  user.deviceId = DEVICE_ID;
  user.platform = PLATFORM;

  const key = AES(
    JSON.stringify({
      user,
      apiUrl: apiUrl || window.location.origin,
      downloadSet,
      actionSession: `${Date.now()}${randomCode()}`,
    })
  );
  return `trd://download/?q=${key}`;
}

export function openApp(scheme) {
  window.location.href = scheme;
  // // 创建 iframe 来尝试调用 URL Scheme
  // const iframe = document.createElement("iframe");
  // iframe.style.display = "none";
  // iframe.src = scheme;
  // document.body.appendChild(iframe);

  // setTimeout(() => {
  //   document.body.removeChild(iframe);
  // }, 1000);
}

export function openAppWithCallback(scheme, timeout = 2000, fallback) {
  let isPageHidden = false;

  const onVisibilityChange = () => {
    if (document.hidden) {
      isPageHidden = true;
    }
  };

  document.addEventListener("visibilitychange", onVisibilityChange);

  // 创建 iframe 来尝试调用 URL Scheme
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  iframe.src = scheme;
  document.body.appendChild(iframe);

  // 这里是比较鸡肋的
  // 在打开scheme，部分浏览器会提示用户是否打开，如果用户不点击确认，就会导致误判

  setTimeout(() => {
    document.removeEventListener("visibilitychange", onVisibilityChange);
    document.body.removeChild(iframe);

    if (!isPageHidden) {
      // 如果页面未切换到后台，跳转到 fallback URL
      fallback && fallback();
    }
  }, timeout);
}
