package com.zanxiang.game.module.manage.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.zanxiang.game.module.manage.constant.RedisKeyConstant;
import com.zanxiang.game.module.manage.enums.ExpireTimeEnum;
import com.zanxiang.game.module.manage.service.ISmsService;
import com.zanxiang.game.module.manage.utils.RedisUtil;
import com.zanxiang.module.sms.pojo.SendResult;
import com.zanxiang.module.sms.service.impl.AliSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author : lingfeng
 * @time : 2024-11-04
 * @description : 短信验证码
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    @Autowired
    private RedisUtil<String> redisUtil;

    @Autowired
    private AliSmsService aliSmsService;

    @Override
    public boolean randomCodeSend(String phoneNumber) {
        //判断是否已经发送
        String smsKey = RedisKeyConstant.SMS_PHONE_KEY + "_" + phoneNumber;
        Assert.state(Strings.isBlank(redisUtil.getCache(smsKey)), "验证码已发送请稍后再试");
        //发送验证码
        String randomCode = RandomUtil.randomNumbers(4);
        //发送短信验证码
        this.smsSendApi(randomCode, phoneNumber);
        //发送成功设置缓存, 时效5分钟
        return redisUtil.setCache(smsKey, randomCode, ExpireTimeEnum.FIVE_MIN.getTime());
    }

    @Override
    public boolean randomCodeCheck(String phoneNumber, String randomCode) {
        String smsKey = RedisKeyConstant.SMS_PHONE_KEY + "_" + phoneNumber;
        //获取缓存中的验证码
        String cache = redisUtil.getCache(smsKey);
        //验证码已过期
        Assert.state(Strings.isNotBlank(cache), "验证码已过期");
        //验证码错误
        Assert.state(Objects.equals(cache, randomCode), "验证码错误");
        //验证成功, 删除缓存
        return redisUtil.deleteCache(smsKey);
    }

    private void smsSendApi(String content, String phoneNumber) {
        //验证手机号
        Assert.state(Pattern.matches("^1[3-9]\\d{9}$", phoneNumber), "手机号格式错误");
        //发送短信
        SendResult sendResult = aliSmsService.sendCode(content, phoneNumber);
        //发送结果判断
        Assert.state(sendResult.isSuccess(), "验证码发送失败");
    }
}
