const { ipcMain, BrowserWindow } = require("electron");
const path = require("path");
const { getHostApi } = require("@/server/utils/store");
const { batchDownloadByStr } = require("./download-core");

/* ===================== 原有命名逻辑（完全保留） ===================== */
function formatTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hour = String(now.getHours()).padStart(2, "0");
  const minute = String(now.getMinutes()).padStart(2, "0");
  const second = String(now.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day}_${hour}.${minute}.${second}`;
}

function customFileNameFormatter(urlStr) {
  let cleanPath = urlStr;
  try {
    cleanPath = decodeURIComponent(urlStr);
  } catch (e) {
    cleanPath = urlStr;
  }
  cleanPath = cleanPath.replace(/\\/g, "/");
  const originalFileName = path.basename(cleanPath);
  const timePrefix = formatTime();
  return originalFileName
    ? `${timePrefix} ${originalFileName}`
    : `${timePrefix}.png`;
}

/**
 * 原有纯函数调用方式（保留，兼容现有代码）
 */
async function batchDownloadUrls(urlStr, targetDir, options = {}) {
  return batchDownloadByStr(urlStr, targetDir, {
    baseUrl: getHostApi().fileApiUrl,
    fileNameFormatter: customFileNameFormatter,
    ...options
  });
}

/* ===================== 新增：IPC 任务管理模块（独立锁，与原素材隔离） ===================== */
const taskState = {
  isRunning: false,
  latestResult: { success: [], failed: [], currentBatchNo: "" }
};

/**
 * 向所有窗口广播状态
 */
function broadcastStatus() {
  const allWindows = BrowserWindow.getAllWindows();
  allWindows.forEach(win => {
    if (!win.isDestroyed()) {
      win.webContents.send("download-typesetting:status", {
        isRunning: taskState.isRunning,
        currentBatchNo: taskState.currentBatchNo,
        result: taskState.latestResult
      });
    }
  });
}

/**
 * 提交下载任务（异步执行，立即返回）
 */
function submitTask(params) {
  const { urlStr, targetPath, batchArrangeNum } = params;
  taskState.currentBatchNo = batchArrangeNum;
  // 全局互斥：有任务在跑直接拒绝
  if (taskState.isRunning) {
    return {
      code: 500,
      msg: "当前正在下载手动排版素材，请等待完成后再操作",
      data: { isRunning: true }
    };
  }

  if (!urlStr || typeof urlStr !== "string") {
    return { code: 500, msg: "下载链接为空或格式无效" };
  }

  // 加锁
  taskState.isRunning = true;
  taskState.latestResult = { success: [], failed: [] };
  broadcastStatus();

  // 后台异步执行下载，不阻塞 IPC 返回
  batchDownloadUrls(urlStr, targetPath)
    .then(result => {
      taskState.latestResult = result;
    })
    .catch(err => {
      taskState.latestResult = {
        success: [],
        failed: [{ url: "", error: err.message || "下载任务异常中断" }]
      };
    })
    .finally(() => {
      taskState.isRunning = false;
      broadcastStatus();
      taskState.currentBatchNo = "";
    });

  return {
    code: 200,
    msg: "排版进行中，请查看处理状态，排版完成的素材至文件夹排版素材查看",
    data: { isRunning: true }
  };
}

/**
 * 查询当前下载状态
 */
function getStatus() {
  return {
    code: 0,
    data: {
      isRunning: taskState.isRunning,
      result: taskState.latestResult
    }
  };
}

/* ===================== 新增：IPC 事件注册 ===================== */
/**
 * 注册手动排版下载 IPC 事件
 * 在主进程入口调用一次即可
 */
function registerTypesettingDownloadIpc() {
  // 提交下载任务
  ipcMain.on("download-typesetting:submit", (event, params) => {
    const result = submitTask(params);
    event.sender.send("download-typesetting:submit-reply", result);
  });

  // 查询下载状态
  ipcMain.on("download-typesetting:getStatus", event => {
    const result = getStatus();
    event.sender.send("download-typesetting:getStatus-reply", result);
  });
}

/* ===================== 导出（兼容两种使用方式） ===================== */
module.exports = {
  // 原有纯函数，可直接在主进程内调用
  batchDownloadUrls,
  // IPC 注册函数，主进程入口调用
  registerTypesettingDownloadIpc
};
