const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
const uuidv4 = require('uuid/v4');
var svgCaptcha = require('svg-captcha');

class CaptchaService {
  constructor() {
    this.redisClient = system.getObject("util.redisClient");
  }

  async apiGenerate(params) {
    var key = uuidv4();

    var options = {
      size: 4,
      noise: 1,
      ignoreChars: '0o1iILl'
    };
    options.width = this.trim(params.width) || 120;
    options.height = this.trim(params.height) || 32;
    options.background = this.trim(params.background) || "#E8E8E8";

    var captchaPrev = this.trim(params.captchaPrev);
    var expire = Number(params.expire || 3 * 60)
    try {
      var cap = svgCaptcha.create(options);
      console.log(cap);
      await this.redisClient.setWithEx(key, cap.text, expire);
      return system.getResultSuccess({
        key: key,
        text: cap.text,
        captcha: cap.data,
      });
    } catch (error) {
      return system.getResult(null, "接口异常：" + error.message);
    }
  }

  async apiValidator(params) {
    var key = this.trim(params.key);
    var code = this.trim(params.code);

    var cacheCode = await this.redisClient.get(key);
    if(!cacheCode) {
      return system.getResult(null, "验证码已过期，请点击重试");
    }
    if(code.toLowerCase() != cacheCode.toLowerCase()) {
      await this.redisClient.delete(key);
      return system.getResult(null, "验证码输入错误，清点击重试");
    }

    return system.getResultSuccess(1);
  }

  trim(o) {
    if(!o) {
      return "";
    }
    return o.toString().trim();
  }

}
module.exports = CaptchaService;