package com.emergency.avenue.admin.controller;

import com.emergency.avenue.common.core.constant.CommonConstants;
import com.emergency.avenue.common.core.constant.SecurityConstants;
import com.emergency.avenue.common.security.annotation.Inner;
import com.google.code.kaptcha.Producer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Controller to authenticate users.
 */
@RestController
@RequestMapping("/api")
@Tag(description = "api", name = "api接口，验证码")
public class UserJWTController {

	@Autowired
	private Producer producer;
	@Autowired
	private RedisTemplate redisTemplate;
	private static final String JPEG = "jpeg";

	@GetMapping(value = "/code")
	@Inner(value = false)
	@Operation(description = "验证码", summary = "验证码")
	public void getCode(HttpServletRequest httpServletRequest,
						HttpServletResponse httpServletResponse) throws IOException {
		//生成验证码
		String text = createStr();
		BufferedImage image = producer.createImage(text);
		//保存验证码信息
		String randomStr = (String) httpServletRequest.getParameter("randomStr");
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.opsForValue().set(CommonConstants.DEFAULT_CODE_KEY + randomStr, text
				, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
		// 转换流信息写出
		httpServletResponse.setContentType("image/jpeg");
		httpServletResponse.setDateHeader("expries", -1);
		httpServletResponse.setHeader("Cache-Control", "no-cache");
		httpServletResponse.setHeader("Pragma", "no-cache");
		ServletOutputStream outputStream = httpServletResponse.getOutputStream();
		try {
			ImageIO.write(image, JPEG, outputStream);
		} catch (IOException e) {

		}
	}


	/**
	 * 验证码替换为纯数字
	 *
	 * @return String
	 */
	private String createStr() {
		String str = "0123456789";
		StringBuilder sb = new StringBuilder(4);
		for (int i = 0; i < 4; i++) {
			char ch = str.charAt(new Random().nextInt(str.length()));
			sb.append(ch);
		}
		return sb.toString();
	}
}
