import fs from "fs";
import { exec, execFile, execSync } from "child_process";
import path from "path";

const pngquantPath = "E:\\Duiba\\project\\江苏银行\\套圈\\JiangSuBankTaoQuan_20240108\\extensions\\duiba-publish\\pngquant\\windows\\pngquant";

const getImages = (dir, imgs) => {
  const files = fs.readdirSync(dir);
  files.forEach((file) => {
    const imgPath = path.join(dir, file);
    const stat = fs.statSync(imgPath);
    if (stat.isDirectory()) {
      getImages(imgPath, imgs);
    }
    else {
      if (file.endsWith(".png")) {
        imgs.push(imgPath);
      }
    }
  });
};

const qualityParam = `--quality 0-99`,
    speedParam = `--speed 3`,
    skipParam = '',
    outputParam = '--ext=.png',
    writeParam = '--force -v',
    // colorsParam = config.colors,
    // compressOptions = `${qualityParam} ${speedParam} ${skipParam} ${outputParam} ${writeParam} ${colorsParam}`;
    compressOptions = `${qualityParam} ${speedParam} ${skipParam} ${outputParam} ${writeParam}`;

const dir = "E:\\Duiba\\test大苏打";
const tempDir = `C:\\Temp\\duiba\\${now}`

if (!fs.existsSync("C:\\Temp")){
    fs.mkdirSync("C:\\Temp");
}

if (!fs.existsSync("C:\\Temp\\duiba")){
    fs.mkdirSync("C:\\Temp\\duiba");
}

if (!fs.existsSync(tempDir)){
    fs.mkdirSync(tempDir);
}

const imgs = [];
getImages(dir, imgs);

// let command = "";
imgs.forEach((imgPath, idx) => {
    console.log(imgPath);

    const tempName = `${tempDir}\\${idx}_${path.basename(imgPath)}`;
    fs.copyFileSync(imgPath, tempName);
    execSync(`"${pngquantPath}" ${compressOptions} "${tempName}"`);
    fs.copyFileSync(tempName, imgPath);

});

fs.rmSync(tempDir, { recursive: true });

// console.log(imgs.length);
// exec(command, (err, stdout, stderr) => {
//     if (err) {
//         console.error(err);
//     } else {
//         console.log(123123123);
//     }
// });

