package com.sdtool.common.tool;

import com.sdtool.common.base.BaseService;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.sweetfish.util.AnyValue;

import javax.annotation.Resource;

/**
 * Created by jlutt on 2018-05-28.
 * 阿里云短信
 *
 * @author jlutt
 */
public class AliSmsService extends BaseService {

    @Resource(name = "property.ali.dysms.accessKeyId")
    String smsAccessKeyId;

    @Resource(name = "property.ali.dysms.accessKeySecret")
    String smsAccessKeySecret;

    @Resource(name = "property.ali.dysms.signName")
    String smsSignName;

    @Resource(name = "property.ali.dysms.registerTemplateCode")
    String smsRegisterTemplateCode;

    private Client smsClient;


    @Override
    public void init(AnyValue config) {
        com.aliyun.teaopenapi.models.Config smsConfig = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(smsAccessKeyId)
                .setAccessKeySecret(smsAccessKeySecret);
        // 访问的域名
        smsConfig.endpoint = "dysmsapi.aliyuncs.com";
        try {
            smsClient = new Client(smsConfig);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 发送注册短信
     *
     * @param to   电话号码
     * @param code 发送内容
     * @return 发送
     */
    public boolean sendRegisterSMS(String to,
                                   String code) {
        SendSmsRequest smsRequest = new SendSmsRequest()
                .setPhoneNumbers(to)
                .setSignName(smsSignName)
                .setTemplateCode(smsRegisterTemplateCode)
                .setTemplateParam("{code: " + code + "}");

        try {
            SendSmsResponse smsResponse = smsClient.sendSms(smsRequest);
            logger.info(smsResponse);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
    }

}
