const path = require("path");
const { pathMap } = require("@/config/index.js");
const { getDTFSetting, getHostApi } = require("@/server/utils/store");
import api from "./request";
const { batchDownloadByStr } = require("./download-core.js");

/* ========== 全局状态 ========== */
const taskState = {
  currentPage: 1,
  pageSize: 100,
  layoutStatus: "3,5",
  isDownloading: false,
  timer: null,
  total: 0,
  interval: 1 * 60 * 1000,
  maxBatchConcurrency: 3,
  maxImageConcurrency: 10
};

/* ========== 工具函数（业务专属，保留） ========== */
function logDownloadError(type, batchNo, url, message) {
  console.error(
    `[自动下载失败][${type}] 批次号: ${batchNo || "未知"} | 链接: ${url ||
      "-"} | 详情: ${message}`
  );
}

// 复用core的并发控制器，也可以直接用core导出的pLimit
const { pLimit } = require("./download-core");

/* ========== 业务逻辑 ========== */
async function processBatchItem(item) {
  const { batchArrangeNum, url: urlStr } = item;

  if (!batchArrangeNum) {
    logDownloadError(
      "参数无效",
      batchArrangeNum,
      "",
      "缺少批次号batchArrangeNum"
    );
    return;
  }
  if (!urlStr || typeof urlStr !== "string") {
    logDownloadError(
      "参数无效",
      batchArrangeNum,
      urlStr,
      "url字段为空或非字符串格式"
    );
    return;
  }

  // 构建保存目录
  let saveDir;
  try {
    const downloadRoot = getDTFSetting().downloadDir;
    if (!downloadRoot) throw new Error("下载根目录downloadDir配置为空");
    saveDir = path.join(
      downloadRoot,
      `批次号：${batchArrangeNum}`,
      "自动排版素材"
    );
  } catch (dirErr) {
    logDownloadError("目录创建失败", batchArrangeNum, "", dirErr.message);
    return;
  }

  // 调用核心批量下载
  await batchDownloadByStr(urlStr, saveDir, {
    concurrency: taskState.maxImageConcurrency,
    timeout: 30000,
    baseUrl: getHostApi().fileApiUrl
  });
}

async function runTask() {
  if (taskState.isDownloading) {
    console.log("当前有下载任务进行中，跳过本轮定时任务");
    return;
  }

  try {
    taskState.isDownloading = true;
    console.log(`=== 开始执行定时任务，当前页码：${taskState.currentPage} ===`);

    // 获取排版策略
    const settingRes = await api.post(pathMap["productionConfig"]);
    if (settingRes.data.autoLayoutStrategy === 3) {
      console.log("不自动排版，跳过本次下载");
      return;
    }

    // 拉取排版数据
    const layoutRes = await api.post(pathMap["productionSoftware"], {
      currentPage: taskState.currentPage,
      pageSize: taskState.pageSize,
      layoutStatus: taskState.layoutStatus
    });

    const list = layoutRes.data.records || [];
    taskState.total = layoutRes.data.total || 0;

    if (list.length === 0) {
      console.log("当前页无数据，本轮任务结束");
      return;
    }

    // 多批次并行下载
    const batchLimit = pLimit(taskState.maxBatchConcurrency);
    const batchPromises = list.map(item =>
      batchLimit(() => processBatchItem(item))
    );
    await Promise.all(batchPromises);

    console.log(`=== 第 ${taskState.currentPage} 页全部处理完成 ===`);

    // 更新页码
    taskState.currentPage++;
    if ((taskState.currentPage - 1) * taskState.pageSize >= taskState.total) {
      taskState.currentPage = 1;
      console.log("已遍历全部数据，下轮任务从第1页重新开始");
    }
  } catch (err) {
    console.error("定时任务执行异常：", err.message);
  } finally {
    taskState.isDownloading = false;
    console.log("本轮任务结束，锁已释放");
  }
}

/* ========== 对外启停方法 ========== */
function startAutoDownloadTask() {
  if (taskState.timer) return;
  console.log("自动下载定时任务已启动，5分钟后首次执行");
  taskState.timer = setInterval(runTask, taskState.interval);
}

function stopAutoDownloadTask() {
  if (taskState.timer) {
    clearInterval(taskState.timer);
    taskState.timer = null;
    taskState.isDownloading = false;
    console.log("自动下载定时任务已停止");
  }
}

export default {
  startAutoDownloadTask,
  stopAutoDownloadTask
};
