package com.css.txw.sso.service.verify;

import cn.hutool.core.util.IdUtil;
import com.css.ggzc.framework.common.pojo.CommonResult;
import com.css.txw.sso.properties.SsoProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
public class VerifyServiceImpl implements VerifyService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SsoProperties ssoProperties;

    @Override
    public CommonResult<String> getVerifyToken(String remoteId) {
        //TODO: 根据ip限制访问次数
        final String verifyToken = IdUtil.fastSimpleUUID();
        stringRedisTemplate.opsForValue().set(formatKey(verifyToken), "1", 1, TimeUnit.MINUTES);
        return CommonResult.success(verifyToken);
    }

    @Override
    public Boolean checkVerifyToken(String verifyToken) {
        if (!this.ssoProperties.isLoginCaptcha()) {
            return true;
        }
        return stringRedisTemplate.hasKey(formatKey(verifyToken));
    }

    private static String formatKey(String verifyToken) {
        String VERIFY_TOKEN = "verify_token:%s";
        return String.format(VERIFY_TOKEN, verifyToken);
    }
}
