"use strict";
import { ipcMain, shell, Menu, dialog } from "electron";
import { app, protocol, BrowserWindow, globalShortcut } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import { createServer } from "@/server/index.js";
import { autoUpdater } from "electron-updater";
const registerDownloadIpc = require("@/utils/download-file.js");
import downloadQueue from "@/utils/download-queue";
const {
  registerTypesettingDownloadIpc
} = require("@/utils/download-typesetting");
const fs = require("fs");

import path from "path"; // 引入 path 模块
const { exec } = require("child_process");
const { setVersion, getHostApi, setApi } = require("@/server/utils/store");

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

registerDownloadIpc();
registerTypesettingDownloadIpc();
async function createWindow() {
  win = new BrowserWindow({
    width: 1500,
    height: 1000,
    icon: "./src/assets/logo.jpg",

    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,

      contextIsolation: false // ^1.4.0 版本必须关闭
    },
    show: false
  });
  win.once("ready-to-show", () => {
    win.maximize();
    win.show();
  });
  const template = [
    {
      label: "编辑",
      submenu: [
        { label: "撤销", role: "undo" },
        { label: "重做", role: "redo" },
        { type: "separator" },
        { label: "剪切", role: "cut" },
        { label: "复制", role: "copy" },
        { label: "粘贴", role: "paste" },
        { label: "删除", role: "delete" },
        { type: "separator" },
        { label: "全选", role: "selectAll" }
      ]
    },

    {
      label: "视图",
      submenu: [
        { label: "重新加载", role: "reload" },
        { label: "强制重新加载", role: "forcereload" },
        { label: "开发者工具", role: "toggledevtools" },
        { type: "separator" },
        { label: "重置缩放", role: "resetzoom" },
        { label: "放大", role: "zoomin" },
        { label: "缩小", role: "zoomout" },
        { type: "separator" },
        { label: "全屏切换", role: "togglefullscreen" }
      ]
    },

    {
      label: "窗口",
      submenu: [
        { label: "最小化", role: "minimize" },
        { label: "缩放", role: "zoom" },
        { label: "关闭", role: "close" }
      ]
    },
    {
      label: "设置",

      submenu: [
        {
          label: "工厂域名设置",
          click: function() {
            (async function() {
              try {
                var mainWindow =
                  BrowserWindow.getFocusedWindow() ||
                  BrowserWindow.getAllWindows()[0];
                if (!mainWindow) {
                  await dialog.showMessageBox({
                    type: "error",
                    title: "错误",
                    message: "无可用窗口",
                    buttons: ["确定"]
                  });
                  return;
                }

                var newDomain = await new Promise(function(resolve) {
                  // 1. 生成唯一 promptId
                  var promptId = "domain-prompt-" + Date.now();

                  // 2. 创建弹窗窗口（配置不变）
                  var promptWin = new BrowserWindow({
                    parent: mainWindow,
                    modal: true,
                    width: 400,
                    height: 180,
                    title: "设置工厂域名",
                    resizable: false,
                    autoHideMenuBar: true,
                    menuBarVisible: false,
                    webPreferences: {
                      nodeIntegration: true,
                      contextIsolation: false,
                      sandbox: false,
                      enableRemoteModule: true,
                      webSecurity: false
                    }
                  });

                  // 3. 打开开发者工具（排查用，上线后删除）
                  // promptWin.webContents.openDevTools();
                  let exePath;

                  if (process.env.NODE_ENV === "development") {
                    exePath = path.join(
                      __dirname,
                      "../html/domain-prompt.html"
                    );
                  } else {
                    const newpath = path
                      .dirname(app.getPath("exe"))
                      .replace(/\\/g, "/");

                    exePath = `${newpath}/html/domain-prompt.html`;
                  }
                  // 4. 核心改：通过 URL 查询参数传递 promptId（替代脚本注入）
                  const promptHtmlPath = path.resolve(exePath);

                  const encodedDomain = new URL(getHostApi().apiApiHost).host;
                  // 拼接 URL：file:///xxx/domain-prompt.html?promptId=xxx
                  const promptUrl = `file://${promptHtmlPath}?promptId=${promptId}&defaultDomain=${encodedDomain}`;
                  promptWin.loadURL(promptUrl);

                  // 5. 监听 IPC 结果（原有逻辑不变）
                  var ipcListener = function(event, val) {
                    console.log("ipcListener", val);

                    resolve(val);
                    ipcMain.removeListener(promptId, ipcListener);
                  };
                  ipcMain.on(promptId, ipcListener);

                  // 6. 窗口关闭/加载失败兜底
                  promptWin.on("closed", function() {
                    ipcMain.removeListener(promptId, ipcListener);
                    resolve(null);
                  });
                  promptWin.webContents.on("did-fail-load", () => {
                    console.error("弹窗页面加载失败");
                    resolve(null);
                    promptWin.close();
                  });
                });

                // 处理结果（原有逻辑不变）
                if (newDomain) {
                  const configPath = getHostApi().configPath;
                  console.log("新工厂域名：", newDomain);
                  fs.readFile(configPath, "utf-8", (err, data) => {
                    if (err) {
                      console.error("读取配置文件失败:", err);
                      return;
                    }
                    try {
                      let configObj = JSON.parse(data);
                      const isTest = process.env.VUE_APP_ENV === "test";
                      console.log("isTest", isTest);
                      console.log("configObj", configObj);

                      const config = isTest ? configObj.test : configObj.prod;
                      config.apiApiHost = isTest
                        ? `http://${newDomain}/api`
                        : `https://${newDomain}/api`;
                      config.fileApiUrl = isTest
                        ? `http://${newDomain}/upload/factory`
                        : `https://${newDomain}/upload/factory`;
                      config.configPath = configPath;
                      // const newData = JSON.stringify(config); // 使用2个空格缩进

                      // console.log("修改后的数据:", newData);
                      configObj[isTest ? "test" : "prod"] = config;
                      const newConfigObj = JSON.stringify(configObj);
                      // 4. 写回文件
                      fs.writeFile(
                        configPath,
                        newConfigObj,
                        "utf-8",
                        writeErr => {
                          if (writeErr) {
                            console.error("写入配置文件失败:", writeErr);
                            this.$message.error(
                              `写入配置文件失败: ${writeErr.message}`
                            );
                            return;
                          }

                          console.log("配置文件更新成功", config);

                          setApi(config);
                        }
                      );
                    } catch (parseError) {
                      console.error("解析 JSON 失败:", parseError);
                      this.$message.error(
                        `配置文件格式错误: ${parseError.message}`
                      );
                    }
                  });
                } else {
                  console.log("用户取消了域名设置");
                }
              } catch (error) {
                console.error("自定义弹窗出错：", error);
              }
            })();
          }
        },
        {
          label: "清除缓存",
          click: function() {
            (async function() {
              try {
                var mainWindow =
                  BrowserWindow.getFocusedWindow() ||
                  BrowserWindow.getAllWindows()[0];
                if (!mainWindow) {
                  await dialog.showMessageBox({
                    type: "error",
                    title: "错误",
                    message: "无可用窗口",
                    buttons: ["确定"]
                  });
                  return;
                }

                var newDomain = await new Promise(function(resolve) {
                  // 1. 生成唯一 promptId
                  var promptId = "clear-prompt-" + Date.now();

                  // 2. 创建弹窗窗口（配置不变）
                  var promptWin = new BrowserWindow({
                    parent: mainWindow,
                    modal: true,
                    width: 450,
                    height: 300,
                    title: "清除缓存",
                    resizable: false,
                    autoHideMenuBar: true,
                    menuBarVisible: false,
                    webPreferences: {
                      nodeIntegration: true,
                      contextIsolation: false,
                      sandbox: false,
                      enableRemoteModule: true,
                      webSecurity: false
                    }
                  });

                  // 3. 打开开发者工具（排查用，上线后删除）
                  // promptWin.webContents.openDevTools();
                  let exePath;

                  if (process.env.NODE_ENV === "development") {
                    exePath = path.join(__dirname, "../html/clear-prompt.html");
                  } else {
                    const newpath = path
                      .dirname(app.getPath("exe"))
                      .replace(/\\/g, "/");

                    exePath = `${newpath}/html/clear-prompt.html`;
                  }
                  // 4. 核心改：通过 URL 查询参数传递 promptId（替代脚本注入）
                  const promptHtmlPath = path.resolve(exePath);
                  // 拼接 URL：file:///xxx/domain-prompt.html?promptId=xxx
                  const promptUrl = `file://${promptHtmlPath}?promptId=${promptId}`;
                  promptWin.loadURL(promptUrl);

                  // 5. 监听 IPC 结果（原有逻辑不变）
                  var ipcListener = function(event, val) {
                    console.log("ipcListener", val);

                    resolve(val);
                    ipcMain.removeListener(promptId, ipcListener);
                  };
                  ipcMain.on(promptId, ipcListener);

                  // 6. 窗口关闭/加载失败兜底
                  promptWin.on("closed", function() {
                    ipcMain.removeListener(promptId, ipcListener);
                    resolve(null);
                  });
                  promptWin.webContents.on("did-fail-load", () => {
                    console.error("弹窗页面加载失败");
                    resolve(null);
                    promptWin.close();
                  });
                });

                // 处理结果（原有逻辑不变）
                if (newDomain) {
                  console.log("clear-checkList：", newDomain);
                  win.webContents.send("clear-checkList", newDomain);
                } else {
                  console.log("用户取消了域名设置");
                }
              } catch (error) {
                console.error("自定义弹窗出错：", error);
              }
            })();
          }
        }
      ]
    }

    // {
    //   label: "帮助",
    //   submenu: [
    //     {
    //       label: "帮助文档",
    //       click: async () => {
    //         await shell.openExternal("");
    //       },
    //     },
    //     {
    //       label: "检查更新",
    //       click: () => {
    //         console.log("检查更新");
    //       },
    //     },
    //     { type: "separator" },

    //     {
    //       label: "关于",
    //       click: () => {},
    //     },
    //   ],
    // },
  ];
  // 构建菜单
  const menu = Menu.buildFromTemplate(template);
  // 设置应用菜单
  Menu.setApplicationMenu(menu);
  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);
  });

  ipcMain.on("request-select-folder", (event, currentPath) => {
    // 打开文件夹选择对话框（Electron 6.x 回调写法，更稳定）
    dialog.showOpenDialog(
      {
        properties: ["openDirectory"], // 仅允许选择文件夹
        title: "选择下载保存位置",
        defaultPath: currentPath || ""
      },
      result => {
        // 处理结果并返回给渲染进程
        console.log(438, result);
        if (result.length) {
          event.reply("select-folder-result", result[0]);
        }
      }
    );
  });

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

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

  ipcMain.on("open-folder-only", async (event, dirPath) => {
    console.log(938, dirPath);

    const result = shell.openItem(dirPath);
    return result;
  });

  win.on("closed", () => {
    // 确保窗口还未销毁，才执行清理操作
    if (win && !win.isDestroyed()) {
      win.removeAllListeners();
      win = 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 });
    console.log(888);
  });

  ipcMain.on("get-install-path", event => {
    const desktopPath = app.getPath("desktop");
    const dtfDir = path.join(desktopPath, "JomallProductionAssistant-DTF");
    let resPath = desktopPath;
    try {
      fs.mkdirSync(dtfDir, { recursive: true });
      resPath = dtfDir;
    } catch (err) {
      console.error("创建文件夹失败", err);
    }

    event.reply("get-install-path-res", resPath);
  });

  // ========== 新增3：窗口关闭时停止定时任务 ==========
  win.on("closed", () => {
    downloadQueue.stopAutoDownloadTask();
  });
}

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
} else {
  app.on("second-instance", () => {
    // 第二次双击时，唤起已有的窗口
    const allWindows = BrowserWindow.getAllWindows();
    const mainWin = allWindows[0];
    if (mainWin) {
      if (mainWin.isMinimized()) mainWin.restore();
      mainWin.show();
      mainWin.focus();
    }
  });
}

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

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

  console.log("winURL", winURL);
  // 获取当前窗口的尺寸
  const { width, height } = win.getBounds();
  win.webContents.send("window-size", { width, height });
  globalShortcut.register("F5", () => {
    return false;
  });
  globalShortcut.register("CommandOrControl+R", () => {
    return false;
  });
  ipcMain.on("update-version", (_, version) => {
    console.log(72, version);

    setVersion(version); // 保存到 electron-store
  });
});

app.on("will-quit", () => {
  globalShortcut.unregister("F5");
  globalShortcut.unregister("CommandOrControl+R");
});
app.on("window-all-closed", () => {
  downloadQueue.stopAutoDownloadTask();
  if (process.platform !== "darwin") {
    app.quit();
  }
});

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