package com.vctgo.gateway.handler;

import com.vctgo.common.core.constant.Constants;
import com.vctgo.common.core.utils.uuid.IdUtils;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.gateway.config.properties.CaptchaProperties;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 */
@RestController
public class CaptchaHandler {

    @Autowired
    private RedisService redisService;

    @Autowired
    private CaptchaProperties captchaProperties;

    /**
     * 生成验证码
     */
    @CrossOrigin
    @GetMapping({"/captchaImage"})
    @ApiOperation(value = "生成验证码", notes = "生成验证码")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {

        AjaxResult ajax = AjaxResult.success();
//        boolean captchaOnOff = configService.selectCaptchaEnabled();
//        ajax.put("captchaOnOff", captchaOnOff);
        boolean captchaOnOff = captchaProperties.getEnabled();
        ajax.put("captchaOnOff", captchaOnOff);
        if (!captchaOnOff)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = "captcha_codes:" + uuid;
        //以下是自己新加的代码——————————————————————————————————————————————————————————
        //验证码EasyCaptcha工具
        Captcha captcha = null;
        String captchaType = captchaProperties.getType();
        if ("math".equals(captchaType)) {//math 算术验证
            //创建算术验证码
            captcha = new ArithmeticCaptcha(115, 42);
        } else if ("chinese".equals(captchaType)) {//chinese 中文验证
            //中文验证
            captcha = new ChineseCaptcha(115, 42);
        } else if ("char".equals(captchaType)) {//char 字符验证
            //创建字符验证码
            captcha = new SpecCaptcha(115,42);
        }
        //得到验证码的值
        String code = captcha.text();
        //存入redis
        redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        ajax.put("uuid", uuid);
        ajax.put("img", captcha.toBase64());  //获得图片的base64编码
        return ajax;
    }
}
