package com.huiju.estateagents.common.smsService;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Service implements InitializingBean {

    @Value("${sms-service.accessKeyId}")
    String accessKeyId;

    @Value("${sms-service.accessKeySecret}")
    String accessKeySecret;

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    //API 的名称,开发者无需替换
    static final String action = "SendSms";
    //API RegionId,开发者无需替换
    static final String regionId = "cn-hangzhou";
    //API 版本,开发者无需替换
    static final String verison = "2017-05-25";

    IAcsClient acsClient;

    public void sendMessage(Message message) throws Exception {
        request(message);
    }

    private CommonResponse request(Message message) throws Exception {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(domain);
        request.setSysVersion(verison);
        request.setSysAction(action);
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", message.getTel());
        request.putQueryParameter("SignName", message.getSign());
        request.putQueryParameter("TemplateCode", message.getCode());
        request.putQueryParameter("TemplateParam", message.getContent());

        return acsClient.getCommonResponse(request);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        acsClient = new DefaultAcsClient(profile);
    }

    @Data
    @Accessors(chain = true)
    public static class Message {
        String code;
        String tel;
        String sign;
        String content;
    }
}
