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

/* ========== 任务管理模块（全局互斥锁 + 状态广播） ========== */
const taskState = {
  isRunning: false,
  currentBatchNo: "",
  latestResult: { success: [], failed: [] }
};

function broadcastStatus() {
  const allWindows = BrowserWindow.getAllWindows();
  allWindows.forEach(win => {
    if (!win.isDestroyed()) {
      win.webContents.send("download:status", {
        isRunning: taskState.isRunning,
        currentBatchNo: taskState.currentBatchNo,
        result: taskState.latestResult
      });
    }
  });
}

function submitTask(params) {
  const { urls, targetPath, batchArrangeNum } = params;

  if (taskState.isRunning) {
    return {
      code: 501,
      msg: `当前正在下载批次【${taskState.currentBatchNo}】，请等待完成后再操作`,
      data: { isRunning: true }
    };
  }

  if (!Array.isArray(urls) || urls.length === 0) {
    return { code: 500, msg: "下载链接数组为空" };
  }

  taskState.isRunning = true;
  taskState.currentBatchNo = batchArrangeNum || "未知批次";
  taskState.latestResult = { success: [], failed: [] };
  broadcastStatus();

  // 调用核心下载能力
  batchDownloadByList(urls, targetPath, {
    concurrency: 2,
    timeout: 30000,
    retryTimes: 1,
    baseUrl: getHostApi().fileApiUrl
  })
    .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: 200,
    data: {
      isRunning: taskState.isRunning,
      currentBatchNo: taskState.currentBatchNo,
      result: taskState.latestResult
    }
  };
}

/* ========== IPC 注册 ========== */
function registerDownloadIpc() {
  ipcMain.on("download:submit", (event, params) => {
    const result = submitTask(params);
    event.sender.send("download:submit-reply", result);
  });

  ipcMain.on("download:getStatus", event => {
    const result = getStatus();
    event.sender.send("download:getStatus-reply", result);
  });
}

module.exports = registerDownloadIpc;
