package com.pj.retry;

import com.pj.aliyun.sms.AliyunInformSmsService;
import com.pj.aliyun.sms.AliyunSmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


/**
 * @Author Mechrevo
 * @Date 2023 07 31 14 43
 **/
@Service
@Slf4j
public class SmsRetryService {


    /**
     * 验证码短信
     * @param phone 手机号
     * @param code  验证码
     * @return
     * @throws Exception
     */
    @Async
    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public boolean sendSmsCode(String phone,String code) throws Exception {
        //模拟发送失败
        //todo: 发送短信业务逻辑
        boolean result = AliyunSmsService.sendSms("18934859524",code);
        if(!result) throw new Exception("模拟短信发送失败!");
        return true;
    }

    /**
     * 通知短信
     * @param phone 手机号
     * @return
     * @throws Exception
     */
    @Async
    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public boolean sendSmsMsg(String phone) throws Exception {
        System.out.println("\n发送通知短信!\n");
        //todo: 发送短信业务逻辑
        boolean result = AliyunInformSmsService.sendSMS("18934859524");
        if(!result) throw new Exception("模拟短信发送失败!");
        return true;
    }

    /**
     * 注册短信
     * @param phone 手机号
     * @return
     * @throws Exception
     */
    @Async
    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public boolean sendSmsRegisteMsg(String phone,String content) throws Exception {
        System.out.println("\n发送注册成功短信!\n");
        //todo: 发送短信业务逻辑
        boolean result = AliyunInformSmsService.sendRegisteSMS("18934859524",content);
        if(!result) throw new Exception("模拟短信发送失败!");
        return true;
    }


    //最终补偿机制
    @Recover
    public void recover(){
        log.error("发送短信失败!");
    }

}
