'use strict';

const qs = require('querystring');
const Service = require('egg').Service;

class OCRService extends Service {
  async getAccessToken() {
    const param = qs.stringify({
      grant_type: 'client_credentials',
      client_id: 'S20Ves9LBcNMUuGwhcboufcH',
      client_secret: 'oHL4QWx0GG8aGGPBasOCIma39s7jry5W',
    });
    const result = await this.ctx.curl(`https://aip.baidubce.com/oauth/2.0/token?${param}`, { dataType: 'json' });
    if (!(result.data && result.data.access_token)) throw new Error(result.data && result.data.error_msg || '百度ocr验证码获取token失败');
    return result.data.access_token;
  }

  async getCode(base64Img) {
    const param = {
      image: encodeURI(base64Img),
      language_type: 'ENG',
    };
    const access_token = await this.getAccessToken();
    const result = await this.ctx.curl(`https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=${access_token}`, {
      method: 'POST',
      data: param,
      dataType: 'json',
    });
    this.ctx.logger.warn(`tecent mail: 百度ocr返回结果 - ${JSON.stringify(result.data)}`);
    if (result.data && result.data.words_result && result.data.words_result.length === 0) return '';
    if (!(result.data && result.data.words_result && result.data.words_result.length && result.data.words_result[0].words)) throw new Error(result.data && result.data.error_msg || '百度ocr验证码识别失败');
    return result.data.words_result[0].words.replace(/\s/ig, '');
  }
}

module.exports = OCRService;
