import {exec, execSync} from "child_process";

var fs = require("fs");
var path = require("path");
var request = require("request");
var uuid = require("uuid");

// 下载素材
export const downloadImage = (list, company, callback, errorBack = null) => {
    try {
        let dirPath = path.join(process.cwd(), "./print/Input/");
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath);
        }
        for (let i = 0; i < list.length; i++) {
            if (!list[i].productionFile) return
            if (!list[i].productionFile.includes('http')) return;
            let fileName = uuid.v4() + ".png";
            let p = path.join(process.cwd(), './print/Input/' + fileName)
            let stream = fs.createWriteStream(p);
            list[i].fileName = fileName
            request(list[i].productionFile).pipe(stream).on("close", function (err) {
                console.log("文件[" + fileName + "]下载完毕");
                if (i === list.length - 1) {
                    callback && callback(list)
                }
            });
        }

    } catch (err) {
        console.log(err)
        errorBack && errorBack(err)
    }


}

// 传递素材给前端
export const sendImg = (filename = 'sample.png') => {
    let filePath = path.join(process.cwd(), './print/Input/' + filename)
    if (!fs.existsSync(filePath)) {
        return false
    }
    let data = fs.readFileSync(filePath);
    data = Buffer.from(data).toString('base64');
    return 'data:' + 'png' + ';base64,' + data;

}

export const toSend = (body) => {
    return new Promise((resolve, reject) => {
        exec(
            body.cmd,
            {cwd: path.join(process.cwd(), 'print'), shell: true},
            (err, stdout, stderr) => {
                console.log(stdout, 1)
                console.log(stderr, 2)
                console.log(err, 4)
                if (!err) {
                    exec(
                        body.print_cmd,
                        {cwd: path.join(process.cwd(), 'print'), shell: true},
                        (err2, stdout2, stderr2) => {
                            console.log(err2)
                            if (!err2) {
                                // 成功后删除 素材图，xml，output文件
                                // fs.unlinkSync(path.join(process.cwd(), 'print/Input/' + body.fileName))
                                // fs.unlinkSync(path.join(process.cwd(), 'print/Profile/' + body.fileName.replace('.png', '') + '.xml'))
                                // fs.unlinkSync(path.join(process.cwd(), 'print/Output/' + body.fileName.replace('.png', '') + '.arxp'))
                                resolve('操作成功')
                            } else {
                                reject('打印机参数错误')
                            }

                        })

                } else {
                    reject('生成arxp文件失败')
                }

            })
    })
}

export const writeProfileXml = (b) => {
    try {
        let p = path.join(process.cwd(), `./print/Profile/${b.byInk}.xml`);
        let file = fs.readFileSync(p, {encoding: "utf8"});
        file = file.replace(/<uiCopies>(.*)<\/uiCopies>/i, `<uiCopies>${b.printNum}</uiCopies>`)
        file = file.replace(/<byPlatenSize>(.*)<\/byPlatenSize>/i, `<byPlatenSize>${b.byPlatenSize}</byPlatenSize>`)
        file = file.replace(/<bEcoMode>(.*)<\/bEcoMode>/i, `<bEcoMode>${b.bEcoMode}</bEcoMode>`)
        file = file.replace(/<bMaterialBlack>(.*)<\/bMaterialBlack>/i, `<bMaterialBlack>${b.bMaterialBlack}</bMaterialBlack>`)
        file = file.replace(/<byHighlight>(.*)<\/byHighlight>/i, `<byHighlight>${b.byHighlight}</byHighlight>`)
        file = file.replace(/<byMask>(.*)<\/byMask>/i, `<byMask>${b.byMask}</byMask>`)
        file = file.replace(/<bTransColor>(.*)<\/bTransColor>/i, `<bTransColor>${b.bTransColor}</bTransColor>`)
        file = file.replace(/<bPause>(.*)<\/bPause>/i, `<bPause>${b.bPause}</bPause>`)
        file = file.replace(/<bDivide>(.*)<\/bDivide>/i, `<bDivide>${b.bDivide}</bDivide>`)
        file = file.replace(/<byChoke>(.*)<\/byChoke>/i, `<byChoke>${b.byChoke}</byChoke>`)
        file = file.replace(/<byInk>(.*)<\/byInk>/i, `<byInk>${b.byInk}</byInk>`)
        file = file.replace(/<bFastMode>(.*)<\/bFastMode>/i, `<bFastMode>${b.bFastMode}</bFastMode>`)
        file = file.replace(/<byResolution>(.*)<\/byResolution>/i, `<byResolution>${1}</byResolution>`)
        file = file.replace(/<byInkVolume>(.*)<\/byInkVolume>/i, `<byInkVolume>${b.byInkVolume}</byInkVolume>`)
        file = file.replace(/<byDoublePrint>(.*)<\/byDoublePrint>/i, `<byDoublePrint>${b.byDoublePrint}</byDoublePrint>`)
        file = file.replace(/<bMultiple>(.*)<\/bMultiple>/i, `<bMultiple>${b.bMultiple}</bMultiple>`)
        file = file.replace(/<bySaturation>(.*)<\/bySaturation>/i, `<bySaturation>${b.bySaturation}</bySaturation>`)
        file = file.replace(/<byBrightness>(.*)<\/byBrightness>/i, `<byBrightness>${b.byBrightness}</byBrightness>`)
        file = file.replace(/<byContrast>(.*)<\/byContrast>/i, `<byContrast>${b.byContrast}</byContrast>`)
        file = file.replace(/<iCyanBalance>(.*)<\/iCyanBalance>/i, `<iCyanBalance>${b.iCyanBalance}</iCyanBalance>`)
        file = file.replace(/<iMagentaBalance>(.*)<\/iMagentaBalance>/i, `<iMagentaBalance>${b.iMagentaBalance}</iMagentaBalance>`)
        file = file.replace(/<iYellowBalance>(.*)<\/iYellowBalance>/i, `<iYellowBalance>${b.iYellowBalance}</iYellowBalance>`)
        file = file.replace(/<iBlackBalance>(.*)<\/iBlackBalance>/i, `<iBlackBalance>${b.iBlackBalance}</iBlackBalance>`)
        file = file.replace(/<bUniPrint>(.*)<\/bUniPrint>/i, `<bUniPrint>${b.bUniPrint}</bUniPrint>`)
        fs.writeFileSync(path.join(process.cwd(), `./print/Profile/${b.fileName.replace('.png', '')}.xml`), file)

    } catch (err) {
        console.log(err)

    }
}
