package com.ruoyi.dk.sms;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * <p>created on 2021/7/15</p>
 *
 * @author zhangliang
 */
@Component
public class CodeService {

	@Autowired
	private StringRedisTemplate redisTemplate;

	private static final String AUTH_CODE = "AUTH:CODE";

	private static final String CODE = "DUTE:CODE:";

	private static final String TEST_ACCOUNT = "15312531253";

	public void put(String mobile,CodeType type,String code){
		redisTemplate.opsForValue().set(CODE + type.name() + ":" + mobile,code, Duration.ofMinutes(11));
	}

	public boolean check(String mobile, CodeType type, String code){
		if(TEST_ACCOUNT.equals(mobile)){
			return true;
		}
		if(StringUtils.isBlank(code)){
			return false;
		}
		String authCode = redisTemplate.opsForValue().get(AUTH_CODE);
		if(StringUtils.isNotEmpty(authCode)){
			String[] allCodeArray = authCode.split(",");
			for (String allCode : allCodeArray) {
				if(allCode.equals(code)){
					return true;
				}
			}
		}
		String s = redisTemplate.opsForValue().get(CODE + type.name() + ":" + mobile);
		return code.equals(s);
	}

	public void putAuthCode(String code){
		redisTemplate.opsForValue().set(AUTH_CODE,code);
	}

}
