import { Config, Init, Provide } from '@midwayjs/core';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import Util, * as $Util from '@alicloud/tea-util';
@Provide()
export class AliyunSmsService {
  @Config('aliyunSms')
  aliyunSms;
  @Config('showDBSub')
  showDBSub: any;

  client: Dysmsapi20170525;
  @Init()
  init() {
    const config = new $OpenApi.Config({
      accessKeyId: this.aliyunSms.AccessKey_ID,
      accessKeySecret: this.aliyunSms.AccessKey_Secret,
    });
    config.endpoint = `dysmsapi.aliyuncs.com`;
    this.client = new Dysmsapi20170525(config);
  }
  async send(phone, code) {
    const smsRequest = new $Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: phone,
      signName: this.aliyunSms.sign,
      templateCode: this.aliyunSms.template,
      templateParam: JSON.stringify({ code }),
    });
    try {
      const res = await this.client.sendSms(smsRequest);
      if(this.showDBSub) console.log(res)
    } catch (error) {
      console.log(error);
    }
  }
}
