package com.tuoheng.controller;

import com.tuoheng.until.JsonResult;
import com.tuoheng.until.VerifyCode;
import com.tuoheng.until.VerifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author chenjiandong
 * @description: TODO
 * @date 2022/10/11 17:08
 */
@RestController
@Slf4j
public class VerifyCodeController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/vercode")
    public JsonResult code(HttpServletResponse response) throws IOException {
        VerifyUtil verifyUtil = new VerifyUtil();
        Map<String, String> result = new HashMap();
        try {
            String codeKey = UUID.randomUUID().toString();
            response.setContentType("image/png");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Expire", "0");
            response.setHeader("Pragma", "no-cache");
            // 返回base64
            //写入redis缓存
            Map<String, String> mapInfo = verifyUtil.getRandomCodeBase64();
            String randomStr = mapInfo.get("randomStr");
            stringRedisTemplate.opsForValue().set(codeKey, randomStr, 60, TimeUnit.SECONDS);
            result.put("captcha", "data:image/png;base64," + mapInfo.get("img"));
            result.put("codeKey", codeKey);
        } catch (Exception e) {
            log.error(e.getMessage());
            return JsonResult.error(e.getMessage());
        }
        return JsonResult.success(result);
    }

}