package org.jeecg.modules.shop.captcha.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class SmsUtil {

    private final Client smsClient;
    
    public void sendSmsCaptcha(String phoneNumber, String captcha) {
        Assert.isTrue(StrUtil.isAllNotEmpty(phoneNumber, captcha) && PhoneUtil.isMobile(phoneNumber) && StrUtil.isNumeric(captcha), "参数错误");
        SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName("杭州柏杰科技")
                .setTemplateCode("SMS_468890012")
                .setTemplateParam(String.format("{\"code\":\"%s\"}", captcha));
        try {
            log.info("发送短信验证码，手机号={}", phoneNumber);
            SendSmsResponse res = smsClient.sendSmsWithOptions(request, new RuntimeOptions());
            Assert.isTrue("OK".equals(res.body.code), res.body.message);
            log.info("短信验证码发送成功");
        } catch (Exception e) {
            log.error("短信验证码发送失败，手机号={}，验证码={}，错误信息={}", phoneNumber, captcha, e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    public void sendSmsNotified(String phoneNumber, String name) {
        Assert.isTrue(StrUtil.isAllNotEmpty(phoneNumber, name) && PhoneUtil.isMobile(phoneNumber), "参数错误");
        SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName("杭州柏杰科技")
                .setTemplateCode("SMS_483425393")
                .setTemplateParam(String.format("{\"name\":\"%s\"}", name));
        try {
            log.info("发送短信验证码，手机号={}", phoneNumber);
            SendSmsResponse res = smsClient.sendSmsWithOptions(request, new RuntimeOptions());
            Assert.isTrue("OK".equals(res.body.code), res.body.message);
            log.info("短信验证码发送成功");
        } catch (Exception e) {
            log.error("短信验证码发送失败，手机号={}，供应商名称={}，错误信息={}", phoneNumber, name, e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
