package com.ytpm.auth.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IOUtils;
import com.ytpm.auth.CaptchaService;
import com.ytpm.general.RepMessage;
import com.ytpm.handle.CustomerException;
import com.ytpm.oauth.model.CaptchaValid;
import com.ytpm.util.CacheUtil;
import com.ytpm.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j(topic = "captcha")
@Service
public class CaptchaServiceImpl implements CaptchaService {


    // 图片宽
    private final int width = 200;
    // 图片高
    private final int height = 100;
    // 字符个数
    private final int codeCount = 4;
    // 干扰圆圈条数
    private final int circleCount = 20;
    // 生成验证码长度
    private final int length = 4;
    // 过期时间
    private final int ttl = 5 * 60;

    @Resource
    private RedisService redisService;

    @Override
    public void create(HttpServletResponse response, String uuid) throws IOException {

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        if(StrUtil.isBlank(uuid)){
            throw new CustomerException(RepMessage.UUID_EMPTY+uuid);
        }
        //获取图片验证码输出到流中
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, circleCount);
        captcha.setGenerator(new RandomGenerator("0123456789",length));
        //设置验证码到缓存中，5分钟过期

        CacheUtil.put("sms_captcha_" + uuid, captcha.getCode(), ttl);
        ServletOutputStream out = response.getOutputStream();
        captcha.write(out);
        IOUtils.closeQuietly(out);
    }

    @Override
    public void valid(CaptchaValid captchaValid) {

        log.info("验证码校验");

        //判断是否需要输入验证码,密码错误次数大于配置错误次数
        if (captchaValid.getShowCaptcha() || captchaValid.getErrorCount() > captchaValid.getSettingErrorCountCaptcha()) {
            if (StrUtil.isBlank(captchaValid.getCaptcha())) {
                throw new RuntimeException("验证码不能为空");
            }
            if (StrUtil.isBlank(captchaValid.getUuid())) {
                throw new RuntimeException("验证码已过期，请刷新后重试");
            }
            String vailCode = (String) CacheUtil.get("sms_captcha_" + captchaValid.getUuid());
            if (vailCode == null) {
                throw new RuntimeException("验证码已过期，请刷新后重试");
            }
            if (!captchaValid.getCaptcha().equals(vailCode)) {
                throw new RuntimeException("验证码错误");
            }
        }
    }
}
