package com.zd.common.core.utils;

import cn.hutool.json.JSONUtil;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.sms.SmsClient;
import com.baidubce.services.sms.SmsClientConfiguration;
import com.baidubce.services.sms.model.SendMessageV3Request;
import com.baidubce.services.sms.model.SendMessageV3Response;
import com.zd.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

public class SMSUtil {
    private static Logger logger= LoggerFactory.getLogger(SMSUtil.class);

//    @Value("${sms.accessKey}")
    private static final String ACCESS_KEY_ID = "4f4ae0dfc10942359d5a53863b84354f";
//    @Value("${sms.secretKey}")
    private static final String SECRET_ACCESS_KEY = "d479a91c8e41427697fb40ae65884f09";
//    @Value("${sms.signatureId}")
    private static final String SIGNATUREID = "sms-sign-JWgtkc22975";
//    @Value("${sms.templateId}")
    private static final String TEMPLATEID = "sms-tmpl-dSpFwA53769";

    private static final String ENDPOINT = "http://smsv3.bj.baidubce.com";


    /**
     * 预警发送 短信推送
     * @param phone 手机号 多个以逗号分隔
     * @param content 发送内容
     * @return 200 成功
     */
    public static AjaxResult sendSMS(@NotNull String phone, @NotNull String content){

        try {
            SmsClientConfiguration config = new SmsClientConfiguration();
            config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
            config.setEndpoint(ENDPOINT);
            SmsClient client = new SmsClient(config);
            SendMessageV3Request request = new SendMessageV3Request();
            // 手机号码,支持单个或多个手机号，多个手机号之间以英文逗号分隔，一次请求最多支持200个手机号
            request.setMobile(phone);
            // 短信签名ID
            request.setSignatureId(SIGNATUREID);
            // 短信模板ID
            request.setTemplate(TEMPLATEID);
            Map<String, String> contentVar = new HashMap<>();
            contentVar.put("content", content);
            // 模板变量内容，用于替换短信模板中定义的变量，为json字符串格式
            request.setContentVar(contentVar);

            // custom 用户自定义参数，格式为字符串，状态回调时会回传该值
            logger.info("发送短信消息：" +JSONUtil.toJsonStr(request));

            SendMessageV3Response response = client.sendMessage(request);
            logger.info("短信发送结果：" + JSONUtil.toJsonStr(response));

            // 解析请求响应 response.isSuccess()为true 表示成功
            if (response != null && response.isSuccess()) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error(response.getMessage());
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
