const fs = require("fs");
const path = require("path");
const sharp = require("sharp");

/**
 * 裁切单个图片的透明白边
 * @param {string} inputPath - 输入图片路径
 * @param {string} outputPath - 输出图片路径
 * @param {Object} options - 配置选项
 * @param {number} options.threshold - 透明度阈值，0-255之间，默认为10
 * @returns {Promise<Object>} - 返回处理结果
 */
async function cropImageTransparentEdges(inputPath, outputPath, options = {}) {
  const threshold = options.threshold || 10;

  // 确保输出目录存在
  const outputDir = path.dirname(outputPath);
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
  console.log(21, outputDir);

  try {
    // 读取图片信息
    const metadata = await sharp(inputPath).metadata();

    // 提取图片的透明通道信息
    const { data, info } = await sharp(inputPath)
      .raw()
      .ensureAlpha()
      .toBuffer({ resolveWithObject: true });

    const { width, height, channels } = info;

    // 找到图片的边界
    let topmost = height;
    let bottommost = 0;
    let leftmost = width;
    let rightmost = 0;

    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        const alphaIdx = (y * width + x) * channels + channels - 1;
        const alpha = data[alphaIdx];

        // 如果像素不是透明的（根据阈值）
        if (alpha > threshold) {
          topmost = Math.min(topmost, y);
          bottommost = Math.max(bottommost, y);
          leftmost = Math.min(leftmost, x);
          rightmost = Math.max(rightmost, x);
        }
      }
    }

    // 如果图片全透明，保持原样
    if (topmost > bottommost || leftmost > rightmost) {
      await sharp(inputPath).toFile(outputPath);
      return {
        status: "unchanged",
        reason: "全透明图片",
        inputPath,
        outputPath,
      };
    }

    // 计算裁切区域
    const cropWidth = rightmost - leftmost + 1;
    const cropHeight = bottommost - topmost + 1;

    // 裁切并保存图片
    await sharp(inputPath)
      .extract({
        left: leftmost,
        top: topmost,
        width: cropWidth,
        height: cropHeight,
      })
      .toFile(outputPath);

    return {
      status: "cropped",
      inputPath,
      outputPath,
      originalSize: { width: metadata.width, height: metadata.height },
      newSize: { width: cropWidth, height: cropHeight },
    };
  } catch (error) {
    return {
      status: "error",
      inputPath,
      outputPath,
      error: error.message,
    };
  }
}

/**
 * 裁切图片目录中的所有图片的透明白边
 * @param {string} inputDir - 输入图片目录
 * @param {string} outputDir - 输出图片目录
 * @param {Object} options - 配置选项
 * @param {number} options.threshold - 透明度阈值，0-255之间，默认为10
 * @returns {Promise<Array>} - 返回处理结果数组
 */
async function cropTransparentEdges(inputDir, outputDir, options = {}) {
  // 确保输出目录存在
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  // 获取输入目录中的所有图片文件
  const files = fs.readdirSync(inputDir).filter((file) => {
    const ext = path.extname(file).toLowerCase();
    return [".png", ".jpg", ".jpeg", ".webp"].includes(ext);
  });

  const results = [];

  // 处理每个图片
  for (const file of files) {
    const inputPath = path.join(inputDir, file);
    const outputPath = path.join(outputDir, file);

    const result = await cropImageTransparentEdges(
      inputPath,
      outputPath,
      options
    );
    results.push({ file, ...result });
  }

  return results;
}

/**
 * 处理图片并输出结果
 * @param {string} inputPath - 输入图片路径或目录
 * @param {string} outputPath - 输出图片路径或目录
 * @param {Object} options - 配置选项
 * @param {number} options.threshold - 透明度阈值，0-255之间，默认为10
 */
async function processImages(inputPath, outputPath, options = {}) {
  console.log(`开始处理图片，从 ${inputPath} 到 ${outputPath}`);

  try {
    let results = [];

    // 检查输入是文件还是目录
    const inputStat = fs.statSync(inputPath);

    if (inputStat.isDirectory()) {
      // 如果输入是目录，检查输出是否有扩展名
      const outputExt = path.extname(outputPath);
      if (outputExt) {
        throw new Error("如果输入是目录，输出也必须是目录");
      }

      // 处理目录下的所有图片
      results = await cropTransparentEdges(inputPath, outputPath, options);
    } else {
      // 处理单个图片
      const result = await cropImageTransparentEdges(
        inputPath,
        outputPath,
        options
      );
      results = [{ file: path.basename(inputPath), ...result }];
    }

    console.log("处理完成!");
    console.log(
      `成功处理: ${results.filter((r) => r.status === "cropped").length} 张图片`
    );
    console.log(
      `保持不变: ${
        results.filter((r) => r.status === "unchanged").length
      } 张图片`
    );
    console.log(
      `处理失败: ${results.filter((r) => r.status === "error").length} 张图片`
    );

    return results;
  } catch (error) {
    console.error("处理图片过程中出错:", error);
    throw error;
  }
}

module.exports = {
  cropTransparentEdges,
  cropImageTransparentEdges,
  processImages,
};
