import { createLog } from "@/utils/logger";

export default function checkRemote(exeName, cb) {
  if (typeof nodeRequire == "undefined") {
    console.log("nodeRequire failed");
    window._hmt.push([
      "_trackEvent",
      window.location.pathname.replace(/=\w*/g, "=").replace(/\d+/g, "{id}"),
      "不在Electron中，调用 " + exeName + " 失败",
    ]);
    createLog({
      page: window.location.pathname,
      action: "不在Electron中，调用 " + exeName + " 失败",
    });
    throw new Error("不在Electron中，调用 " + exeName + " 失败");
  }
  return new Promise((resolve) => {
    window.nodeRequire("node-cmd").get(exeName, async (err, data, stderr) => {
      let stderrConverted;
      try {
        const iconv = require("iconv-lite");
        stderrConverted = iconv.decode(stderr, "cp936");
      } catch (error) {
        console.log("convert failed", error);
        stderrConverted = "convert failed";
      }
      console.log(exeName, err, data, stderrConverted); // 未免过多日志，此处后续可以关闭
      createLog({
        page: window.location.pathname,
        exeName,
        error: JSON.stringify(err),
        data,
        stderr: JSON.stringify(stderr),
        stderrConverted: JSON.stringify(stderrConverted),
        absPath: exeName.includes(":"),
      });
      // 如果相对路径没找到，则通过绝对路径来执行
      if (!exeName.includes(":") && err) {
        const fs = window.nodeRequire("electron").remote.require("fs");

        const path = window.nodeRequire("electron").remote.require("path");

        const [exePath, exeParams] = exeName.split(" ");
        const absPath = path.join(
          window.nodeRequire("electron").remote.app.getAppPath(),
          "../../",
          exePath
        );
        if (fs.existsSync(absPath)) {
          try {
            await checkRemote([absPath, exeParams].join(" ").trim(), cb);
          } catch (error) {
            console.log("second try error", absPath);
          }
        }
      }
      await new Promise((resolve2) => setTimeout(() => resolve2(), 1000));
      try {
        await cb();
      } catch (e) {
        console.log("call cb failed", e);
      } finally {
        resolve();
      }
    });
  });
}

export function fileExists(file) {
  if (typeof nodeRequire == "undefined") {
    console.log("nodeRequire failed");
    window._hmt.push([
      "_trackEvent",
      window.location.pathname.replace(/=\w*/g, "=").replace(/\d+/g, "{id}"),
      "不在Electron中，调用 fs 失败",
    ]);
    createLog({
      page: window.location.pathname,
      action: "不在Electron中，调用 fs 失败",
    });
    throw new Error("不在Electron中，调用 fs 失败");
  }
  return window.nodeRequire("fs").existsSync(file);
}

export function nodeCheckRemoteDesktop() {
  createLog({
    page: window.location.pathname,
    action: "nodeCheckRemoteDesktop",
  });

  const appList = window
    .nodeRequire("child_process")
    .execSync("tasklist")
    .toString();
  if (
    appList &&
    appList.match(/sunloginclient/gi) &&
    appList.match(/sunloginclient/gi).length > 0
  ) {
    return true;
  } else {
    return false;
  }
}
