package com.sqx.common.sms;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.sqx.common.utils.Constant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 短信发送工具
 */
@Slf4j
@RequiredArgsConstructor
public class SmsSendUtil {

    private final SmsConfig smsConfig;
    /**
     * 最终发送内容模板，格式： 【短信签名】短信内容
     */
    private final String contentTemplate = "【%s】%s";

    /**
     * 使用腾讯sms发送短信
     * @param phone 手机号码
     * @param content 短信内容，内容需要和腾讯云sms控制台已创建的模板格式保持一致
     * @return
     */
    public SmsSendResult sendByTencent(String phone, String content) {
        SmsSingleSender smsSingleSender = new SmsSingleSender(Integer.parseInt(smsConfig.getClientId()), smsConfig.getClientSecret());

        String code;
        String msg;
        try {
            SmsSingleSenderResult result = smsSingleSender.send(0, "86", phone, String.format(contentTemplate, smsConfig.getSmsSign(), content), "", "");
            if (result.result == 0) {
                code = Constant.YES;
                log.info("腾讯短信发送成功，发送参数：phone【{}】, content【{}】", phone, content);
            } else {
                code = Constant.NO;
                log.error("腾讯短信发送失败，发送参数：phone【{}】, content【{}】，错误信息【{}】", phone, content, result.errMsg);
            }
            msg = result.errMsg;
        } catch (Exception e) {
            code = Constant.NO;
            msg = e.getMessage();
            log.error("腾讯短信发送失败，发送参数：phone【{}】, content【{}】，错误信息【{}】", phone, content, e.getMessage());
        }

        return SmsSendResult.builder()
                .code(code)
                .msg(msg)
                .content(content)
                .sendTo(phone)
                .build();
    }
}
