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

import cn.com.poc.common.constant.RedisKeyConstant;
import cn.com.poc.common.service.JudgeCodeService;
import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.utils.UUIDTool;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.regex.Pattern;

@Component
public class JudgeCodeServiceImpl implements JudgeCodeService {
    @Resource
    private RedisService redisService;
    @Override
    public boolean judgeCode(String account, String code) throws Exception {
        //验证次数
        String accountKey = "JUDGE_CODE_COUNT:" + account;
        //校验校验验证码：从redis获取发送的验证码
        String mobileCode = (String) redisService.get(account);
        if (StringUtils.isEmpty(mobileCode)) {
            throw new I18nMessageException("exception/verification.code.has.expired.please.obtain.it.again");
        }

        // 防止撞库攻击
        if (!redisService.hasKey(accountKey)) {
            redisService.set(accountKey, 1, 60);
        }
        //如果没有验证过
        int verifyCount = Integer.parseInt(String.valueOf(redisService.get(accountKey)));
        if (verifyCount > 5) {
            throw new I18nMessageException("exception/maximum.number.of.verifications.has.been.reached");
        }
        //验证次数自增
        verifyCount++;
        redisService.set(accountKey, verifyCount, redisService.getExpire(accountKey));
        //验证逻辑
        boolean isValid = mobileCode.equals(code);
        //如果成功,删除验证码和验证码次数
        if (isValid) {
            redisService.del(account);
            redisService.del(accountKey);
            return true;
        }
        return false;
    }

    @Override
    public String judgeCodeReturnAuthCode(String account, String code) throws Exception {
        //验证验证码是否正确
        if (!judgeCode(account, code)) {
            return StringUtils.EMPTY;
        }
        //验证次数
        String authCode = UUIDTool.getUUID();

        //校验手机号格式
        boolean matches = Pattern.matches(
                "(?:0|86|\\+86)?1[3-9]\\d{9}|" +
                        "(?:0|852|\\+852)?\\d{8}|" +
                        "(?:0|886|\\+886)?(?:|-)09\\d{8}|" +
                        "(?:0|853|\\+853)?(?:|-)6\\d{7}", account);

        if(matches){    //是手机号
            redisService.set(RedisKeyConstant.Code.AUTH_CODE + account, authCode, 60 * 5);
        }else{
            redisService.set(RedisKeyConstant.Code.AUTH_CODE + account, authCode, 60 * 15);
        }
        return authCode;
    }
}
