package edu.whut.smilepicturebackend.service.impl;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import edu.whut.smilepicturebackend.constant.CacheConstant;
import edu.whut.smilepicturebackend.model.vo.CaptchaVO;
import edu.whut.smilepicturebackend.service.MainApplicationService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 公共应用服务实现
 */
@Service
@RequiredArgsConstructor
public class MainApplicationServiceImpl implements MainApplicationService {

	private final StringRedisTemplate redisCache;

	/**
	 * 获取图形验证码
	 *
	 * @return 图形验证码VO
	 */
	@Override
	public CaptchaVO getCaptcha() {
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
		specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
		String captchaCode = specCaptcha.text().toLowerCase();
		String captchaImage = specCaptcha.toBase64();
		String captchaKey = UUID.randomUUID().toString();
		// 把验证码存入 Redis 并且设置 1 分钟过期
		redisCache.opsForValue().set(String.format(CacheConstant.CAPTCHA_CODE_KEY, captchaKey), captchaCode, 1, TimeUnit.MINUTES);
		CaptchaVO captchaVO = new CaptchaVO();
		captchaVO.setCaptchaKey(captchaKey);
		captchaVO.setCaptchaImage(captchaImage);
		return captchaVO;
	}
}
