"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";

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`);
  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;
  });

  // 自动更新逻辑开始
  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()
    })

  });
}

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

app.on("ready", async () => {
  await createWindow();
  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();
    });
  }
}
