package com.railway.web.controller.common;

import com.google.code.kaptcha.Producer;
import com.railway.common.constant.Constants;
import com.railway.common.core.controller.BaseController;
import com.railway.common.core.domain.AjaxResult;
import com.railway.common.core.redis.RedisCache;
import com.railway.common.utils.sign.Base64;
import com.railway.common.utils.uuid.IdUtils;
import com.railway.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 图片验证码（支持算术形式）
 *
 * @author railway
 */
@Api(tags = "权限认证 - 验证码")
@RestController
public class CaptchaController extends BaseController {

  @Resource(name = "captchaProducer")
  private Producer captchaProducer;

  @Resource(name = "captchaProducerMath")
  private Producer captchaProducerMath;

  /** 验证码类型 */
  @Value("${railway.captchaType}")
  private String captchaType;

  private final RedisCache redisCache;
  private final ISysConfigService configService;

  public CaptchaController(RedisCache redisCache,
      ISysConfigService configService) {
    this.redisCache = redisCache;
    this.configService = configService;
  }

  /**
   * 生成验证码
   */
  @ApiOperation(value = "验证码生成", notes = "验证码生成", response = ModelAndView.class)
  @ApiImplicitParam(name = "type", value = "math 或 char", paramType = "query", dataType = "string")
  @GetMapping("/captchaImage")
  public AjaxResult getCode(String type) {
    AjaxResult ajax = AjaxResult.success();
    boolean captchaOnOff = configService.selectCaptchaOnOff();
    ajax.put("captchaOnOff", captchaOnOff);
    if (!captchaOnOff) {
      return ajax;
    }

    // 保存验证码信息
    String uuid = IdUtils.simpleUUID();
    String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
    String capStr, code = null;
    BufferedImage image = null;

    if(null == type){
      type = this.captchaType;
    }

    // 生成验证码
    if ("math".equals(type)) {
      String capText = captchaProducerMath.createText();
      capStr = capText.substring(0, capText.lastIndexOf("@"));
      code = capText.substring(capText.lastIndexOf("@") + 1);
      image = captchaProducerMath.createImage(capStr);
    } else if ("char".equals(captchaType)) {
      capStr = code = captchaProducer.createText();
      image = captchaProducer.createImage(capStr);
    }

    redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
    // 转换流信息写出
    FastByteArrayOutputStream os = new FastByteArrayOutputStream();
    try {
      assert image != null;
      ImageIO.write(image, "jpg", os);
    } catch (IOException e) {
      return AjaxResult.error(e.getMessage());
    }

    ajax.put("uuid", uuid);
    ajax.put("img", Base64.encode(os.toByteArray()));
    return ajax;
  }
}