package cn.wisenergy.common.utils;

import cn.wisenergy.web.config.SmsConfig;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 短信发送工具类
 */
@Slf4j
@Component
public class SmsUtils {

    @Autowired
    private SmsConfig smsConfig;

    /***
     * 发送短信的方法
     * @param
     * @return
     */
    public boolean sendMessage(String phone, String templateCode, String code) {
        //构造一个acs的clinet
        DefaultProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(), smsConfig.getAccessKeyId(), smsConfig.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        //构造请求的request
        CommonRequest request = new CommonRequest();
        //设置了一堆参数
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsConfig.getDomain());
        request.setSysVersion(smsConfig.getVersion());
        request.setSysAction(smsConfig.getAction());
        request.putQueryParameter("RegionId", smsConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", smsConfig.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(StringUtil.createSimpleMap("code", code)));
        try {
            //发送请求，接收响应
            CommonResponse response = client.getCommonResponse(request);
            log.debug(response.getData());
            String status = (String) JSONObject.parseObject(response.getData()).get("Code");
            return "OK".equals(status);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}

