package com.bonus.zlpt.system.service.impl;

import com.bonus.zlpt.common.core.exception.ServiceException;
import com.bonus.zlpt.system.config.SmsComponent;
import com.bonus.zlpt.system.service.ISmsService;
import org.springframework.stereotype.Service;

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

/**
 * Description: 短信发送接口实现
 *
 * @Author 阮世耀
 * @Create 2023/12/6 15:05
 * @Version 1.0
 */
@Service
public class ISmsServiceImpl implements ISmsService {

    @Resource
    SmsComponent smsComponent;

    /**
     * @param phone     给手机号发送验证码
     * @param leastTime 短信有效时间
     * @return 消息
     * @throws ServiceException 异常信息
     */
    @Override
    public String sendCode(String phone, int leastTime) {
        if (phone == null || phone.isEmpty()) {
            throw new ServiceException("手机号为空");
        }

        // 判断是否已经发送过 (需要从Redis缓存中获取记录来进行判断，此处暂时去除)
        // if (!StringUtils.isEmpty(redisCode)) {
        //     long time = Long.parseLong(redisCode.split("_")[1]);
        //     if (System.currentTimeMillis() - time < leastTime) {
        //         throw new ServiceException("发送频率过高");
        //     }
        // }

        String code = getSixBitCode();  // 生成新的验证码
        //存储 phone -> code到Redis中
        // redisCache.setCacheObject(Constants.HEAD + phone, code + "_" + System.currentTimeMillis(), smsComponent.getTimeout(), TimeUnit.MINUTES);
        int minute = leastTime / 60 / 1000; //分钟
        smsComponent.sendCode(phone, code, Integer.toString(minute));
        return "已发送验证码 " + phone;
    }

    /**
     * 随机生成6位验证码
     */
    private String getSixBitCode() {
        //随机数
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(rand.nextInt(10));
        }
        return sb.toString();
    }


    /**
     * 判断验证码是否存在Redis中
     *
     * @param phone 手机号码
     * @param code  验证码
     * @return 校验结果
     * @throws ServiceException 异常信息
     */
    @Override
    public boolean checkCode(String phone, String code) {
        // String redisCode = redisCache.getCacheObject(Constants.HEAD + phone);
        // if (StringUtils.isEmpty(redisCode)) {
        //     throw new ServiceException("验证码失效");
        // }
        // if (!StringUtils.equals(redisCode.split("_")[0], code)) {
        //     throw new ServiceException("验证码错误");
        // } else {
        //     redisCache.deleteObject(Constants.HEAD + phone);
            return true;
        // }
    }
}
