package cn.com.poc.common.service.impl;

import cn.com.poc.common.dto.SmsDto;
import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.service.SmsService;
import cn.com.poc.support.sms.channel.baidu.BaiDuThirdPlatformService;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

@Service
public class SmsServiceImpl implements SmsService {


    @Resource
    private BaiDuThirdPlatformService baiDuThirdPlatformService;

    @Resource
    private RedisService redisService;

    @Override
    public void smsDelivered(String phone) throws Exception {
        SmsDto smsDto = new SmsDto();
        Random random = new Random();
        // 随机生成六位数的随机数字
        int randomNum = 100000 + random.nextInt(900000); // 生成[10000, 99999]范围内的随机数
        String code = Integer.toString(randomNum);
        smsDto.setMobilePhone(phone);
        smsDto.setSmsCode(code);
        boolean isSend = baiDuThirdPlatformService.doSend(smsDto);
        if (isSend) {
            // 如果成功发送，则把验证码存入redis当中，并设置五分钟的过期时间
            redisService.set(phone, code, 300);
        } else {
            throw new I18nMessageException("exception/verification.code.sending.failed.please.try.again");
        }
    }

}
