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

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("cmd /c chcp 65001>nul && " + exeName, async (err, data, stderr) => {
        console.log(exeName, err, data); // 未免过多日志，此处后续可以关闭
        createLog({
          page: window.location.pathname,
          exeName,
          error: JSON.stringify(err),
          data,
          stderr: JSON.stringify(stderr),
          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("cmd /c chcp 65001>nul && tasklist /FO CSV")
    .toString();
  // console.debug(appList);
  if (
    appList &&
    ((appList.match(/sunloginclient/gi) &&
      appList.match(/sunloginclient/gi).length > 0) ||
      (appList.match(/选择免安装运行，截图识别/gi) &&
        appList.match(/选择免安装运行，截图识别/gi).length > 0))
  ) {
    return true;
  } else {
    return false;
  }
}

let previousAppList = [];
export function nodeCheckProcess() {
  try {
    let appList = window
      .nodeRequire("child_process")
      .execSync("cmd /c chcp 65001>nul && tasklist /FO CSV")
      .toString();
    // 不能打印，electron-log 不能接收
    // console.log(appList);
    appList = appList.split("\r\n");
    appList.shift();
    appList = appList.map((v) => v.split(",")[0]);
    const xorRes = xor(previousAppList, appList);
    if (xorRes && xorRes.length > 0) {
      createLog({
        page: window.location.pathname,
        action: "nodeCheckProcess",
        xorRes: xorRes.join(" ||| "),
      });
    }
    previousAppList = appList;
  } catch (error) {
    console.log("nodeCheckProcess exec error: ", error);
  }
}
