import { TURBO_CORE_URL, APP_ID, TURBO_PARM_SECRET } from '@consts';
import { Service } from 'egg';
const crypto = require('crypto');
/**
 * Test Service
 */
export default class TurboCore extends Service {

  /**
   * 用户获取手机验证码
   * @param telNo - 用户手机号
   */

  public async getSms(telNo: string) {
    const ctx = this.ctx;
    const body = {
      telNo,
    };
    const result = await ctx.curl(`${TURBO_CORE_URL}/user/getSms`, {
      method: 'POST',
      contentType: 'json',
      headers: {
        AppId: APP_ID,
        sign: this.getTurboSign(body, TURBO_PARM_SECRET),
      },
      data: body,
      dataType: 'json',
    });
    return result.data;
  }

  /**
   * 用户获取到手机验证码之后发送验证登录请求
   * @param telNo 登录手机号
   * @param code 登录验证码
   */
  public async smsLogin(telNo: string, code: string) {
    const ctx = this.ctx;
    const body = {
      telNo, code,
    };
    const result = await ctx.curl(`${TURBO_CORE_URL}/user/getSms`, {
      method: 'POST',
      contentType: 'json',
      headers: {
        AppId: APP_ID,
        sign: this.getTurboSign(body, TURBO_PARM_SECRET),
      },
      data: body,
      dataType: 'json',
    });
    return result.data;
  }

  /**
   * 获取多宝规则下的参数签名
   * @param params 参数列表
   * @param secret 密钥
   */
  private getTurboSign(params, secret) {
    const paramsString = this.joinParamsStr(params);
    let stringToSign = paramsString;

    if (secret) {
      stringToSign = `${stringToSign}&secret=${secret}`;
      return crypto.createHmac('sha256', secret)
        .update(stringToSign)
        .digest('hex');
    }
    return null;
  }

  /**
   * 将参数组合成字符串
   * @param params 参数列表
   */
  private joinParamsStr(params) {
    const signString = Object.keys(params).filter(function(key) {
      return params[key] !== undefined && params[key] !== '' && [ 'pfx', 'partner_key', 'sign', 'key' ].indexOf(key) < 0;
    }).sort()
      .map(function(key) {
        return key + '=' + params[key];
      })
      .join('&');
    return signString;
  }
}
