package com.sv.service.common;

import com.sv.exception.api.ExceptionCodeTemplate;
import com.sv.service.api.config.SpringProfiles;
import com.ydd.framework.core.exception.ServiceException;
import com.ydd.framework.core.service.CacheService;
import org.springframework.stereotype.Service;

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

/**
 * Service - 验证码缓存
 *
 * @author Demon
 * @since 06/11/2017
 */
@Service
public class CaptchaCacheServiceImpl {

    @Resource
    private CacheService cacheService;

    @Resource
    private SpringProfiles springProfiles;

    /**
     * 保存验证码
     *
     * @param mobile    手机号码
     * @param captcha   验证码
     * @param expiredIn 有效期（秒）
     * @param prefix    前缀
     */
    public void setCaptcha(String mobile, String captcha, Long expiredIn, String prefix) {
        cacheService.set(prefix + mobile, captcha, expiredIn, TimeUnit.SECONDS);
    }

    /**
     * 查询验证码
     *
     * @param mobile 手机号码
     * @param prefix 浅醉
     * @return 验证码
     */
    public String getCaptcha(String mobile, String prefix) {
        Object ret = cacheService.get(prefix + mobile);

        if (ret == null) {
            return null;
        }

        return ret.toString();
    }

    /**
     * 断言验证码正确
     *
     * @param mobile  手机号码
     * @param prefix  前缀
     * @param captcha 验证码
     */
    public void assertCaptcha(String mobile, String prefix, String captcha) {
        // 校验验证码是否正确
        if (springProfiles.isProduction() && !captcha.equals(getCaptcha(mobile, prefix))) {
            throw new ServiceException(ExceptionCodeTemplate.INCORRECT_CAPTCHA);
        }
    }

    /**
     * 删除验证码
     *
     * @param mobile 手机号码
     * @param prefix 验证码
     */
    public void remove(String mobile, String prefix) {
        cacheService.remove(prefix + mobile);
    }
}
