var fs = require("fs");
var path = require('path');
const { createCanvas, loadImage } = require('canvas')

let MaxRectsPacker = require("maxrects-packer").MaxRectsPacker;

var aaa =require()

var pathName = "./psd/common"
//读文件夹
var files = fs.readdirSync(pathName);
//找出所有png图片
var images = [];
let count = 0, countAll = files.length;
files.forEach(async function (fileName) {
    if (path.extname(fileName).indexOf(".png") < 0) {
        if (++count == countAll) tm()
        return;
    }
    // console.log(img)
    images.push(
        await handleImage(fileName)
    )
    if (++count == countAll) tm()
})
//开始处理
function tm() {
    // console.log(images)
    // return
    const options = {
        smart: true,
        pot: false,//是否powerOf2
        square: false,
        allowRotation: true,
        tag: false,
        border: 2
    }; // Set packing options
    let packer = new MaxRectsPacker(2048, 2048, 2, options); // width, height, padding, options
    //  console.log(packer.options)
    packer.addArray(images);

    packer.bins.forEach((bin, i) => {
        console.log(bin);
        var canvas = createCanvas(bin.width, bin.height)
        var ctx = canvas.getContext("2d");
        var obj = {}
        bin.rects.forEach((rect) => {
            ctx.save()
            if (rect.rot) {
                ctx.translate(rect.x, rect.y);
                ctx.rotate(Math.PI / 2)
                ctx.translate(-rect.x, -rect.y);
                ctx.drawImage(rect.imgData, rect.x, rect.y - rect.height)
            } else {
                ctx.drawImage(rect.imgData, rect.x, rect.y)
            }
            ctx.restore();
            //数据
            obj[rect.name] = {
                "x": rect.x,
                "y": rect.y,
                "w": rect.width,
                "h": rect.height,
                "ox": rect.offsetX ? rect.offsetX : 0,
                "oy": rect.offsetY ? rect.offsetY : 0,
                "sw": rect.originW,
                "sh": rect.originH,
                "ro": rect.rot,
            }
        })
        canvas.createPNGStream().pipe(fs.createWriteStream("./psd/out.png"));
        fs.writeFileSync("./psd/out.json", JSON.stringify(obj, "", "\t"));
    });

}
// console.log(images.length)
/**
 * 处理图片
 * @param {*} imgName 
 */
async function handleImage(imgName) {
    // console.log(image(fs.readFileSync(pathName + "/" + (imgName)))) 
    const myimg = await loadImage(fs.readFileSync(pathName + "/" + (imgName))/*'./image/b.png'*/).catch((err) => { });
    if (!myimg) {
        return null
    }
    const canvas = createCanvas(myimg.width, myimg.height)
    const ctx = canvas.getContext('2d');
    ctx.drawImage(myimg, 0, 0)
    var imageData = ctx.getImageData(0, 0, myimg.width, myimg.height);
    if (!needTrim(imageData)) {
        return {
            name: imgName,
            width: myimg.width,
            height: myimg.height,
            originW: myimg.width,
            originH: myimg.height,
            imgData: myimg,
        }
    } else {
        const pixels = imageData.data;
        const len = pixels.length;
        const bound = {
            top: null,
            left: null,
            right: null,
            bottom: null,
        };
        let i;
        let x;
        let y;
        let width = myimg.width, height = myimg.height
        for (i = 0; i < len; i += 4) {
            if (pixels[i + 3] !== 0) {
                x = (i / 4) % width;
                y = ~~((i / 4) / width);

                if (bound.top === null) {
                    bound.top = y;
                }

                if (bound.left === null) {
                    bound.left = x;
                }
                else if (x < bound.left) {
                    bound.left = x;
                }

                if (bound.right === null) {
                    bound.right = x + 1;
                }
                else if (bound.right < x) {
                    bound.right = x + 1;
                }

                if (bound.bottom === null) {
                    bound.bottom = y;
                }
                else if (bound.bottom < y) {
                    bound.bottom = y;
                }
            }
        }

        width = bound.right - bound.left;
        height = bound.bottom - bound.top //+ 1;

        const data = ctx.getImageData(bound.left, bound.top, width, height);
        var cc = createCanvas(width, height)
        cc.getContext("2d").putImageData(data, 0, 0)
        return {
            offsetX: bound.left,
            offsetY: bound.top,
            name: imgName,
            width: width,
            height: height,
            originW: myimg.width,
            originH: myimg.height,
            imgData: cc,
        };
    }
}
/**
 * 判断是否要进行透明度裁切
 * @param {*} imageData 
 */
function needTrim(imageData) {
    const width = imageData.width;
    const height = imageData.height;
    const pixels = imageData.data;

    const len = pixels.length;
    //4条边缘，有任何一条出现全透明像素就要进行裁切
    let hasPix = false;
    //上边缘
    for (var i = 0; i < width; i++) {
        if (pixels[i * 4 + 3] !== 0) {
            hasPix = true;
            break
        }
    }
    if (!hasPix) return true;

    //下边缘
    hasPix = false;
    for (var i = 0; i < width; i++) {
        if (pixels[width * (height - 1) * 4 + i * 4 + 3] !== 0) {
            hasPix = true;
            break
        }
    }
    if (!hasPix) return true;
    //左边缘
    hasPix = false;
    for (var i = 0; i < height; i++) {
        if (pixels[width * i * 4 + 3] !== 0) {
            hasPix = true;
            break
        }
    }
    //右边缘
    hasPix = false;
    for (var i = 0; i < height; i++) {
        if (pixels[width * i * 4 + 3 + (width - 1) * 4] !== 0) {
            hasPix = true;
            break
        }
    }
    if (!hasPix) return true;
    return false
}