var fs = require("fs");
var iconv = require('iconv-lite');
var path = require('path');
//用于处理带base64图片的lottie文件，取出图片，同名lottie文件夹，写入代码"./src/lotties/"中;

var pathName = "./lotties"
//读文件夹
var files = fs.readdirSync(pathName);
//对每个json文件作处理
files.forEach(function (lottiesFileName) {
    //后缀不是json的，不处理
    if (path.extname(lottiesFileName).indexOf(".json") < 0) return;
    //读数据
    var data = iconv.decode(fs.readFileSync(pathName + "/" + lottiesFileName), "utf-8");//GBK
    //反序列化
    data = JSON.parse(data);
    //存图片
    var assets = data.assets;
    if (!assets || !assets.length) return;
    //删除属性
    delete data.assets;
    var imgOutPath = pathName + "/" + data.nm
    //建文件夹data.nm
    if (!fs.existsSync(imgOutPath)) fs.mkdirSync(imgOutPath);
    assets.forEach((e) => {
        //没有base64数据
        if (!e.p) return
        let id = e.id;
        let uuid = guid();
        //存图片
        var base64 = e.p.replace(/^data:image\/\w+;base64,/, "");//去掉图片base64码前面部分data:image/png;base64
        var dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象，
        fs.writeFile(imgOutPath + "/" + uuid + ".png", dataBuffer, ()=>0);
        //修改用到id的所有refId
        data.layers.forEach((l) => { l.refId === id && (l.refId = uuid) })
    })
    //开始删东西
    delete data.ddd;
    //遍历删除图层东西
    for (var i = 0; i < data.layers.length; i++) {
        var l = data.layers[i];
        //是否3d,后缀,sr,ap,开始时间，混合模式，特效
        ["ddd", "cl", "sr", "ao", "st", "bm", "ef"].forEach((e) => { delete l[e]; });
        //ks删除
        ["o", "r", "p", "a", "s"].forEach((e) => {
            var d = l.ks[e];
            //ix不知道干嘛用，删了
            delete d.ix;
            //删除k里数据
            if (d.k.length && typeof d.k[0] == "object") {
                d.k.forEach((ee) => {
                    ["i", "o", "ti", "to"].forEach((eee) => { delete ee[eee]; })
                })
            }
        })
    }

    //导出代码到src的lotties文件夹，名字就是lottie动画名字，资源名字临时处理了，首页加载动画用图层的nm，bonustime用refid
    var endPath = './src/lotties';
    if (!fs.existsSync(endPath)) fs.mkdirSync(endPath);
    //导出对象直接用lottie动画名字
    var endFile = `export const ${data.nm} = ${JSON.stringify(data, "", "\t")}`
    //文件名字用lottie动画名字
    fs.writeFileSync(endPath + "/" + data.nm + ".ts", endFile);
})

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}



