package com.softwarebr.nunu.service.sms.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.brframework.commonweb.exception.HandleException;
import com.softwarebr.nunu.domain.SMSConfig;
import com.softwarebr.nunu.service.sms.AbstractCaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 阿里验证码
 * @author xu
 * @date 2020/1/8 23:33
 */
@Service
@Slf4j
public class AliCaptchaServiceImpl extends AbstractCaptchaService {
    @Override
    protected void sendCaptchaRequest(String phone, String business, String captcha, SMSConfig config) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", config.getAliAk(), config.getAliSk());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", config.getAliSign());
        request.putQueryParameter("TemplateCode", business);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + captcha + "\"}");

        try {
            client.getCommonResponse(request);
        } catch (ClientException e) {
            log.error("短信发送失败" + e.getMessage(), e);
            throw new HandleException("短信发送失败：" + e.getMessage());
        }
    }
}
