/**
 * imageMin.js
 * Created by 还有醋v on 2022/9/29 下午7:19.
 * Copyright © 2022 haiyoucuv. All rights reserved.
 */

// const imagemin = require("imagemin");
// const imageminJpegtran = require('imagemin-jpegtran');imagemin-mozjpeg
// const imageminJpegtran = require("imagemin-mozjpeg");
// const imageminPngquant = require("imagemin-pngquant");
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");

const tinyImage = require("./tinyImage");

// 要处理的图片文件夹路径
const altasPath = "./released/resource/";

function getImgFiles(dir) {
	let fileArr = [];
	if (fs.existsSync(dir)) {
		const files = fs.readdirSync(dir);
		files.forEach((file) => {
			const fpath = dir + '/' + file;
			const stat = fs.lstatSync(fpath);
			if (stat.isFile() && /\.jpg|\.png|\.jpeg$/.test(file)) {
				fileArr.push(fpath);
			} else if (stat.isDirectory()) {
				fileArr.push(...getImgFiles(fpath));
			}
		});
	}
	return fileArr;
}

const folders = getFolders(altasPath);
folders.map(async (folder) => {
	// const files = await imagemin([altasPath + folder + '/*.{png,jpg}'], {
	//     destination: altasPath + folder,
	//     plugins: [
	//         imageminJpegtran(),
	//         imageminPngquant({
	//             quality: [0.6, 0.8]
	//         })
	//     ]
	// });

	// if (files && files.length) {
	// 	files.forEach((v) => {
	// 		console.log("压缩图片成功:", v.sourcePath.substring(v.sourcePath.lastIndexOf("/") + 1, v.sourcePath.length))
	// 	})
	// }

	// TODO 2022/07/12 修改到线上到图片压缩服务
	// TODO 2022/09/21 压缩图片并行压缩，图多能节省大量时间
	const files = getImgFiles(altasPath + folder);

	const ps = [];

	for (const file of files) {

		ps.push(
			tinyImage(file)
				.then((tinyBuffer) => {
					fs.writeFileSync(file, tinyBuffer);
					console.log(chalk.gray("压缩图片成功:" + file));
				})
				.catch((e) => {
					console.log(chalk.red("压缩图片失败:" + file));
				})
		);
	}

	await Promise.all(ps);
});


function getFolders(dir) {
	return fs.readdirSync(dir)
		.filter(function (file) {
			return fs.statSync(path.join(dir, file)).isDirectory();
		});
}
