import { exec } from "child_process";

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

function zip(from, to) {
  return new Promise((resolve, reject) => {
    let dirName = path.join(to, uuid.v4());
    console.log(dirName);
    if (!fs.existsSync(dirName)) {
      fs.mkdirSync(dirName);
    }
    let arr = [];
    compressing.zip
      .uncompress(from, dirName, { zipFileNameEncoding: "gbk" })
      .then(() => {
        console.log("success");
        let data = fs.readdirSync(dirName);
        for (let i = 0; i < data.length; i++) {
          let fileName = uuid.v4() + ".png";
          let el = data[i];
          let file_path = path.join(dirName, el);
          console.log(file_path, to);
          fs.renameSync(file_path, path.join(to, fileName));
          arr.push({
            fileName: fileName,
            designId: data[i].split("_GCPS")[0],
            productionFile: path.join(to, fileName)
          });
        }

        fs.unlinkSync(from); // 删除压缩包
        fs.rmdirSync(dirName); // 删除目录文件
        // console.log(arr);
        resolve(arr);
      })
      .catch(err => {
        console.log(err);
        reject("压缩包解压失败");
      });
  });
}

// 下载素材
export const downloadImage = list => {
  return new Promise((resolve, reject) => {
    try {
      let dirPath = path.join(process.cwd(), "./print/Input/");
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
      }
      let count = 0;
      for (let i = 0; i < list.length; i++) {
        if (list[i].url && list[i].url.includes("http")) {
          let fileName = "";
          let type = 2;
          let flag =
            [
              ".zip",
              ".gzip",
              ".tar",
              ".taz",
              ".rar",
              ".7z",
              ".gz",
              ".bz2"
            ].filter(el => list[i].url.toLowerCase().includes(el)).length > 0;
          if (flag) {
            fileName = list[i].url.split("/")[
              list[i].url.split("/").length - 1
            ];
            type = 1;
          } else {
            fileName = uuid.v4() + ".png";
            type = 2;
          }
          let p = path.join(process.cwd(), "./print/Input/" + fileName);
          let stream = fs.createWriteStream(p);
          request(list[i].url)
            .pipe(stream)
            .on("close", async function() {
              if (type === 1) {
                list[i].list = await zip(p, dirPath);
                if (count === list.length - 1) {
                  resolve(list);
                }
              } else {
                if (!list[i].list) list[i].list = [];
                const filename = list[i].url.split("/")[
                  list[i].url.split("/").length - 1
                ];
                list[i].list.push({
                  fileName,
                  productionFile: p,
                  designId: filename.split("_GCPS")[0]
                });
              }
              if (count === list.length - 1) {
                console.log(list);
                resolve(list);
              }
              count++;
            });
        }
      }
    } catch (err) {
      console.log(err);
      reject(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 => {
              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);
  }
};
