const system = require("../../system")
const uuidv4 = require('uuid/v4');
const ApiBase = require("../api.base");
const fs = require("fs");
const mime = require("mime");
const gm = require("gm");
const imageMagick = gm.subClass({ imageMagick: true });
const puppeteer = require('puppeteer');
class ImageHandleApi extends ApiBase {
  constructor() {
    super();
    this.ossClient = system.getObject("util.ossClient");
    this.execClient = system.getObject("util.execClient");
  }
  //生成委托书
  async makeDeleForTM(obj) {
    //  var data= await this.checkKey(obj.appKey);
    //  if(data && data.status==-1){
    //    return data;
    //  }
    var urladdress = obj.url;
    const browser = await puppeteer.launch({
      args: ['--no-sandbox'],
      timeout: 10000,
    });
    console.log(urladdress);
    const page = await browser.newPage();
    //await page.setExtraHTTPHeaders({"Content-Type":"text/html;charset:utf-8;"});
    await page.goto(urladdress, { "waitUntil": 'networkidle2' });
    await page.waitFor(2000);
    var uuid = uuidv4();
    var u = uuid.replace(/\-/g, "");
    var filekey = "zc_" + u + ".pdf";
    var tmpfile = "/tmp/" + filekey;
    await page.pdf({ path: tmpfile, format: 'A4' });
    var rtn = await this.ossClient.upfile(filekey, tmpfile);
    await browser.close();
    fs.unlink(tmpfile, function (err) { });
    return system.getResult2({ "url": rtn.url }, null);
  }
  //商标营业执照处理，大小小于2M，宽高10-50cm
  //身份证同营业执照处理
  async bzLicenseForTM(obj) {
    console.log(obj);
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    //命令行
    //按照jpg路径参数下载jpg到临时目录，然后再转换
    var jpgpath = obj.jpgpath;
    var basename = obj.jpgpath.substring(0, obj.jpgpath.lastIndexOf("."));
    var jpgpathtmp = "/tmp/" + jpgpath;
    var epspath = "/tmp/" + basename + ".eps";
    var pdfpathKey = basename + ".pdf";
    var pdfpath = "/tmp/" + basename + ".pdf";
    var result = await this.ossClient.downfile(jpgpath);
    //转换为eps
    var cmd2eps = "jpeg2ps -p " + " a4 " + jpgpathtmp + " -o " + epspath;
    var x = await this.execClient.exec(cmd2eps);
    //转换为pdf
    var cmd2pdf = "ps2pdf -dDownsampleColorImages=true " + epspath + "  " + pdfpath;
    var y = await this.execClient.exec(cmd2pdf);
    //上传 pdfpath 到ossClient
    var rtn = await this.ossClient.upfile(pdfpathKey, pdfpath);
    fs.unlink(jpgpathtmp, function (err) { });
    fs.unlink(epspath, function (err) { });
    fs.unlink(pdfpath, function (err) { });
    return system.getResult2({ "url": rtn.url }, null);
  }
  //委托书小于2M 600-4000
  async deleForTM(obj) {

    console.log(obj);
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    //命令行
    //按照jpg路径参数下载jpg到临时目录，然后再转换
    var jpgpath = obj.jpgpath;
    var basename = obj.jpgpath.substring(0, obj.jpgpath.lastIndexOf("."));
    var jpgpathtmp = "/tmp/" + jpgpath;
    var epspath = "/tmp/" + basename + ".eps";
    var result = await this.ossClient.downfile(jpgpath);
    //转换为eps
    var cmd2eps = "jpeg2ps -p " + " a4  -r 300 " + jpgpathtmp + " -o " + epspath;
    var x = await this.execClient.exec(cmd2eps);
    //再转换为jpeg
    var cmd2jpg = "eps2jpg -h 3800px  -f " + epspath;
    var y = await this.execClient.exec(cmd2jpg);
    //上传 pdfpath 到ossClient
    var rtn = await this.ossClient.upfile(jpgpath, jpgpathtmp);
    fs.unlink(jpgpathtmp, function (err) { });
    fs.unlink(epspath, function (err) { });
    return system.getResult2({ "url": rtn.url }, null);
  }
  async onLineMakeTM(obj) {
    var word = obj.word;
    var fontsize = obj.fs;
    var bs = obj.bs;
    var uuid = uuidv4();
    var u = uuid.replace(/\-/g, "");
    var destfile = "zc_word2pic" + u + ".jpg";
    var d = await this._onLineMakeTM(word, fontsize, bs, "/tmp/" + destfile);
    var rtn = await this.ossClient.upfile(destfile, d);
    fs.unlink(d, function (err) { });
    return system.getResult2({ "url": rtn.url }, null);
  }
  //在线生成商标图样,bs大小,fs字体尺寸
  async _onLineMakeTM(word, fs, bs, destfile) {
    // var word=obj.word;
    // var fs=obj.fs;
    // var bs=obj.bs;
    // var uuid=uuidv4();
    // var u=uuid.replace(/\-/g,"");
    // var destfile= "zc_word2pic"+u+".jpg";
    var p = new Promise(function (resv, reject) {
      imageMagick(bs, bs, "#fff")
        .font(__dirname + "/fonts/heiti.otf")
        .fontSize(fs)
        .drawText(0, 0, word, "center")
        .write(destfile, function (err) {
          if (!err) {
            resv(destfile);
          } else {
            reject(err);
          }
        });
    });
    return p;
  }
  //商标图样,如果
  //转换为黑白
  //jpeg  -g参数
  async toblack(obj) {
    //下载
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    var jpgpath = obj.jpgpath;
    var basename = obj.jpgpath.substring(0, obj.jpgpath.lastIndexOf("."));
    var result = await this.ossClient.downfile(jpgpath);
    var jpgpathtmp = "/tmp/" + jpgpath;
    var bkimgpath = "/tmp/bk" + basename + ".jpg";
    var comimgpath = "/tmp/comimg" + basename + ".jpg";

    var size = await this._getImgSize(jpgpathtmp);
    var maxSize = Math.max(size.height, size.width);
    var scale = 0;//不缩放
    if (maxSize < 400) {
      maxSize = 500;
      scale = 1;//放大
    }
    if (maxSize > 1500) {
      maxSize = 1400;
      scale = 1;//缩小
    }
    //生成背景图片
    var bkimg = await this._onMakeTmBkPic(maxSize, bkimgpath);
    //合成图像
    var comimg = await this._composeImg(scale, maxSize, jpgpathtmp, bkimgpath, comimgpath);
    var grayimg = await this._grayImg(comimgpath);
    //上传覆盖元先的路径
    var rtn = await this.ossClient.upfile(jpgpath, comimgpath);
    fs.unlink(jpgpathtmp, function (err) { });
    fs.unlink(bkimgpath, function (err) { });
    fs.unlink(comimgpath, function (err) { });
    return system.getResult2({ "url": rtn.url }, null);
  }
  //调整图样大小
  async adjustTMSize(obj) {
    //下载
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    var jpgpath = obj.jpgpath;
    var basename = obj.jpgpath.substring(0, obj.jpgpath.lastIndexOf("."));
    var result = await this.ossClient.downfile(jpgpath);
    var jpgpathtmp = "/tmp/" + jpgpath;
    var bkimgpath = "/tmp/bk" + basename + ".jpg";
    var comimgpath = "/tmp/comimg" + basename + ".jpg";

    var size = await this._getImgSize(jpgpathtmp);
    var maxSize = Math.max(size.height, size.width);
    var scale = 0;//不缩放
    if (maxSize < 400) {
      maxSize = 500;
      scale = 1;//放大
    }
    if (maxSize > 1500) {
      maxSize = 1400;
      scale = 1;//缩小
    }
    //生成背景图片
    var bkimg = await this._onMakeTmBkPic(maxSize, bkimgpath);
    //合成图像
    var comimg = await this._composeImg(scale, maxSize, jpgpathtmp, bkimgpath, comimgpath);


    //上传覆盖元先的路径
    var rtn = await this.ossClient.upfile(jpgpath, comimgpath);
    fs.unlink(jpgpathtmp, function (err) { });
    fs.unlink(bkimgpath, function (err) { });
    fs.unlink(comimgpath, function (err) { });
    return system.getResult2({ "url": rtn.url }, null);
  }
  //获取图像尺寸
  async _getImgSize(srcImg) {
    var p = new Promise(function (resv, reject) {
      imageMagick(srcImg)
        .size(function (err, size) {
          if (!err) {
            resv(size);
          } else {
            reject(err);
          }
        });
    });
    return p;
  }
  //缩放图像
  async _grayImg(srcImg) {
    var p = new Promise(function (resv, reject) {
      imageMagick(srcImg)
        .colorspace("GRAY")
        .write(srcImg, function (err) {
          if (!err) {
            resv(srcImg);
          } else {
            reject(err);
          }
        });
    });
    return p;
  }
  //缩放图像
  async _scaleImg(srcImg, w, h) {
    var p = new Promise(function (resv, reject) {
      imageMagick(srcImg)
        .resize(w, h)
        .write(srcImg, function (err) {
          if (!err) {
            resv(srcImg);
          } else {
            reject(err);
          }
        });
    });
    return p;
  }
  //生成背景图片,bs大小
  async _onMakeTmBkPic(bs, destfile) {
    var p = new Promise(function (resv, reject) {
      imageMagick(bs, bs, "#fff")
        .write(destfile, function (err) {
          if (!err) {
            resv(destfile);
          } else {
            reject(err);
          }
        });
    });
    return p;
  }
  //合成图片
  async _composeImg(scale, maxSize, srcImg, bakImg, destfile) {
    var self = this;
    var p = new Promise(async function (resv, reject) {
      if (scale == 0) {
        imageMagick()
          .command("composite")
          .in("-gravity", "center")
          .in(srcImg)
          .in(bakImg)
          .write(destfile, function (err) {
            if (!err) {
              resv(destfile);
            } else {
              reject(err);
            }
          });
      } else {
        var srcimg = await self._scaleImg(srcImg, maxSize);
        imageMagick()
          .command("composite")
          .in("-gravity", "center")
          .in(srcimg)
          .in(bakImg)
          .write(destfile, function (err) {
            if (!err) {
              resv(destfile);
            } else {
              reject(err);
            }
          });
      }
    });
    return p;
  }

  //合成图片
  async genPosterQrcodeImg(qrcode, bakImg, fileName) {
    if (qrcode.lastIndexOf("/") != -1) {
      qrcode = qrcode.substring(qrcode.lastIndexOf("/") + 1);
    }
    if (bakImg.lastIndexOf("/") != -1) {
      bakImg = bakImg.substring(bakImg.lastIndexOf("/") + 1);
    }
    var self = this;
    var d1 = await this.ossClient.downfile(qrcode);
    var d2 = await this.ossClient.downfile(bakImg);

    if (!fileName) {
      var uuid = uuidv4();
      var u = uuid.replace(/\-/g, "");
      fileName = "zc_" + u + ".png";
    }

    var qrcodeFile = "/tmp/" + qrcode;
    var bakImgFile = "/tmp/" + bakImg;
    var destfile = "/tmp/" + fileName;

    var p = new Promise(async function (resv, reject) {
      imageMagick()
        .command("composite")
        .in("-gravity", "SouthEast")
        .in("-geometry", "+20+20")
        .in(qrcodeFile)
        .in(bakImgFile)
        .write(destfile, async function (err) {
          if (!err) {
            // var rs = await self.ossClient.upfile(fileName, destfile);
            // resv({
            //   "key": rs.name || "",
            //   "url": rs.url || ""
            // });
            resv(destfile);
          } else {
            console.error(err);
            reject(err);
          }

          // fs.unlink(qrcodeFile, function(err){});
          // fs.unlink(bakImgFile, function(err){});
          // fs.unlink(destfile, function(err){});
        });
    });
    return p;
  }

}
module.exports = ImageHandleApi;
  // var t=new ImageHandleApi();
  //
  // t.makeDeleForTM({"url":"http://192.168.18.40:3000/mobile#/products/createwts/10711536633793138"}).then(d=>{
  //   console.log(d);
  // });
// t.onLineMakeTM("hello","/tmp/a.jpg").then(f=>{
//   console.log(f);
// });
// t.adjustTMSize({
//   appKey:"wx76a324c5d201d1a4",
//   jpgpath:"zc_1158153631265738720187173057387ban4.jpg"
// }).then(d=>{
//   console.log(d);
// });
// t.toblack({
//   appKey:"wx76a324c5d201d1a4",
//   jpgpath:"zc_1158153631265738720187173057387ban4.jpg"
// }).then(d=>{
//   console.log(d);
// });
// t._scaleImg("/tmp/a.jpg",400).then(d=>{
//   console.log(d);
// });
// t._grayImg("/tmp/b.png").then(d=>{
//   console.log(d);
// });
