"use strict";
import { contextBridge, ipcMain, ipcRenderer } from "electron";
import { app, protocol, BrowserWindow, Menu, screen } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import webApp from "@/backend/webserver/be_nodeSrv.js";

let isCreateWin = false;
const isDevelopment = process.env.NODE_ENV !== "production";

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

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

  let displays = screen.getAllDisplays();

  //寻找副屏幕
  let externalDisplay = displays.find(display => {
    return display.bounds.x !== 0 || display.bounds.y !== 0;
  });

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

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

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

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

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

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

app.on("ready", async () => {
  createWindow();
});

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