package com.template.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.template.mapper.SysCaptchaMapper;
import com.template.model.pojo.SysCaptcha;
import com.template.services.SysCaptchaService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ceshi
 * @since 2024-10-25
 */
@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaMapper, SysCaptcha> implements SysCaptchaService {
    @Autowired
    private Producer producer;
    @Autowired
    private SysCaptchaMapper sysCaptchaMapper;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (!StringUtils.hasText(uuid)) {
            return null;
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);

        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addMinutes(new Date(), 5));
        int insertCaptcha = sysCaptchaMapper.insert(captchaEntity);
        if (insertCaptcha <= 0) {
            return null;
        }

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        QueryWrapper<SysCaptcha> scm = new QueryWrapper<>();
        scm.eq("uuid", uuid);
        scm.eq("code", code);
        scm.ge("expire_time", new Date());

        SysCaptcha SC = sysCaptchaMapper.selectOne(scm);
        if(SC != null){
            sysCaptchaMapper.deleteById(SC.getId());
        }


        return SC == null ? false : true;
    }
}
