const system = require("../system");
const qr = require("qr-image");
var settings = require("../../config/settings");
var ossClient = require("./ossClient");
const fs = require("fs");
class QrClient{
  constructor(){
    this.redisClient = system.getObject("util.redisClient");
  }

  /**
   * fn:生成二维码
   * @return http连接  上传失败后返回null
   * @param key
   * @returns {Promise<void>}
   */
  async generateQR(text, prev = "qc"){
    try {
      if(!text){
        return null;
      }
      let key = prev + await this.redisClient.genrateId("qrcode") + ".png";
      let filePath = settings.localPath();
      var qr_png = qr.image(text, {size :10 });
      let _r = await qr_png.pipe(require('fs').createWriteStream(`${filePath}${key}`));
      console.log(_r);
      if(!_r){
        return null;
      }
      let urlRes = await new ossClient().upfile(key,`${filePath}${key}`);
      fs.unlink(`${filePath}${key}`, (err) => {
        if (err){
          console.log(`二维码删除失败`);
        }
        console.log('已成功地删除文件');
      });
      return urlRes.url;
    }catch (e) {
      console.log(e);
      return null;
    }
  }
}
module.exports=QrClient;