import { HOST_FILE_HASH_MAP } from "@/constants/constants";
import { throttle } from "lodash";
import Vue from "vue";
import { createLog } from "./logger";

export function toChineseNumber(num) {
  let ret;
  if (num < 10) {
    ret = num.toLocaleString("zh-u-nu-hanidec");
  } else if (num === 10) {
    ret = "十";
  } else if (num > 10 && num < 20) {
    ret = "十" + (num % 10).toLocaleString("zh-u-nu-hanidec");
  } else if (num >= 20 && num < 100) {
    let s = num
      .toLocaleString("zh-u-nu-hanidec", { useGrouping: false })
      .split("");
    s.splice(1, 0, "十");
    ret = s.join("").replace("〇", "");
  } else {
    ret = num.toLocaleString("zh-u-nu-hanidec"); // 假设没有超过100的大题
  }

  return ret;
}

// 如果这台机器上登录过的学生人数小于5，那么这台电脑就是学生的
export function isThisMachineOwnByStudent() {
  return (JSON.parse(localStorage.getItem("userIds")) || []).length < 5;
}

export function setUUID() {
  if (!localStorage.getItem("uuidForEcs")) {
    const uuidForEcs = "" + Date.now() + Math.random();
    localStorage.setItem("uuidForEcs", uuidForEcs);
  }
}

export function isElectron() {
  return typeof nodeRequire != "undefined";
}

export function registerOnResize() {
  const throttledResizeLog = throttle(() => {
    createLog({
      page: window.location.pathname,
      action: "registerOnResize",
      width: window.screen.width,
      height: window.screen.height,
      screenX: window.screen.availWidth,
      screenY: window.screen.availHeight,
      clientWidth: document.documentElement.clientWidth,
      clientHeight: document.documentElement.clientHeight,
      windowInnerWidth: window.innerWidth,
      windowInnerHeight: window.innerHeight,
      windowOuterWidth: window.outerWidth,
      windowOuterHeight: window.outerHeight,
    });
    getScreenShot({ cause: "ss-registerOnResize" });
  }, 3000);
  window.onresize = throttledResizeLog;
}

// 下载文件
export async function downloadFileURL(url, name) {
  const link = document.createElement("a");
  link.style.display = "none";
  const fileName = name || url.split("/").pop().split("?")[0];
  console.log(fileName);
  link.setAttribute("download", fileName);

  link.href = url;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

export function checkMainExe() {
  try {
    let iid = window.nodeRequire("process").pid;
    const cp = window.nodeRequire("child_process");
    iid = cp
      .execSync(
        `cmd /c chcp 65001>nul && C:\\Windows\\System32\\wbem\\wmic process where ^(processid^=${iid}^) get parentprocessid /value`
      )
      .toString();
    iid = iid.replace("ParentProcessId=", "").trim();
    console.log(iid);
    iid = cp
      .execSync(
        `cmd /c chcp 65001>nul && C:\\Windows\\System32\\wbem\\wmic process where ^(processid^=${iid}^) get parentprocessid /value`
      )
      .toString();
    iid = iid.replace("ParentProcessId=", "").trim();
    console.log(iid);

    let executablePath = cp.execSync(
      `cmd /c chcp 65001>nul && C:\\Windows\\System32\\wbem\\wmic process where ^(processid^=${iid}^) get executablepath /value`
    );
    console.log(executablePath);
    const encoding = window.nodeRequire("encoding");
    executablePath = encoding.convert(executablePath, "utf8", "gbk").toString();
    console.log(executablePath);
    executablePath = executablePath
      .replace("ExecutablePath=", "")
      .trim()
      .replace(/&amp;/g, "&");
    if (executablePath === eval(`process.env.PORTABLE_EXECUTABLE_FILE`)) {
      const getHash = window
        .nodeRequire("crypto")
        .createHmac("sha256", "abcdefg")
        .update(window.nodeRequire("fs").readFileSync(executablePath))
        .digest("hex");
      console.log("the hash: ", getHash);
      if (HOST_FILE_HASH_MAP.get(window.location.hostname) === getHash) {
        return true;
      }
    }
    // check filepath executablePath md5
  } catch (error) {
    console.log(error);
  }
  return false;
}

export function initScreenShot() {
  window
    .nodeRequire("electron")
    .desktopCapturer.getSources(
      { types: ["window", "screen"] },
      async (e, sources) => {
        console.log(sources);
        for (const source of sources) {
          console.log(source);
          if (source.name === "Entire screen") {
            try {
              const stream = await navigator.mediaDevices.getUserMedia({
                audio: false,
                video: {
                  mandatory: {
                    chromeMediaSource: "desktop",
                    chromeMediaSourceId: source.id,
                    minWidth: 600,
                    maxWidth: 600,
                    minHeight: 480,
                    maxHeight: 480,
                  },
                },
              });
              handleStream(stream);
            } catch (e) {
              console.log(e);
              createLog({
                page: window.location.pathname,
                action: "ss-failed",
                sse: e,
              });
            }
            return;
          }
        }
      }
    );

  function handleStream(stream) {
    const video = document.querySelector("#ssVideo");
    video.srcObject = stream;
    video.onloadedmetadata = () => video.play();
  }
}

export async function getScreenShot({ cause = "ss-none" }) {
  const video = document.querySelector("#ssVideo");

  async function getSnapShot() {
    return new Promise((resolve, reject) => {
      if (video.readyState !== 4 || !video.srcObject.active) {
        reject("desktop没有正常启用");
      }
      video.pause();
      var canvas = document.createElement("canvas");
      canvas.width = 220;
      canvas.height = 165;

      var context = canvas.getContext("2d");
      context.drawImage(video, 0, 0, 220, 165);

      canvas.toBlob(resolve, "image/png", 0.95);
    });
  }

  const captureBlob = await getSnapShot();

  const params = new URLSearchParams();
  params.append("fileSuffix", "png");
  // params.append("fileMd5", fileMd5);
  if (window.location.pathname.includes("/login")) return;
  const res = await Vue.prototype.$http.get(
    "/api/ecs_oe_student/examControl/getCapturePhotoYunSign?" + params
  );

  let myFormData = new FormData();
  for (let [k, v] of Object.entries(res.data.formParams)) {
    myFormData.append(k, v);
  }
  myFormData.append("file", captureBlob);

  try {
    const res2 = await fetch(res.data.formUrl, {
      method: "POST",
      // headers: myHeaders,
      body: myFormData,
    });
    console.log(res2, {
      "res2.headers": res2.headers,
      'res2.headers.get("Content-MD5")': res2.headers.get("Content-MD5"),
      'res2.headers.get("Content-Type")': res2.headers.get("Content-Type"),
    });
    // throw new Error("eee");
    if (!res2.ok) {
      throw res2.status;
    }
    createLog({
      page: window.location.pathname,
      detail: "桌面抓拍保存成功",
      resultUrl: res.data.accessUrl,
      cause,
    });
  } catch (error) {
    console.log(error);
    createLog({
      page: window.location.pathname,
      detail: "桌面抓拍失败",
      error,
      cause,
    });
  } finally {
    video && video.play();
  }
}
