"use strict";
import { ipcMain } from "electron";
import { app, protocol, BrowserWindow, screen, globalShortcut } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import { createServer } from "@/server/index.js";
import { autoUpdater } from "electron-updater";

import path from "path"; // 引入 path 模块
const { exec } = require("child_process");

Object.defineProperty(app, "isPackaged", {
  get() {
    return true;
  },
});
createServer();
const isDevelopment = process.env.NODE_ENV !== "production";

let win;
let newWindow;
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);
const winURL =
  process.env.NODE_ENV === "development"
    ? "http://localhost:8050"
    : `file://${__dirname}/index.html`;

async function createWindow() {
  win = new BrowserWindow({
    width: 1500,
    height: 1000,
    icon: "./src/assets/logo.jpg",
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
    },
  });

  // let newWindow = new BrowserWindow({
  //   fullscreen: false,
  //   width: 1000,
  //   height: 1000,
  //   webPreferences: {
  //     nodeIntegration: true,
  //     //配置预加载脚本文件(preload)，此处起名为preloadOther
  //     //p.s.路径为绝对路径
  //     // preload:   path.join(__dirname, "./preloadOther.js")
  //   },
  // });

  console.log(winURL + "#" + `/design-detail`);
  // //指定副屏幕打开的网页
  // await newWindow.loadURL(winURL + "#" + `/design-detail`);
  // newWindow.reload();
  // win.on("closed", () => {
  //   //这一段放外面的话，如果你电脑没双屏会报错。
  //   win = null;
  // });

  ipcMain.on("allPrint", () => {
    // 获取到打印机列表
    const printers = win.webContents.getPrinters();
    // 把获取的打印机列表发送给渲染进程
    win.webContents.send("printName", printers);
  });
  ipcMain.on("win-subScreen", (data, v) => {
    if (newWindow) newWindow.webContents.send("getProductionNoInfo", v);
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    await win.loadURL("app://./index.html");
  }

  ipcMain.on("send-card", (event, obj) => {
    win.webContents.send("sendWebsockt", obj);
  });

  win.on("closed", () => {
    // win && win.removeAllListeners();
    // win = null;
    // newWindow && newWindow.close();
    // newWindow = null;

    // 确保窗口还未销毁，才执行清理操作
    if (win && !win.isDestroyed()) {
      win.removeAllListeners();
      win = null;
    }
    // // 确保 newWindow 还未销毁，才执行关闭操作
    // if (newWindow && !newWindow.isDestroyed()) {
    //   newWindow.close();
    //   newWindow = null;
    // }
  });

  // 自动更新逻辑开始
  autoUpdater.autoDownload = false;
  autoUpdater.autoInstallOnAppQuit = false; // 应用退出后自动安装
  autoUpdater.on("download-progress", (progress) => {
    // 下载进度监听
    if (win.isDestroyed()) return;
    win.webContents.send("update", {
      speed: Math.ceil(progress.bytesPerSecond / 1000), // 网速
      percent: Math.ceil(progress.percent), // 百分比
    });
  });

  autoUpdater.on("error", (err) => {
    // 下载失败监听
    if (win.isDestroyed()) return;
    win.webContents.send("update-error", err);
  });

  autoUpdater.on("update-downloaded", (info) => {
    // 下载完成监听
    if (win.isDestroyed()) return;
    console.log(info, "info");
    win.webContents.send("downloaded", info);
  });

  ipcMain.on("install", () => {
    // 退出安装
    autoUpdater.quitAndInstall();
  });

  ipcMain.on("toUpdateApp", (data, item) => {
    // 去手动下载更新
    if (win.isDestroyed()) return;
    autoUpdater.setFeedURL({
      provider: "generic",
      url: item.url,
    });
    autoUpdater.checkForUpdates().then((res) => {
      console.log(res);
      autoUpdater.downloadUpdate();
    });
  });

  // 监听渲染进程发来的请求，执行 PowerShell 脚本
  ipcMain.on("select-files", (event, folderPath) => {
    return new Promise((resolve, reject) => {
      let psScriptPath;
      if (process.env.NODE_ENV === "development") {
        psScriptPath = path.join(__dirname, "..", "scripts", "script.ps1");
      } else {
        psScriptPath = path.join(
          path.dirname(app.getPath("exe")),
          "resources",
          "scripts",
          "script.ps1"
        );
      }

      // 构建 PowerShell 命令
      const psCommand = `powershell -ExecutionPolicy Bypass -File "${psScriptPath}" -folderPath "${folderPath}"`;

      exec(psCommand, (error, stdout, stderr) => {
        if (error) {
          reject(`exec error: ${error}`);
        }
        resolve(stdout || stderr);
      });
    });
  });

  win.on("resize", () => {
    const { width, height } = win.getBounds();
    win.webContents.send("window-size", { width, height });
  });
  // 监听窗口的 reload 事件
  win.webContents.on("did-finish-load", () => {
    const { width, height } = win.getBounds();
    win.webContents.send("window-size", { width, height });
  });
}

app.on("activate", async () => {
  if (win === null) {
    await createWindow();
  }
});

app.on("ready", async () => {
  await createWindow();
  // 获取当前窗口的尺寸
  const { width, height } = win.getBounds();
  win.webContents.send("window-size", { width, height });
  globalShortcut.register("F5", () => {
    return false;
  });
  globalShortcut.register("CommandOrControl+R", () => {
    return false;
  });
});

app.on("will-quit", () => {
  globalShortcut.unregister("F5");
  globalShortcut.unregister("CommandOrControl+R");
});

if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}
