import { app, BrowserWindow, ipcMain, dialog, shell } from "electron";
import { fileURLToPath } from "url";
import path from "path";
import { spawn } from "child_process";
import fs from "fs";
import Papa from "./libs/papaparse/papaparse.js";

process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

let mainWindow = null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1400,
    height: 900,
    minWidth: 800,
    minHeight: 600,
    webPreferences: {
      preload: path.join(__dirname, "./preload.mjs"),
      contextIsolation: true,
      nodeIntegration: false,
      allowRunningInsecureContent: false,
    },
    icon: path.join(__dirname, "../src/assets/images/icon.png"),//这里切换程序图标
  });

  if (process.env.NODE_ENV === "development") {
    mainWindow.loadURL("http://localhost:5173");
    // mainWindow.webContents.openDevTools();  //这是打开控制台
  } else {
    mainWindow.loadFile(path.join(__dirname, "../dist/index.html"));
    // mainWindow.webContents.openDevTools();   //这是打开控制台
  }

  // ✅ 运行 Python EXE
  ipcMain.handle("run-python-exe", async (event, apiName, params = {}) => {
    return new Promise((resolve, reject) => {
      let pythonExePath;

      if (process.env.NODE_ENV === "development") {
        pythonExePath = path.join(__dirname, "../serves/dist/api_test.exe");
      } else {
        pythonExePath = path.join(
          process.resourcesPath,
          "app.asar.unpacked",
          "serves",
          "dist",
          "api_test.exe"
        );
      }

      if (!fs.existsSync(pythonExePath)) {
        reject(`Python EXE 不存在: ${pythonExePath}`);
        return;
      }

      const args = [
        apiName,
        Buffer.from(JSON.stringify(params)).toString("base64"),
      ];

      const child = spawn(pythonExePath, args, { encoding: "utf8" });
      let stdoutData = "";
      let stderrData = "";

      child.stdout.on("data", (data) => (stdoutData += data.toString()));
      child.stderr.on("data", (data) => (stderrData += data.toString()));

      child.on("close", (code) => {
        if (code !== 0) {
          reject(`Python EXE exited with code ${code}\n${stderrData}`);
          return;
        }

        try {
          resolve(JSON.parse(stdoutData));
        } catch (err) {
          resolve(stdoutData.trim());
        }
      });
    });
  });

  // ✅ 读取 CSV
  ipcMain.handle("read-csv", async (event, filePath) => {
    try {
      const csvData = fs.readFileSync(filePath, "utf-8");
      const parsedData = Papa.parse(csvData, {
        header: true,
        skipEmptyLines: true,
        transformHeader: (header) => header.trim(),
      });
      const cleanData = parsedData.data.filter((row) =>
        Object.values(row).some((val) => val && val.trim() !== "")
      );
      return cleanData;
    } catch (error) {
      console.error("读取 CSV 失败:", error);
      return { error: error.message };
    }
  });

  // ✅ 文件选择
  ipcMain.handle("get-file-path", async () => {
    try {
      const { filePaths } = await dialog.showOpenDialog({
        properties: ["openFile", "multiSelections"],
      });
      return filePaths.length > 0 ? filePaths[0] : null;
    } catch (error) {
      console.error("获取文件路径失败:", error);
      return null;
    }
  });

  // ✅ 保存数据到文件夹？
  ipcMain.handle("save-submission", async (event, args) => {
    try {
      const baseDir = path.join(app.getPath("documents"), "雷击引下线数据");
      const { folderName, files } = args;
      const targetDir = path.join(baseDir, folderName);

      fs.mkdirSync(targetDir, { recursive: true });
      const savedPaths = [];

      for (const f of files) {
        const filePath = path.join(targetDir, f.fileName);
        const data =
          typeof f.content === "string" ? f.content : JSON.stringify(f.content);
        fs.writeFileSync(filePath, data, "utf8");
        savedPaths.push({ fileName: f.fileName, fullPath: filePath });
      }

      return { ok: true, dir: targetDir, savedPaths };
    } catch (err) {
      console.error("save-submission failed:", err);
      return { ok: false, error: String(err) };
    }
  });

    /** ✅ 删除单个文件夹 */
  ipcMain.handle("delete-folder", async (event, folderPath) => {
    try {
      if (!folderPath || !fs.existsSync(folderPath)) {
        return { ok: false, error: "文件夹不存在" };
      }
      fs.rmSync(folderPath, { recursive: true, force: true });
      console.log("已删除文件夹:", folderPath);
      return { ok: true };
    } catch (err) {
      console.error("删除文件夹失败:", err);
      return { ok: false, error: String(err) };
    }
  });

  /** ✅ 清空所有数据文件夹 */
  ipcMain.handle("clear-all-folders", async () => {
    try {
      const baseDir = path.join(app.getPath("documents"), "雷击引下线数据");
      if (fs.existsSync(baseDir)) {
        fs.rmSync(baseDir, { recursive: true, force: true });
        console.log("已清空目录:", baseDir);
      }
      return { ok: true };
    } catch (err) {
      console.error("清空文件夹失败:", err);
      return { ok: false, error: String(err) };
    }
  });

  // ✅ 读取文本文件
  ipcMain.handle("read-text-file", async (event, filePath) => {
    try {
      const content = fs.readFileSync(filePath, "utf8");
      return { ok: true, content };
    } catch (err) {
      return { ok: false, error: String(err) };
    }
  });

  // ✅ 读取 JSON 文件
  ipcMain.handle("read-json-file", async (event, filePath) => {
    try {
      const text = fs.readFileSync(filePath, "utf8");
      const json = JSON.parse(text);
      return { ok: true, json };
    } catch (err) {
      return { ok: false, error: String(err) };
    }
  });

  // ✅ 打开文件夹（只打开到指定目录）
  ipcMain.handle("open-path", async (event, folderPath) => {
    try {
      const stats = fs.statSync(folderPath);
      const target = stats.isDirectory()
        ? folderPath
        : path.dirname(folderPath);
      await shell.openPath(target);
      return { ok: true, opened: target };
    } catch (err) {
      console.error("打开路径失败:", err);
      return { ok: false, error: String(err) };
    }
  });

  // ✅ 关闭确认
  mainWindow.on("close", (event) => {
    event.preventDefault();
    const choice = dialog.showMessageBoxSync(mainWindow, {
      type: "question",
      buttons: ["取消", "退出"],
      defaultId: 0,
      title: "确认退出",
      message: "退出程序正在分析中的数据会丢失，确定要退出程序吗？",
    });

    if (choice === 1) {
      mainWindow.removeAllListeners("close");
      mainWindow.close();
    }
  });

  mainWindow.on("closed", () => {
    mainWindow = null;
  });
}

app.whenReady().then(createWindow);
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});
app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

export { createWindow };
