package com.ym.mec.common.validcode.impl;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.ym.mec.common.redis.service.RedisCache;
import com.ym.mec.common.validcode.SmsCodeService;

@Service
public class SmsCodeServiceImpl implements SmsCodeService {

	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	
	private RedisCache<String,String> redisCache = new RedisCache<String, String>(redisTemplate);
	
	private final String loginVerifyCodeKey = "loginVerifyCode:";
	
	private int expireTime = 60;

	@Override
	public boolean verifyValidCode(String mobile, String authCode) {
		String verifyCode = redisTemplate.opsForValue().get(loginVerifyCodeKey + mobile);
		if(StringUtils.isNoneEmpty(verifyCode) && StringUtils.equalsIgnoreCase(verifyCode,authCode)){
			return true;
		}
		return true;
	}

	@Override
	public boolean sendValidCode(String mobile) {
		String code = RandomStringUtils.randomNumeric(6);
		// 发送验证码
		redisTemplate.opsForValue().set(loginVerifyCodeKey + mobile, code, expireTime);
		return true;
	}

	@Override
	public String getValidCode(String mobile) {
		return redisTemplate.opsForValue().get(loginVerifyCodeKey + mobile);
	}

	@Override
	public void removeValidCode(String mobile) {
		if (redisTemplate.hasKey(loginVerifyCodeKey + mobile)) {
			redisTemplate.delete(loginVerifyCodeKey + mobile);
		}
	}

}
