import {
  downloadImage,
  downloadOtherImage,
  toSend,
  writeProfileXml,
} from "@/server/utils";
const {
  cropImageTransparentEdges,
  cropTransparentEdges,
  processImages,
} = require("../utils/setImage");
import axios from "axios";
import { returnLogFilePath } from "../utils/log";
var request = require("request");
const compressing = require("compressing");
const uuid = require("uuid");
const path = require("path");
const fs = require("fs");
const os = require("os");
const { app } = require("electron");
let fileEnv, env, visionUrl;
axios.defaults.timeout = 12600000;
const multiparty = require("multiparty");

function readEnv() {
  let exePath, configPath;
  if (process.env.NODE_ENV === "development") {
    configPath = path.join(__dirname, "../config/env.json");
  } else {
    exePath = path.dirname(app.getPath("exe")).replace(/\\/g, "/");
    configPath = `${exePath}/config/env.json`;
  }
  console.log(configPath, __dirname);
  fs.readFile(configPath, "utf-8", (err, data) => {
    if (err) {
      console.error("读取配置文件失败:", err);
      return;
    }
    const config = JSON.parse(data);
    fileEnv = config.fileApiUrl;
    env = config.apiApiHost;
    visionUrl = config.visionUrl;
  });
}
readEnv();
export default {
  writePrintLog: async (req, res) => {
    try {
      let body = req.body;
      let p = path.join(returnLogFilePath(), "print.json");
      p = p.replace("\\api.log", "");
      console.log(p);
      let data = [];
      if (!fs.existsSync(p)) {
        fs.writeFileSync(p, "[]");
        data = [];
      } else {
        data = fs.readFileSync(p, { encoding: "utf-8" });
        data = JSON.parse(data);
      }
      data.unshift(body);
      fs.writeFileSync(p, JSON.stringify(data));
      res.json({ code: 200 });
    } catch (e) {
      res.json({ code: 500, msg: e });
    }
  },
  downloadBySubOrderNumber: async (req, res) => {
    const params = req.body;

    const token = req.headers["jwt-token"];
    console.log(72, params);

    let url =
      params.type === "CN"
        ? "factory/podJomallOrder/downloadByProduction"
        : "factory/podJomallOrderProductUs/downloadDesignImages";
    try {
      let { data } = await axios.post(`${env}/${url}`, [...params.ids], {
        headers: { "jwt-token": token },
      });
      let files = [];
      console.log(81, data);

      if (data.code === 200) {
        if (!data.data) data.data = [data.message];
        files = data.data;
        files = files.map((el) => {
          return { url: `${fileEnv}${el}` };
          // return { url: `${el}` };
        });

        if (params.device === 1) {
          downloadImage(files)
            .then((data) => {
              res.json({ code: 200, data });
            })
            .catch((err) => {
              res.json({ code: 500, msg: err });
            });
        } else {
          downloadOtherImage(files)
            .then((data) => {
              console.log(77, data);

              res.json({ code: 200, data });
            })
            .catch((err) => {
              res.json({ code: 500, msg: err });
            });
        }
      } else {
        res.json(data);
      }
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },
  findByPodProductionNo: async (req, res) => {
    const token = req.headers["jwt-token"];
    const params = req.body;
    let url =
      params.type === "CN"
        ? "factory/podJomallOrderProduct/getSubOrderByThirdSubOrderNumber"
        : "factory/podJomallOrderProductUs/getProductUsByFactorySubOrderNumber";
    let paramsField =
      params.type === "CN" ? "thirdSubOrderNumber" : "factorySubOrderNumber";
    try {
      let { data } = await axios.get(`${env}/${url}`, {
        params: {
          [paramsField]: params.thirdSubOrderNumber,
        },
        headers: { "jwt-token": token },
      });
      res.json(data);
    } catch (err) {
      res.json({ code: 500, msg: err });
    }
  },
  getCompanyList: async (req, res) => {
    try {
      let { data } = await axios.get(
        "https://platform.jomalls.com/api/tools/getCompanyList"
      );
      res.send(data);
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },
  commitApply: async () => {},
  completeDelivery: async (req, res) => {
    const token = req.headers["jwt-token"];
    const params = req.body;
    let url =
      params.type === "CN"
        ? "factory/podJomallOrderProduct/completeDelivery"
        : "factory/podJomallOrderProductUs/completeDelivery";

    let postData =
      params.type === "CN"
        ? { id: params.id }
        : { id: params.id, podJomallOrderUsId: params.podJomallOrderUsId };
    try {
      let { data } = await axios.post(`${env}/${url}`, postData, {
        headers: { "jwt-token": token },
      });
      res.send(data);
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },
  downloadByDesignId: async (req, res) => {
    let q = req.body;
    try {
      let dir = path.join(os.homedir(), "/Desktop/" + q.productionNo + ".zip");
      const zipStream = new compressing.zip.Stream();

      for (let k in q.imgList) {
        const p = path.join(
          process.cwd(),
          "./print/Input/" + q.imgList[k].fileName
        );
        zipStream.addEntry(p);
      }

      const destStream = fs.createWriteStream(dir);
      zipStream
        .pipe(destStream)
        .on("finish", () => {
          console.log("success");
          res.json({
            code: 200,
            msg: q.productionNo + ".zip" + "已下载到桌面",
          });
        })
        .on("error", () => {
          res.json({ code: 500, msg: "文件下载失败" });
        });
      // let ws=fs.createWriteStream(dir );
      // console.log(downloadByDesignId)
      //
      // ws.write(downloadByDesignId.data);
      // ws.on('drain',function () {
      //     console.log("内存干了");
      // });
      // ws.on('error',function (err) {
      //     res.json({code: 500, msg: '文件下载失败'})
      // });
      // ws.on('close',function (err) {
      //
      // });
      // ws.end()
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },
  uploadImage: async (req, res) => {
    try {
      const p = path.join(process.cwd(), "./print/Input/");
      let fileName = uuid.v4() + ".png";
      console.log(fileName);

      const form = new multiparty.Form({ uploadDir: p });
      form.parse(req, function(err, fields, files) {
        console.log(fields, files, err);
        if (err) {
          res.send({ code: 500, err });
        } else {
          fs.renameSync(files.file[0].path, path.join(p, fileName));
          res.json({
            code: 200,
            data: {
              fileName,
              url: path.join(process.cwd(), "./print/Input/" + fileName),
            },
          });
        }
      });
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },
  getPngImg: async (req, res) => {
    try {
      const filePath = path.join(
        process.cwd(),
        `./print/Input/${req.body.fileName}`
      );
      console.log(filePath);
      // 给客户端返回一个文件流 type类型
      res.set("content-type", { png: "image/png", jpg: "image/jpeg" }); //设置返回类型
      let stream = fs.createReadStream(filePath);
      let responseData = []; //存储文件流
      if (stream) {
        //判断状态
        stream.on("data", function(chunk) {
          responseData.push(chunk);
        });
        stream.on("end", function() {
          const finalData = Buffer.concat(responseData);
          res.write(finalData);
          res.end();
        });
      }
    } catch (err) {
      res.send({ code: 500, msg: err });
    }
  },
  login: async (req, res) => {
    try {
      console.log(`${env}/factory/login`);
      let { data } = await axios.post(`${env}/factory/login`, req.body);
      res.send(data);
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },
  toPrint: (req, res) => {
    let body = req.body;
    writeProfileXml(body); // 写入xml文件
    // GTXproCMD.exe print -X "Profile\\CO12.xml" -I "Input\\sample.png" -A "Output\\pO12.arxp" -S 03000400 -L 02540254
    console.log(249, body);

    toSend(body)
      .then(() => {
        res.send({ code: 200, msg: "操作成功" });
      })
      .catch((err) => {
        res.send({ code: 500, msg: err });
      });
  },
  checkUpdate: async (req, res) => {
    console.log("version", req.query.version);
    const company = "https://admin.jomalls.com";
    try {
      let q = `${company}/api/manage/rest/app/checkUpdate?version=${req.query.version}&businessType=production_assistant`;

      let { data } = await axios.get(q);
      console.log("q", q);
      console.log("data", data);

      if (data.data) {
        q = `${company}/api/manage/rest/app/getLatest?businessType=production_assistant`;
        let r = await axios.get(q);
        res.send(r.data);
      } else {
        res.send(data);
      }
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },

  incrementalUpdates: async (req, res) => {
    try {
      let from = path.join(process.cwd(), "./resources/app/css.zip");
      let dirName = path.join(process.cwd(), "./resources/app/");
      let stream = fs.createWriteStream(from);
      req.body.url = visionUrl + req.body.url;
      console.log(req.body.url, "下载zip地址");
      request(req.body.url)
        .pipe(stream)
        .on("close", function() {
          compressing.zip
            .uncompress(from, dirName, { zipFileNameEncoding: "gbk" })
            .then(() => {
              fs.unlinkSync(from);
              res.json({ code: 200, msg: "更新成功" });
            })
            .catch((err) => {
              res.json({ code: 500, msg: err.message });
            });
        });
    } catch (err) {
      res.json({ code: 500, msg: err.message });
    }
  },
  //裁切单个图片的透明白边
  imageTransparentEdges: async (req, res) => {
    const { inputPath, outputPath } = req.body;
    try {
      const data = await cropImageTransparentEdges(inputPath, outputPath);

      res.json({ code: 200, msg: data });
    } catch (err) {
      res.json({ code: 500, msg: err.message });
    }
  },
  //裁切图片目录中的所有图片的透明白边
  imageListTransparentEdges: async (req, res) => {
    const { inputDir, outputDir } = req.body;
    try {
      const data = await cropTransparentEdges(inputDir, outputDir);

      res.json({ code: 200, msg: data });
    } catch (err) {
      res.json({ code: 500, msg: err.message });
    }
  },
  //输入图片路径或目录
  processImage: async (req, res) => {
    const { inputPath, outputPath } = req.body;
    try {
      const data = await processImages(inputPath, outputPath);

      res.json({ code: 200, msg: data });
    } catch (err) {
      res.json({ code: 500, msg: err.message });
    }
  },
  saveToPng: async (req, res) => {
    try {
      const p = path.join(process.cwd(), "./print/Input/");
      const form = new multiparty.Form({ uploadDir: p });
      form.parse(req, function(err, fields, files) {
        console.log(367, fields, files, err);
        if (err) {
          res.send({ code: 500, err });
        } else {
          let list = [];
          files.files.forEach((file) => {
            let fileName = uuid.v4() + ".png";
            fs.renameSync(file.path, path.join(p, fileName));
            list.push({
              fileName,
              url: path.join(process.cwd(), "./print/Input/" + fileName),
            });
          });
          res.json({
            code: 200,
            data: list,
          });
        }
      });
    } catch (err) {
      console.log(err);
      res.json({ code: 500, msg: err });
    }
  },
};
