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

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